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.
class Button {
private var clickListener: (() -> Unit)? = null
fun setOnClickListener(listener: () -> Unit) {
clickListener = listener
}
fun performClick() {
clickListener?.invoke()
}
class NavigationView(
private val navigator: Navigator
) {
val goToParkButton = Button()
init {
goToParkButton.setOnClickListener {
navigator.navigate("Park")
}
}
}
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.
// Mock the dependency needed for navigationView
val navigator = mockk<Navigator>()
// Create the navigation view to test
val navigationView = NavigationView(navigator)
// Test the button in navigation view
navigationView.goToParkButton.performClick()
verify { navigator.navigateTo("Park") }
navigationView.goToParkButton.performClick()
// Throws as navigateTo("Park") was never called.
// MockK will mention in the error that navigateTo("Parka") was called.
verify { navigator.navigateTo("Park") }
Verifying that any mock functions is never called
verify { navigator wasNot Called }
Verifying a function is called a certain number of times
verify(exactly = 1) { navigator.navigateTo("Park") }
verify(atLeast = 1, atMost = 1) { navigator.navigateTo("Park") }
verify(atLeast = 2, atMost = 3) { navigator.navigateTo("Park") }
In the sample test will be green in the following cases:
- Function called two times
TODO: ordering
, verifyAll
, verifySequence
, verifyOrder