简体   繁体   中英

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?

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])

implicit formats: Formats is also passed as an argument, so mockito will need to be able to match it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM