Within this post, I show you how to setup a Unit Test in Spring Boot performing HTTP requests with Mockito. In this case, we’re using
Model in our controller, but we could follow similar instructions for a REST controller case.
Sometimes testing web access with Spring Boot can be tricky. There are some different annotations for different scenarios, and the configuration is also one of the most struggling parts.
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, containing Mockito in it. As usual, we want the dependency only for test purposes so we set the scope to.
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 (irrelevant for the test).
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:
- here). It tells the framework to load a . is a specific annotation for integration tests (check Javadoc
- 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…
Want to know more about proper Unit Testing and Integration Testing with Spring Boot?
- Check out The Complete Guide to REST (Controller) Tests in Spring Boot: Unit and Integration Tests
- Get my book to have a full understanding of how TDD works nicely with Spring Boot: Learn Microservices with Spring Boot