Table of contents
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(MyDependency::class.java)
๐ 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())
Stubbing
๐คฎ Mockito stubbing method when
requires backticks since when
is a reserved keyword in Kotlin.
`when`(mock.foo()).doReturn(null)
๐ Mockito-Kotlin adds a whenever
alias so you don't have to type or look at those ugly backticks.
whenever(mock.foo()).doReturn(null)
๐ 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 }
}
@Test
fun test() {
mock.stub {
on { foo() } doReturn { "override" }
}
}
๐ It even supports stubbing of suspend functions (Kotlin Coroutines).
mock {
onBlocking { apiCall() } doReturn "Hello World"
}