bit*_*ver 5 testing groovy spock
我正在使用 Spock 测试框架。我有很多测试的结构与此类似:
def "test"() {
when:
doSomething()
then:
1 * mock.method1(...)
2 * mock.method2(...)
}
Run Code Online (Sandbox Code Playgroud)
我想将“then”块的代码移动到辅助方法中:
def assertMockMethodsInvocations() {
1 * mock.method1(...)
2 * mock.method2(...)
}
Run Code Online (Sandbox Code Playgroud)
然后调用这个辅助方法来消除我的规范中的代码重复,如下所示:
def "test"() {
when:
doSomething()
then:
assertMockMethodsInvocations()
}
Run Code Online (Sandbox Code Playgroud)
但是,在放入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')
Run Code Online (Sandbox Code Playgroud)
如何从我的then:块中删除重复的代码?
其实我找到了一个简单的方法来解决这个问题。我们需要做的是将辅助方法包装在一个interaction块中。
then:
interaction {
assertService()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
663 次 |
| 最近记录: |