Mockito for Objects in Scala

Good news! With the latest 1.16 release of mockito-scala, you can now mock scala objects.

To enable withObjectMocked feature, it is mandatory to create the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line:

mock-maker-inline 

Example:

object FooObject {   
  def simpleMethod: String = "not mocked!"
}

"mock" should {
  "stub an object method" in {
    FooObject.simpleMethod shouldBe "not mocked!"

    withObjectMocked[FooObject.type] {
      FooObject.simpleMethod returns "mocked!"
      //or
      when(FooObject.simpleMethod) thenReturn "mocked!"

      FooObject.simpleMethod shouldBe "mocked!"
    }

    FooObject.simpleMethod shouldBe "not mocked!"
  } 
}

See: https://github.com/mockito/mockito-scala#mocking-scala-object


Instead of mocking it, you could try spying it as follows:

val m = spy(io.Source)

Or you could mock it as follows:

val m = mock[io.Source.type]

But then how are you using Source in the class you are testing? If you had an example class like so:

class MyClass{

  def foo = {
    io.Source.doSomething //I know doSomething is not on Source, call not important
  }
}

Then in order to take advantage of mocking/spying, you'd have to structure your class like so:

class MyClass{
  val source = io.Source
  def foo = {
    source.doSomething
  }
}

And then your test would have to look something like this:

val mockSource = mock[io.Source.type]
val toTest = new MyClass{
  override val source = mockSource
}

In the Java world, static methods are the bane of mocking. In the Scala world, calls to objects can also be troublesome to deal with for unit tests. But if you follow the code above, you should be able to properly mock out an object based dependency in your class.