Spock的右位移(模拟)运算符似乎不起作用

7

这是我的Spock单元测试:

def "when favorite color is red then doSomething produces empty list of things"() {
    given:
    FizzBuzz fizzBuzz = Mock(FizzBuzz)
    fizzBuzz.name >> 'Dark Helmet'
    fizzBuzz.attributes >> [:]
    fizzBuzz.attributes["favcolor"] >> 'red'
    fizzBuzz.attributes["age"] >> '36'

    Something something = new Something(fizzBuzz)

    when:
    Whoah whoah = something.doSomething()

    then:
    !whoah.things
}

以下是 FizzBuzz 的模拟代码:

public interface FizzBuzz extends Serializable {
    Map<String, Object> getAttributes();
}

当我运行这个程序时,会得到以下结果:
java.lang.NullPointerException: Cannot invoke method rightShift() on null object

at com.commercehub.houston.SomethingSpec.when favorite color is red then doSomething produces empty list of things fail(SomethingSpec.groovy:18)

Process finished with exit code 255

第18行所指的“null对象”是指fizzBuzz或其attributes映射。 为什么呢?

2个回答

6

您正试图使用多级引用,并且>>被应用到.attributes["favcolor"]的结果上,这是空的(因为.attributes是一个空映射)。相反,只需初始化映射:

fizzBuzz.attributes >> [favcolor: 'red', age: 36]

(此外,你真的希望age是一个字符串吗?)

1
在我的情况下,我意识到我无意中声明了when块的结果。
when:
Whoah whoah = something.doSomething() >> expectedResult

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接