Skip to content

Mocking and verifying

Niek Haarman edited this page Nov 15, 2016 · 25 revisions

This page provides some examples on how to mock classes and verify them with Mockito-Kotlin.

Creating mocks

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())

Stubbing

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

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().

Argument Matchers

Using higher-order functions, you can write very clear expectations about expected values. For example:

Kotlin:

verify(myClass).setItems(argThat{ size == 2 })

Argument Captors

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])
}

InOrder

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()
}
Clone this wiki locally