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

标签 java unit-testing groovy mocking spock

我在使用 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-style splitting of stubbing and mocking into two separate statements will not work

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

需要在定义mock方法的同一行定义调用次数

关于java - Spock 模拟方法实现在检查调用数时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60542724/

相关文章:

java - 在学习编程的同时学习代码约定

java - Java考试准备-递归任务

c# - 任何以我学习 Java 的方式教授 C# 的教程或书籍(命令行,没有智能感知或 VS)?

java - Google 服务冲突错误

linux - 如何在unix中获取数字记录和文件大小

python - 在 python 中有没有一种方法可以修补类似于使用 patch.dict 的列表?

.net - 如何以编程方式向 ConfigurationElementCollection 添加元素?

javascript - 当只有一个元素时,字符串数组作为字符串传递到我的 Controller

Java : GroovyClassLoader : cannot find symbol for method in Groovy Class

curry 时的 Groovy 错误