Skip to content

Verifying & Capturing

Joshua Selbo edited this page Apr 20, 2026 · 3 revisions

Note

This page is not exhaustive. Check the Mockito-Kotlin Documentation for the full API.

Verifying

Verifying behavior reads just like regular Mockito:

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

However, If you want to restrict any to a certain subclass, use:

verify(myClass).doSomething(any<MySubClass>())

Properties

You can also verify the setting of properties. For example:

interface Foo {
  var bar : String
}

@Test
fun test() {
  val foo = mock<Foo>()
  foo.bar = "test"
  verify(foo).bar = "test"
  // or you can use a setter argument
  doAnswer { it.getArgument(0) }.whenever(foo).bar = any()
}

Argument Matchers

The standard set of matchers are available: any(), eq(T), etc.

You can also use argThat to match arbitrary conditions. For example:

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

If you prefer a more natural read, you can use:

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

Both argThat and argForWhich take in a function T.() -> Boolean, where T is the type of the parameter.

If you want to do more assertions on the received argument, you can use check:

verify(myClass).setItems(check { 
  assertThat(it.size, is(2))
  assertThat(it[0], is("test"))
})

check accepts a function (T) -> Unit, and thus does not report anything back to Mockito. If you want your test to fail inside a check invocation, you should make sure the body throws an error (like assertThat or assertEquals would do).

Argument Captors

Argument Captors can be used to capture argument values for further assertions, just like in Mockito. For example:

val myCaptor = argumentCaptor<String>()
verify(myClass, times(2)).setItems(myCaptor.capture())

assertEquals(2, myCaptor.allValues.size)
assertEquals("test", myCaptor.firstValue)

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