Home > Back-end >  Groovy Spock. How to verify interaction with two arguments method?
Groovy Spock. How to verify interaction with two arguments method?

Time:12-23

Trying to use Spock mocks to verify method invocation arguments. Documentation and most of the examples in the internet contain example for single argument.

How to implement capture and verification of multiple arguments in a mock method call?

interface MyAction{
  String doSomething(int first, String second);
}

// spec
def "should do something"(){
  given:
  MyAction action = Mock()

  when:
  action.doSomething(123, "abc")

  then:

  // how to verify that (first == 123) and (second == "abc") ?
}

CodePudding user response:

Just list them like you'd do for a single argument.

import spock.lang.*

class ASpec extends Specification {
    // spec
    def "should do something"(){
        given:
            MyAction action = Mock()

        when:
            action.doSomething(123, "abc")

        then:
        1 * action.doSomething(123, "abc")    
    }
}

interface MyAction{
  String doSomething(int first, String second);
}

Try it in the Groovy Web Console


Edit: an example mismatch will show which argument didn't match and why.

Too few invocations for:
            
               1 * action.doSomething(123, "abc")   (0 invocations)
            
               Unmatched invocations (ordered by similarity):
            
               1 * action.doSomething(123, 'bc')
               One or more arguments(s) didn't match:
               0: <matches>
               1: argument == expected
                  |        |  |
                  bc       |  abc
                           false
                           1 difference (66% similarity)
                           (-)bc
                           (a)bc
  • Related