By   November 17, 2018

Mocking Inner Singleton objects for Scala Tests using MockitoSugar

This is a special case of testing when you need to test a type but dependencies come in all shapes and sizes. In order to test your class, you might not have any control on the dependencies. This is specially true when your dependencies are from a third party package. In our post today, we will consider such a case.

In this example we have a dependency of a dependency with an inner singleton object. Here we have a Bike trait with a companion object. The trait has a singleton inner object Seat. The inner object has a property color.

A rider type is passed with this. As always, the rider’s favorite color is the color of his bike’s seat.

In order to test our Rider. We can simply mock Bike using MockitoSugar as it is a trait. But what about the inner object. This is a singleton. In order to make sure that getFavoriteColor always return the same color as color property of Seat inner object, we need to mock Seat. But how? MockitoSugar makes it easy to allow Singleton mocking usin g type property. Here we are plainly mocking Bike but using this mock (bike) to mock the inner object i.e. mock[bike.Seat.type]. Next we just need to set expectations and mocked return value when color property is used.

And the unit test definitely successful. May all your unit tests are also always green!!!



Here is my sbt: