Kotlin + Spring Boot + Mockk

Aidar Samerkhanov
Oct 4, 2018 · 2 min read
Image for post
Image for post
“coffee latte near white wireless keyboard and Apple EarPods on the table photography” by Lukas Blazek on Unsplash

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.

In this 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 Service.

That’s all!

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store