这是我的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行引用的“空对象”是fizzBuzz
或其attributes
地图。的为什么吗
答案 0 :(得分:5)
您尝试使用多个间接级别,>>
将应用于.attributes["favcolor"]
的结果,该结果为空(因为.attributes
是一张空地图)。相反,只需初始化地图:
fizzBuzz.attributes >> [favcolor: 'red', age: 36]
(另外,你真的是说age
是一个字符串吗?)
答案 1 :(得分:1)
就我而言,我意识到我不小心声明了when
块的结果。
when:
Whoah whoah = something.doSomething() >> expectedResult