testing - 在 Spock 中,如何消除 "then" block 中的重复交互?

标签 testing groovy spock

我正在使用 Spock 测试框架。我有很多测试的结构与此类似:

def "test"() {
    when:
    doSomething()
    then:
    1 * mock.method1(...)
    2 * mock.method2(...)
}

我想将“then” block 的代码移动到辅助方法:

def assertMockMethodsInvocations() {
    1 * mock.method1(...)
    2 * mock.method2(...)
}

然后调用这个辅助方法来消除我的规范中的代码重复,如下所示:

def "test"() {
    when:
    doSomething()
    then:
    assertMockMethodsInvocations()
}

但是,当将 n * mock.method(...) 放在辅助方法中时,我无法匹配方法调用。以下示例演示:

// groovy code
class NoInvocationsDemo extends Specification {

    def DummyService service

    def "test"() {
        service = Mock()

        when:
        service.say("hello")
        service.say("world")

        then:
        assertService()
    }

    private assertService() {
        1 * service.say("hello")
        1 * service.say("world")
        true
    }

}

// java code
public interface DummyService {
    void say(String msg);
}

// [RESULT]
// Too few invocations for:
//
// 1 * service.say("hello")   (0 invocations)
//
// Unmatched invocations (ordered by similarity):
//
// 1 * service.say('hello')
// 1 * service.say('world')
//
// Too few invocations for:
//
// 1 * service.say("world")   (0 invocations)
//
// Unmatched invocations (ordered by similarity):
//
// 1 * service.say('world')
// 1 * service.say('hello')

如何从我的 then: block 中删除重复的代码?

最佳答案

其实我找到了一个简单的方法来解决这个问题。我们需要做的是将辅助方法包装在 interaction block 中。

then:
interaction {
    assertService()
}

关于testing - 在 Spock 中,如何消除 "then" block 中的重复交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38865023/

相关文章:

selenium - 什么是 Selenium 包装器?

Jenkins 核心 API 文档 : How to navigate to find detailed properties and methods?

spring-boot - Spring Boot + Eureka Server + Hystrix with Turbine : empty turbine. 流

gradle - 如何在编写目标时使用/引用 gradle 插件属性?

java - 从 Jenkins 运行 Android 模拟器以使用 Robotium 运行 Junit 测试

go - 运行测试时如何丢弃打印输出

maven - Gradle 不会将系统属性传递给测试类

unit-testing - 模拟 domainInstance.validate() 的返回值

eclipse - 在 Eclipse 中突出显示 Spock 测试关键字

ruby-on-rails - 是否可以使用 Cucumber 来测试现有的 Rails 应用程序?