How to Have a MockK Spy Do Nothing When a Specific Method Is Called

My team has recently been migrating mocking in Kotlin unit tests from Mockito to MockK. When I came across a Mockito spy that was configured to do nothing when a specific method was called...

// 1) arrange
val spy = spy(viewModel)
val bitmap = mock(Bitmap::class.java)
val event = DoneClick(bitmap)
doNothing().`when`(spy).handleDoneClick(bitmap)

// 2) act
spy.handleEvent(event)

// 3) assert
verify(spy).handleDoneClick(bitmap)

...I expected there to be a comparable doNothing method in MockK. When I couldn't find one, I asked a teammate, and he recommended that I return Unit:

// 1) arrange
val spy = spyk(viewModel)
val bitmap = mockk<Bitmap>()
val event = DoneClick(bitmap)
every { spy.handleDoneClick(bitmap) } returns Unit // do nothing

// 2) act
spy.handleEvent(event)

// 3) assert
verify { spy.handleDoneClick(bitmap) }

This worked as expected. The spy can thus confirm that calling the viewModel's handleEvent() method results in a call to the viewModel's handleDoneClick() method, without the test causing the internals of the handleDoneClick() to actually be executed. This is a simple way to verify flow without making unwanted calls to external resources.

comments powered by Disqus