Spock: makes fun of a method with varargs

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

Problem:

The Spock structure does not validate the arguments of the mocking method with varargs.

Steps to play:

1) Create a Groovy Project

2) Create an interface:

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

3) Create a test 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 to run the test

Effect: the test fails with the error "incorrect number of arguments".

Temporary solution:

the readLine call is replaced by:

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

then the test succeeds.

Question:

is there a better way to “explain” that the last argument to the function being mocked is vararg and, as such, can it be omitted?

+3
1

varargs Mock() GroovyMock().

, Spock Spock Mock Groovy GroovyMock, GroovyMock.

Mock GroovyMock :

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

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

        then:
            result == "hey"
+6

All Articles