Mockito-Kotlin is an interesting example of a testing library that makes use of Kotlin features to provide a custom testing DSL that makes mocking and testing feel very fluent and readable.
In the following code snippet, you can see an example of using Mockito-Kotlin to mock the behavior of the GreetingProvider class:
@Test
fun `test with mockito-kotlin`() {
val mockGreeter = mock<SimpleGreeter> {
on { getGreeting() } doReturn "Hey there!"
on { getMessage() } doReturn "You're great!"
}
}
Notice that this test code is making heavy use of lambdas and higher-order functions.
The mock() function is passed a lambda within which that mocked object can have its behavior configured. This configuration becomes very human readable when using functions such as on() and doReturn(), which allow us to define which values should be returned when specific methods are invoked. This allows us to write test code that reads very similarly to how we might verbally describe the testing behavior.
Once your mock has been configured, you are then free to confirm any state and behavior you wish to verify. In this example, we can invoke the getGreeting() method and then verify that getGreeting() was called on one occasion:
@Test
fun `test with mockito-kotlin`() {
val mockGreeter = mock<SimpleGreeter> {
on { getGreeting() } doReturn "Hey there!"
on { getMessage() } doReturn "You're great!"
}
mockGreeter.getGreeting()
verify(mockGreeter, times(1)).getGreeting()
}
With Mockito-Kotlin, you can write fluent Kotlin test code that is easy to read and observes common Kotlin idioms. This is possible thanks to the custom DSL that Mockito-Kotlin provides, which enables the Kotlin-idiomatic creation and configuration of mocked objects. If you're writing test code in Kotlin, Mockito-Kotlin is potentially a very useful tool to explore.