4
votes

Given the following code that mocks a Scala class with Mockito, I get an error and cannot compile:

import org.mockito.Mockito._

class Testeable {
  def fun1 = 1
  def fun2 = 2
}

object test {

  def getMock = {
      val testMock = mock[Testeable]  // <-- this line throws the error
      when(testMock.fun1).thenReturn(3)
      testMock
  }

}

Error is:

ambiguous reference to overloaded definition, both method mock in object Mockito of type (x$1: Class[common.Testeable], x$2: org.mockito.MockSettings)common.Testeable and method mock in object Mockito of type (x$1: Class[common.Testeable], x$2: org.mockito.stubbing.Answer[_])common.Testeable match expected type ?

I just mocked a class, what's ambiguous?

1
mock(classOf[Testeable])? It expects a java.lang.Class, and classOf method provides it, just like in Java you could do Testeable.class.insan-e
Correction, class Any has a getClass method, so for non-generic classes like Int, String etc you could use getClass and for generic ones like List[T] you use classOf[List[_]] from Predef...insan-e
thanks, it worked using mock(classOf[Testeable])ps0604
@insan-e mocking an Int sounds like a wonderful idea! :)Dima

1 Answers

4
votes

You can't use mockito directly like this (you can use it, but can't make it look this pretty). Take a look at scala test library. The simplest thinng you can do to solve your immediate problem with it is just mix in MockitoSugar into your test class instead of importing Mockito._, then mock[Foo] will just work as you expect it to. There are many other things that library offers to write idiomatic test code in scala, so you should read through some docs and examples on that site I linked to.