我对使用Spock的模拟方法有疑问。下面是我正在使用的代码。无需任何更改,一切都可以正常工作-模拟实现正常工作并返回“模拟”字符串。但是,如果我取消对调用检查(3 * notifier.test())的注释,则方法notify的模拟实现不会被调用,并且测试会失败,因为通知者模拟返回null。为什么会这样?
class Aaaaa extends Specification {
class Notifier {
def test() {
println("Called in impl...")
return "impl"
}
}
def "Should verify notify was called"() {
given:
Notifier notifier = Mock(Notifier)
notifier.test() >> {
println("Called in mock...")
return "mock"
}
when:
notifier.test()
notifier.test()
def result = notifier.test()
then:
// 3 * notifier.test()
result == "mock"
}
}
Mockito样式的存根和嘲笑分为两个单独的部分声明不起作用
需要在定义模拟方法的同一行中定义调用次数
为关注者发布实际答案:
def "Should verify notify was called"() {
given:
Notifier notifier = Mock(Notifier)
notifier.test()
when:
notifier.test()
notifier.test()
def result = notifier.test()
then:
3 * notifier.test() >> {
println("Called in mock...")
return "mock"
}
result == "mock"
}