Spock:用可变参数模拟一种方法 [英] Spock: mock a method with varargs

查看:866
本文介绍了Spock:用可变参数模拟一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是这个Q& A的分支:测试Groovy类使用System.console()



问题:



Spock框架用可变参数错误地检查了模拟方法的参数。



重现步骤:

1)创建groovy项目2)创建一个接口:

  interface IConsole {
String readLine(String fmt,Object ... args)
}



<3>创建spock测试:

  class TestInputMethods extends Specification {

def 'test console input'(){
setup:
def consoleMock = GroovyMock(IConsole)
1 * consoleMock.readLine(_)>> 'validResponse'

当:
//在这里,我们得到异常错误的参数数量:
def testResult = consoleMock.readLine('testPrompt')

then:
testResult =='validResponse'
}
}



)尝试运行测试
$ b

效果:测试失败,出现异常参数数量错误。





调用readLine替换为:

  def testResult = consoleMock.readLine('testPrompt',[] as Object [])

然后测试成功完成。



问题:

有一个更好的方法来解释spock的模拟函数的最后一个参数是可变的,因此,它可以被省略?

解决方案

您可以避免使用Mock()而不是GrooyMock()来解释可变参数。



一般来说,在编写Spock规范时,除非您打算使用GroovyMock的一些独特功能,否则您应该更喜欢spock的Mock对象而不是Groovy的GroovyMock。 参考资料



为GroovyMock交换模拟允许您避免详细的Object params:

  setup :
def consoleM = Mock(IConsole)
1 * consoleM.readline(_)>> hey

when:
def result = consoleM.readline(prompt)

then:
result ==hey


This question is an offshoot of this Q&A: Test Groovy class that uses System.console()

The problem:

Spock framework incorrectly checks arguments of the mocked method with varargs.

Steps to reproduce:

1) Create groovy project

2) Create an interface:

interface IConsole {
  String readLine(String fmt, Object ... args)
}

3) Create spock test:

class TestInputMethods extends Specification {

  def 'test console input'() {
    setup:
    def consoleMock = GroovyMock(IConsole)
    1 * consoleMock.readLine(_) >> 'validResponse'

    when:
    // here we get exception "wrong number of arguments":
    def testResult = consoleMock.readLine('testPrompt')

    then:
    testResult == 'validResponse'
  }
}

4) try running the test

Effect: test fails with exception "wrong number of arguments".

Workaround:

call to readLine is replaced with:

def testResult = consoleMock.readLine('testPrompt', [] as Object[])

then test completes successfully.

Question:

is there a better way to "explain" spock that the last argument of the mocked function is vararg and, as such, it could be omitted?

解决方案

You can avoid having to explain the vararg by using Mock() instead of GrooyMock().

In general, when writing Spock specifications you should prefer spock's Mock object over groovy's GroovyMock unless you intend to use some of the unique functionality from GroovyMock. Reference

Swapping out Mock for GroovyMock allows you to avoid the verbose Object params:

        setup:
            def consoleM = Mock(IConsole)
            1 * consoleM.readline(_) >> "hey"

        when:
            def result = consoleM.readline("prompt")

        then:
            result == "hey"

这篇关于Spock:用可变参数模拟一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆