Search code examples
scalamockitoscalatest

MatchersException despite using any() and eq() in Test [Scala]


I have a method with the following signature:

def fetchCode[T](
      seconds:        Int,
      client:         String,
      scope:          String,
      data:           T,
      retryLimit:     Int = 10
  )(implicit formats: Formats): String

and in my tests I'm trying to mock it as:

val accessCode:           String = "CODE"
when(
        mockService
          .fetchCode[String](
            any[Int],
            any[String],
            Matchers.eq(partner.name),
            any[String],
            any[Int]
          )
      ).thenReturn(accessCode)

verify(mockService).fetchCode(
        Matchers.any(),
        Matchers.any(),
        Matchers.eq(partner.name),
        Matchers.any(),
        Matchers.any()
      )

Upon running this test, I still see the following errors:

Invalid use of argument matchers!
6 matchers expected, 5 recorded:
This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

I don't see why this error crops up - I only need 5 matchers - one each for an argument, why are 6 expected?


Solution

  • As @Levi mentioned in his answer, you need to address all arguments the method gets, in order to use mocks. As you can see as part of your error message:

    6 matchers expected, 5 recorded
    

    What you need to do is to add any[Formats] in new paranthesis (exactly like your original method), and provide their the mock value:

    when(
    mockService
      .fetchCode[String](
        any[Int],
        any[String],
        Matchers.eq(partner.name),
        any[String],
        any[Int]
      )(any[Formats])
    ).thenReturn(accessCode)
    
    verify(mockService).fetchCode(
    Matchers.any(),
    Matchers.any(),
    Matchers.eq(partner.name),
    Matchers.any(),
    Matchers.any()
    )(any[Formats])