Spock-模拟方法不同的参数和不同的返回值

时间:2019-02-01 12:08:28

标签: groovy spock

given:
def someService = Mock(SomeService)

1 * someService.processInput(argument1) >> output1
1 * someservice.processInput(argument2) >> output2

如何在一个带有不同参数的with子句的语句中使用它。例如:

2 * someService.processInput(argument1) >>> [output1, output2]

1 个答案:

答案 0 :(得分:0)

我相信,当前在Spock中不可能以您期望的优雅的方式进行。我只提出了以下内容:

def args = [arg1, arg2]
2 * service.processInput({ it == args.removeAt(0) }) >>> [out1, out2]

不确定它是否符合您的期望。以下是测试此方法的完整规格

class SOSpec extends Specification {
    def "mock a method different arguments and different return values"() {
        when:
        def arg1 = "F"
        def arg2 = "B"
        def out1 = "Foo"
        def out2 = "Bar"
        def service = Mock(SomeService) {
            def args = [arg1, arg2]
            2 * processInput({ it == args.removeAt(0) }) >>> [out1, out2]
        }

        then:
        service.processInput(arg1) == out1
        service.processInput(arg2) == out2
    }
}