spock:这个嘲弄有什么不对

时间:2014-01-05 22:53:59

标签: mocking spock

给出以下界面:

interface Bundle {
    String getName()

    String getVersion()
}

以下方法:

String log(Bundle b) {
    return "${b.getName()}: ${b.getVersion()}"
}

这个spock测试失败了:

def "my test"() {
        given:
        def bundle = Mock(Bundle)
        bundle.getName() >> "name"
        bundle.getVersion() >> "1.0.0"

        when:
        def x = log(bundle)

        then:
        x == "name: 1.0.0"
        1 * bundle.getName()
        1 * bundle.getVersion()

    }

这是错误:

condition not satisfied:
x == "name: 1.0.0"
| |
| false
| 8 differences (27% similarity)
| n(ull): (null-)
| n(ame): (1.0.0)
null: null

如果我删除了两个验证(1 * bundle.getName()1 * bundle.getVersion()),则测试将为绿色。

知道我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:2)

同一个调用的模拟和存根需要一起发生(在giventhen块中):

...
then:
1 * bundle.getName() >> "name"
1 * bundle.getVersion() >> "1.0.0"
x == "name: 1.0.0"
Combining Mocking and Stubbing中的{p> Spock Reference Documentation更详细地解释了这一点。

另一种方法是摆脱模仿部分(1 * bundle.getName()等),这可能不是那里必要/有用的。

相关问题