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

冷暖自知 提交于 2019-12-07 02:23:53

问题


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.


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/26737268/mock-out-return-of-a-method-base-on-the-number-of-invocation-only-in-spock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!