Wednesday, March 14, 2018

Scala Mockito workarounds

I was pleased to have figured out this org.mockito.stubbing.Answer solution (lines 4-8) to a null logger inside my Scala class.

 Also, that you can tell a mock to call the real method you are trying to test (line 9).

 1  @Test
 2  def testNullHandlerCallsStart(): Unit = {
 3    predictor.setHandler(null)
 4    when(predictor.log == null).thenAnswer(new Answer[Logger] {
 5      def answer(invocation: InvocationOnMock): Logger = {
 6        LoggerFactory.getLogger("Predictor")
 7      }
 8    })
 9    when(predictor.enqueueEvent(any())).thenCallRealMethod()
10    val deactivation = new UnitUpdateNotification(unit, unit.updateStatus(Status.INACTIVE, Action.DEACTIVATED, "damaged", "user"))
11    callback.handle(deactivation)
12    verify(predictor).enqueueEvent(any(classOf[Event]))
13  }

One thing, I had to make the logger inside my Predictor class publicly visible for it to work.