【问题标题】:In Spock, how can I eliminate duplicated interactions from the "then" block?在 Spock 中,如何消除“then”块中的重复交互?
【发布时间】:2016-08-10 05:37:44
【问题描述】:

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

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

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

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: 块中删除重复的代码?

【问题讨论】:

  • 很好,但是您有问题吗?
  • 此功能无法使用,因为n * mock.method(...) 是语法糖。如果您在另一种方法中使用它,它将无法按预期工作。它们不会捕获任何方法调用。 @ScaryWombat

标签: testing groovy spock


【解决方案1】:

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

then:
interaction {
    assertService()
}

【讨论】:

  • 不知道。不错!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
  • 2022-01-04
  • 2016-05-03
  • 2014-07-15
  • 2021-08-06
相关资源
最近更新 更多