Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mock out return of a method base on the number of invocation only in spock

Is it possible to mock out the return value of a method in spock based on the nth time it was called? Note that I don't want to specify the parameters passed in because it does not matter for a specific test case.

For example, for the first call it should return x, for the second call it should return y.

like image 739
froi Avatar asked Nov 04 '14 14:11

froi


People also ask

How do you mock a method in Spock?

In Spock, a Mock may behave the same as a Stub. So we can say to mocked objects that, for a given method call, it should return the given data. So generally, this line says: itemProvider. getItems will be called once with ['item-'id'] argument and return given array.

Can you use Mockito with Spock?

We can use Mockito stubbing, not Spock's. It works well! To help you with spock mocks, Spock also has annotations to setup mocks from the Subject Collaborator extension: github.com/marcingrzejszczak/…

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.

How do you mock another method in the same class which is being tested?

Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows. Mockito.


1 Answers

Yes it is possible.

someObject.someMethod(*_) >>> [ 'x', 'y' ]

It will return x on first invocation and y on second invocation of the method.

Example:

void "test something"() {
    given:
    def sample = Mock(Sample) {
        someMethod(_) >>> ['Hello', 'World']
    }

    expect:
    sample.someMethod('foo') == 'Hello'
    sample.someMethod('bar') == 'World'
}

class Sample {
    def someMethod(def a) {
        return a
    }
}
like image 167
dmahapatro Avatar answered Sep 30 '22 04:09

dmahapatro