Kotlin + Spring Boot + Mockk
I once needed to create tests for a Spring Boot controller class. It was a Kotlin project and all of the tests used the Mockk library, one of the best mocking libraries, which is developed by Oleksiy Pylypenko.
So I decided to get rid of the Mockito library, which Spring Boot brings to the project, and use Mockk instead.
Let’s see how I achieved this.
For example, we have the following Controller class:
And a Service class to create a personalized greeting:
Let’s add the Mockk dependency and exclude Mockito. In this case I use the Gradle Kotlin DSL file.
Now we need to create a test to verify the behavior of our API endpoint.
ControllerTest class we use
@ExtendWith annotation from JUnit 5 and
@WebMvcTest from Spring Boot to use the MockMvc class to perform requests.
We cannot use the
@MockBean annotation because it uses Mockito. So we need to create a Spring configuration where we create a mock for the
Service class. This could be achieved by creating a nested class with
@TestConfiguration annotation where we create a bean with a mock for
Now we can use the usual Mockk functions to specify the required behavior.
The source code can be downloaded from GitHub: https://github.com/Darych/springbootmockk