【问题标题】:Spock rightShift (mocking) operator apparently not workingSpock rightShift(模拟)运算符显然不起作用
【发布时间】:2016-04-17 02:24:13
【问题描述】:

这是我的 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 映射。 为什么?

【问题讨论】:

    标签: java unit-testing groovy spock


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您正在尝试使用多个间接级别,并且&gt;&gt; 被应用于.attributes["favcolor"] 的结果,该结果为空(因为.attributes 是一个空映射)。相反,只需初始化地图:

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

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

      【讨论】:

        猜你喜欢
        • 2016-08-20
        • 2016-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-21
        相关资源
        最近更新 更多