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?
The main difference between Spock and JUnit is in breadth of capabilities. Both frameworks can be used for unit testing. However, Spock offers much more — including mocking and integration testing. JUnit requires a third party library for mocking.
6. Spying Classes in Spock. Spies provide the ability to wrap an existing object. This means we can listen in on the conversation between the caller and the real object but retain the original object behavior. Basically, Spy delegates method calls to the original object.
As you can see in below Spock Test example, @Unroll annotation are used in some features, By putting @Unroll annotation on the feature. it means an iteration is required on feature and on each iteration values given in where block get substituted by its value and leading hash sign ( # ), to refer to data variables.
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With