-
Notifications
You must be signed in to change notification settings - Fork 205
Mocking and verifying
This page provides some examples on how to mock classes and verify them with Mockito-Kotlin.
To find more information on how Mockito works, see the official Mockito website.
When calling mock(), you don't have to pass in the class instance anymore.
If the type can be inferred, you can just write:
val mock : MyClass = mock()If the type cannot be inferred directly, use:
val mock = mock<MyClass>()Passing a new mock as a parameter becomes:
myClass.test(mock())Mockito-Kotlin provides whenever in favor of when. Basic usage stays the same:
whenever(mock.stringValue()).thenReturn("test")Alternatively, you can pass a lambda expression to mock(). The lambda expression is of type KStubbing<T>.() -> Unit, where T is the type of the mocked class. KStubbing<T> provides a method on which takes a function T.() -> R, so you can directly call the method to mock:
val mock = mock<MyClass> {
on { stringValue() }.doReturn("test")
}doReturn is marked as an infix function, so you can use:
val mock = mock<MyClass> {
on { stringValue() } doReturn "test"
}Verifying behavior looks a lot like the original version:
verify(myClass).doSomething("test")Just as with mock(), you don't have to specify the type of any when you pass it as a parameter:
verify(myClass).doSomething(any())For generic arrays, use anyArray().
Using higher-order functions, you can write very clear expectations about expected values. For example:
verify(myClass).setItems(argThat{ size == 2 })Argument Captors can be used to capture argument values for further assertions, just like in Mockito. For example:
argumentCaptor<String>().apply {
verify(myClass).setItems(capture())
assertEquals(2, allValues.size)
assertEquals("test", allValues[0])
}In Mockito-Kotlin, inOrder can take in a lambda for easy verification:
val a = ...
val b = ...
inOrder(a,b) {
verify(a).doSomething()
verify(b).doSomething()
}