Search code examples
scalamockitoscalatestscala-generics

When using scalatest with mockito, scalatest throws strange exception


I need help with scalatest and mockito. I want to write test for a simple method with generic:

trait RestClient {
  def put[T: Marshaller](url: String, data: T, query: Option[Map[String, String]] = None) : Future[HttpResponse]
}

my test class:

class MySpec extends ... with MockitoSugar .... {
  ...
  val restClient = mock[RestClient]
  ...
  "Some class" must {
    "handle exception and print it" in {
      when(restClient.put(anyString(), argThat(new SomeMatcher()), any[Option[Map[String, String]])).thenReturn(Future.failed(new Exception("Some exception")))
      ... 
    }
  }
}

when I run test, it throws following exception:

Invalid use of argument matchers!
4 matchers expected, 3 recorded:

So, why it asks 4 matchers, if my method has only 3 parameters? Is it because of generic?

versions:

  • scala 2.11.7
  • scalatest 2.2.4
  • mockito 1.10.19

Solution

  • This is because the following notation

    def put[T: Marshaller](a: A, b: B, c: C)
    

    is equivalent to

    def put[T](a: A, b: B, c: C)(implicit m: Marshaller[T])
    

    So you need to pass in a matcher for the marshaller:

    put(anyA, anyB, anyC)(any[Marshaller[T]])