给定以下界面:
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()
),测试将为绿色。
知道我的代码有什么问题吗?
最佳答案
同一调用的模拟和 stub 需要同时发生(在 given
或 then
block 中):
...
then:
1 * bundle.getName() >> "name"
1 * bundle.getVersion() >> "1.0.0"
x == "name: 1.0.0"
Combining Mocking and Stubbing在 Spock Reference Documentation更详细地解释了这一点。
另一种方法是去掉模拟部分(1 * bundle.getName()
等),这在这里可能不是那么必要/有帮助。
关于mocking - spock:这个 mock 有什么问题吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20940287/