21

I need to check if a method was not invoked in my unit tests. This is an example test I did that checks if the method was invoked and it works perfectly fine:

@Test
fun viewModel_selectDifferentFilter_dispatchRefreshAction() {
    val selectedFilter = FilterFactory.make()
    val event = GroceriesAisleFiltersUiEvent.SelectFilter(
        filter = selectedFilter,
        refreshListAction = mockk()
    )
    every { event.refreshListAction(selectedFilter) } just runs
    viewModel.dispatchViewAction(event)
    verify { event.refreshListAction(selectedFilter) }
}

For that I'm using the mockk's verify function to check if the method is being invoked.

Is there a way to check, using mockk, that this method has not been invoked? In short I need to complete the code below with this check in place of the comment:

@Test
fun viewModel_selectSameFilter_notDispatchRefreshAction() {
    val selectedFilter = viewModel.viewState.value.selectedFilter
    val event = GroceriesAisleFiltersUiEvent.SelectFilter(
        filter = selectedFilter,
        refreshListAction = mockk()
    )
    every { event.refreshListAction(selectedFilter) } just runs
    viewModel.dispatchViewAction(event)
    // TODO: verify if method's not invoked
}
Pierre Vieira
  • 2,252
  • 4
  • 21
  • 41

1 Answers1

38

If you want to verify that your method was not called, you can verify that it was called exactly 0 times:

verify(exactly = 0) { event.refreshListAction(any()) } 

Or, in this case where your event.refreshListAction is the mock, you can equivalently write the following to verify that the mock was not called at all:

verify { event.refreshListAction wasNot called }
Karsten Gabriel
  • 3,115
  • 6
  • 19
  • this doesn't work with a mocked navController. Edit: So, for some reason, only the first one works with navController and not the second one. – Muhammad Sarim Mehdi Jan 13 '23 at 22:37
  • Can confirm this. First works, second doesn't. – spyro Jan 24 '23 at 17:12
  • 1
    In the second case it should be using :: `event::refreshListAction` – Arnold Feb 08 '23 at 15:03
  • 4
    verify { event.refreshListAction wasNot called } cannot be used with methods. wasNot can only be used for checking that a mock as a whole was not called. It cannot be used for checking that a method was not called. – Johan Paul Mar 15 '23 at 12:48
  • 1
    @JohanPaul Yes, please note the line `refreshListAction = mockk()` in the question. `event.refreshListAction` is not a method of the mock, but it is the mock. – Karsten Gabriel Mar 15 '23 at 20:38