Spock模拟方法实现在检查调用次数时不起作用

问题描述 投票:0回答:2

我对使用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"
    }
}
java unit-testing groovy mocking spock
2个回答
0
投票

Mockito样式的存根和嘲笑分为两个单独的部分声明不起作用

来自文档:http://spockframework.org/spock/docs/1.0/interaction_based_testing.html#_combining_mocking_and_stubbing

需要在定义模拟方法的同一行中定义调用次数


0
投票

为关注者发布实际答案:

    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"
    }
© www.soinside.com 2019 - 2024. All rights reserved.