Writing Beautiful Tests in Kotlin


2 min read


Table of contents

Maven Central

Mockito-Kotlin is a small library that provides helper functions to work with Mockito in Kotlin. It is a great choice for Java devs already familiar with Mockito. Mockito is a widely used Java testing framework that helps create mock objects for unit testing. It allows developers to isolate code from dependencies, define behaviors, and verify method calls.

Creating Mocks

๐Ÿคฎ Legacy Java Mockito syntax. Don't do it.

val mock = mock(

๐Ÿ˜ Now, don't these look better?

val mock: MyDependency = mock()
val mock = mock<MyDependency>

๐Ÿ˜ Creating mocks inline can be quite handy!

val subject = MyClass(mock())


๐Ÿคฎ Mockito stubbing method when requires backticks since when is a reserved keyword in Kotlin.


๐Ÿ™‚ Mockito-Kotlin adds a whenever alias so you don't have to type or look at those ugly backticks.


๐Ÿ˜ Even better, Mockito-Kotlin adds a new stubbing DSL! It can be used when creating a new mock and on existing mocks.

val mock: MyDependency = mock {
    on { foo() } doReturn { "default" }
    on { bar() } doReturn { 1 }

fun test() {
    mock.stub {
        on { foo() } doReturn { "override" }

๐Ÿ˜ It even supports stubbing of suspend functions (Kotlin Coroutines).

mock {
    onBlocking { apiCall() } doReturn "Hello World"