mocking - spock:这个 mock 有什么问题吗

标签 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()),测试将为绿色。

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

最佳答案

同一调用的模拟和 stub 需要同时发生(在 giventhen block 中):

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

Combining Mocking and StubbingSpock Reference Documentation更详细地解释了这一点。

另一种方法是去掉模拟部分(1 * bundle.getName() 等),这在这里可能不是那么必要/有帮助。

关于mocking - spock:这个 mock 有什么问题吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20940287/

相关文章:

java - 如何通过 Kotlin Gradle 和 -D 为我的测试提供系统属性

unit-testing - dotnet 核心的无约束隔离(模拟)框架

node.js - 用 Jest 模拟 new Function()

java - 如何测试一个方法及其两个助手之间的交互?

java - 在方法中模拟新对象的创建

testing - 当由 CompletableFuture 运行时,在 Spock 的 Mock 等待中休眠

grails - Spring Boot、GORM 和单元测试

java - Mockito 模拟无法正常工作

PHPUnit模拟父方法

c# - 在为单元测试创​​建模拟时,我们是否在自欺欺人?