1. Overview

In this quick tutorial, we’ll learn how to use Mockk to verify that a method wasn’t invoked. We’ll explore two of Mockk’s features.

2. Mock Target Setup

To begin with, let’s create a mock of a Runnable:

@Test
fun `Verify a mock was not called`() {
    val myMock: Runnable = mockk()
    every { myMock.run() } answers { throw RuntimeException() }
}

3. Verification Using verify(exactly = 0)

The most precise way to verify that a method on our mock wasn’t executed is to assert that this method from the mock should have been called exactly zero times.

To transform this assertion into actual code, we’ll use Mockk’s verify() method, passing 0 as the argument:

@Test
fun `Verify a mock was not called`() {
    val myMock: Runnable = mockk()
    every { myMock.run() } answers { throw RuntimeException() }

    verify(exactly = 0) { myMock.run() }
}

4. Verification Using verify { mock wasNot called }

Sometimes we don’t need that much preciseness. Having more information inside a test function leads to cluttered information, and we want to keep it as simple as possible. We want to make a simpler assertion – this mock shouldn’t have been used at all.

The verify() function has a special syntax that we can use to assert exactly this by using wasNot in addition to called or Called (same behaviour).

Let’s see how we could adapt our previous test to use this alternative instead:

@Test
fun `Verify a mock was not called`() {
    val myMock: Runnable = mockk()
    every { myMock.run() } answers { throw RuntimeException() }

    verify { myMock wasNot Called }
}

5. Conclusion

In this article, we learned the two main ways to verify that a mock object created with Mockk didn’t execute a behaviour.

As always, the code used in the tutorial is available over on GitHub.

Comments are closed on this article!