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

1

12

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.

Prieto answered 4/11, 2014 at 14:12 Comment(2)
Quite strange requirement. It isn't possible out of the box, what You need/want to achieve? What is the scenario?Select
@Select I have a service method that I iterate over until that method returns a specific value, now I just need to verify if the iterating process/ loop works as expected.Prieto
C
18

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
    }
}
Cloak answered 4/11, 2014 at 14:52 Comment(1)
thank you!! this is what i needed too for my testPlunger

© 2022 - 2024 — McMap. All rights reserved.