代码之家  ›  专栏  ›  技术社区  ›  Yan Khonski

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

  •  0
  • Yan Khonski  · 技术社区  · 6 年前
    given:
    def someService = Mock(SomeService)
    
    1 * someService.processInput(argument1) >> output1
    1 * someservice.processInput(argument2) >> output2
    

    如何在一个声明中 with 具有不同参数的子句。例如:

    2 * someService.processInput(argument1) >>> [output1, output2]
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Dmitry Khamitov    6 年前

    我相信现在在斯波克不可能像你期望的那样优雅。我只想到了如下几点:

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