Verify that functions were called

    Using verify to verify that a function was called looks a lot like using every for stubbing. A simple example is to call a method and immediately check that it was called.

    Similar to stubbing with every, verify starts a verification block and uses anonymous functions and to define what will be verified. verify supports the same argument matchers as every, along with a few .

    In the previous simple example, verification isn’t very helpful as it just checks that the previous line ran. Verification becomes more useful when you are testing other classes, that depend on mocked instances. Let’s start testing a button.

    1. class Button {
    2. private var clickListener: (() -> Unit)? = null
    3. fun setOnClickListener(listener: () -> Unit) {
    4. clickListener = listener
    5. }
    6. fun performClick() {
    7. clickListener?.invoke()
    8. }
    9. class NavigationView(
    10. private val navigator: Navigator
    11. ) {
    12. val goToParkButton = Button()
    13. init {
    14. goToParkButton.setOnClickListener {
    15. navigator.navigate("Park")
    16. }
    17. }
    18. }

    A test for the above NavigationView class should check that clicking the goToParkButton tells the navigator to go to the park. If the navigator doesn’t record where it goes, then it can be difficult to check that the button does its job correctly. This is a scenario where MockK can shine.

    1. // Mock the dependency needed for navigationView
    2. val navigator = mockk<Navigator>()
    3. // Create the navigation view to test
    4. val navigationView = NavigationView(navigator)
    5. // Test the button in navigation view
    6. navigationView.goToParkButton.performClick()
    7. verify { navigator.navigateTo("Park") }
    1. navigationView.goToParkButton.performClick()
    2. // Throws as navigateTo("Park") was never called.
    3. // MockK will mention in the error that navigateTo("Parka") was called.
    4. verify { navigator.navigateTo("Park") }

    Verifying that any mock functions is never called

    1. verify { navigator wasNot Called }

    Verifying a function is called a certain number of times

    1. verify(exactly = 1) { navigator.navigateTo("Park") }
    2. verify(atLeast = 1, atMost = 1) { navigator.navigateTo("Park") }
    1. verify(atLeast = 2, atMost = 3) { navigator.navigateTo("Park") }

    In the sample test will be green in the following cases:

    1. Function called two times

    TODO: ordering, verifyAll, verifySequence, verifyOrder

    Confirming all calls were verified