Search code examples
scalamockitoscalatest

Simple use of Mockito AnyMap is not working


Why does anyMap not work here in this simple case? I get func1 cannot be matched with this signature?

case class foo() {def func1 (m: Map[Int, Int]) = m.size }

case class SomeTest extends SomeSpec MockitoSugar with MustMatchers {
   it("checks size ") { fixture =>
      val spyfoo = spy(foo())
      doReturn(5).when(spyfoo).func1(anyMap())}

I get the func1 cannot be recognized with this signature


Solution

  • Disclaimer; I don't use ScalaTest, but as it appears that Mockito functionality is provided as-is, you should be able to use anything from the Matchers class.

    However the provided anyMap() and anyMapOf[K,V] functions are matchers for java.util.Map and so won't match your func1 method signature which (unless you've explicitly brought in java.util.Map) is expecting a scala.collection.immutable.Map[Int,Int].

    The easiest way around this would seem to be using the generic any[T] matcher, which is very loose, but does what you need.

    There are more problems though - why are you spy()ing on an object you own? And why are you trying to return a Map in your mocked behaviour for func1 when it takes a Map and returns an Int?

    This compiles and works for me:

    import org.mockito.{Matchers, Mockito}
    
    val mockFoo = Mockito.mock(classOf[Foo])
    
    Mockito.when(mockFoo.func1(Matchers.any(classOf[Map[Int, Int]]))).thenReturn(1)
    
    ...