The System Under Test
We’ll be stubbing this interface – one method, returning random Integer.
doReturn with Mockito-Kotlin
Now let’s create test:
We have no assertion in here – I’m just checking mock behavior manually and looking into the logs.
What’s happening here?
- Create mock with Mockito-Kotlin
- stub
random()
method fromRandomNumberProvider
withdoReturn
- return
Random.nextInt()
- Use Kotlin built-in method
repeat
- Inside
repeat
block invoke stubbed method 10 times.
Run this test and see results:

Ok – we can see, that while stubbing method with doReturn
, return value is resolved once and then each invocation gives us the same result.
Now let’s check doAnswer
.
doAnswer with Mockito-Kotlin
Exactly like in doReturn example – no assertion in here. We’ll be checking logs.
Step by step:
- Create mock with Mockito-Kotlin
- stub
random()
method fromRandomNumberProvider
withdoAnswer
- in
doAnswer
create function returningRandom.nextInt()
- Use Kotlin built-in method
repeat
- Inside
repeat
block invoke stubbed method 10 times.
And here’s the results:

Each time different number.
Stubbing method with doAnswer makes our code evaluate expression inside doAnswer
block every time it’s invoked.
Using returns and answers in MockK
The same stubbing mechanism is present in MockK:
By using returns
and answers{}
we will achieve the same behavior.
Summary
Mocking libraries such as MockK and Mockito (Mockito-Kotlin) gives us several ways of creating stubs. The most common choice is doReturn
or returns
– stubbed method will be evaluated once. If your test design requires evaluating stub each time it’s invoked, use doAnswer{}
or answers
.
Further reading
Kotlin Testing libraries in one place
https://kotlintesting.com/libraries/
Mockito-Kotlin
https://kotlintesting.com/using-mockito-in-kotlin-projects/
MockK for suspend function
https://kotlintesting.com/mocking-suspend-with-mockk/