Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 299
bitdancer Avatar asked Aug 10 '16 05:08

bitdancer


People also ask

Is Spock better than JUnit?

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.

What is Spy in Spock?

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.

What is @unroll in groovy?

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.


1 Answers

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()
}
like image 128
bitdancer Avatar answered Nov 25 '22 17:11

bitdancer