Integration testing with Mockito and Spring Boot

Within this post, I show you how to setup properly a Unit Test in Spring Boot performing HTTP requests with Mockito. In this case, I’m testing directly against data to be placed into the model, but a similar test could be written for checking a REST API.

Sometimes testing web access with Spring Boot can be tricky. There are some specific annotations to be used, being the configuration to use maybe the most important one.

Maven configuration

First, you will need to include the corresponding dependency in your Spring Boot application. In my case and using Maven it will be something like this:

This is the dependency provided by Spring Boot guys containing even Mockito in it. As usual, we want the dependency only for test purposes so we set the scope to test .

The test case

The scenario is a web page that is going to be shown when doing a specific request. We’re expecting some data in the model that later will be used and rendered in the HTML, in this case using Thymeleaf (does not matter for the test).

Basically, we want to test the controller and view so we are going to mock the service to return some predefined data.

Pay attention here to the highlighted lines since they are the key for this to work:

  • @WebAppConfiguration  is a specific annotation for integration tests (check Javadoc here). It tells the framework to load a WebApplicationContext .
  • @SpringApplicationConfiguration  annotation is used to pass a specific configuration for the test. In this case, I have created a separated class for that but an inner class could also be used. This is really important because if you don´t use a different configuration for testing all the default beans in your Spring Boot app are going to be loaded.

So now let’s see what this specific configuration for testing contains:

Easy. Just injecting the controller with a service mock. It’s in the Unit Test where we use Mockito to pass the expected values, this way we can reuse this configuration class.

Another valid option would be creating profiles, this way the configuration would be taken automagically. But this is another story, maybe for next post 😉

Want to know more about proper Unit Testing and Integration Testing with Spring Boot?

Related Posts

A practical book about Microservices Microservices are getting very popular these days. This type of software architecture has a lot of advantages like flexibility and ease at scale. Mapp...
How to deploy a Spring Boot WAR in Wildfly / JBoss This is a short guide on how to deploy a war packaged Spring Boot application in Wildfly. As you know Wildfly is the new name for JBoss AS since 8.0 v...

Leave a Reply