Spock rightShift(模拟)运算符显然不起作用

时间:2016-01-12 12:51:08

标签: java unit-testing groovy spock

这是我的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地图。的为什么吗

2 个答案:

答案 0 :(得分:5)

您尝试使用多个间接级别,>>将应用于.attributes["favcolor"]的结果,该结果为空(因为.attributes是一张空地图)。相反,只需初始化地图:

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

(另外,你真的是说age是一个字符串吗?)

答案 1 :(得分:1)

就我而言,我意识到我不小心声明了when块的结果。

when:
Whoah whoah = something.doSomething() >> expectedResult