bitweaver bitweaver - 3 months ago 31
Groovy Question

In Spock, how can I eliminate duplicated interactions from the "then" block?

I am using the Spock testing framework. I have a lot of tests with a structure similar to this:

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


I want to move the code of the "then" block to a helper method:

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


Then invoke this helper method to eliminate the code duplications in my Specification as follows:

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


However, I am unable to match method invocations when placing
n * mock.method(...)
in a helper method. The following example demonstrates:

// 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')


How can I remove the duplicated code from my
then:
block?

Answer

Actually I found an easy way to solve this problem. What we need to do is wrapping helper methods in an interaction block.

then:
interaction {
    assertService()
}