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.
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.
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/…
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.
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.
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
}
}
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