How to test our REST services using Spring Boot?

Updated:

Spring Boot offers us easy to use features to test our REST service. Our goal is to check that our REST Controller answers correctly to an HTTP request.

Here we are not interested to test the services layer or the database. For this reason we have to mock everything is around the controller.

Code sample

You can find the working code for the REST controller here:

marmo.dev GitHub DavisControllerTest

Mock the request

Spring boot gives us the possibility to simulate the http request without any browser using the annotation @WebMvcTest . This annotation configure @MockMvc that simulates the request for the tests.

Mock the service

As we see in the picture we don’t need to test the service, maybe it is retrieving some data from the database. We can use the annotations @MockBean or @SpyBean.

@MockBean creates a mock of the entire object.

@SpyBean allows to mock only some methods of an object.

To the code

Import the required classes:

@RunWith(SpringRunner.class)  
@WebMvcTest(DavisController.class)  
public class DavisControllerTest { 

In our case we have specified the controller to test in the annotation.

@SpyBean 
private DavisService davisService; 
     
@Autowired 
private MockMvc mvc; 

We use @SpyBean because we are interested in mocking only the method that access the database.

@Test 
public void resultListTest() throws Exception { 
 
String expectedResult = "[{\"year\":2015,\"winner\":\"Marco Team\"}]"; 
 
given(this.davisService.getResultList()).willReturn(mockedDavisData()); 
 
this.mvc.perform(get("/result_list")) 
   .andExpect(status().isOk()) 
   .andExpect(content().json(expectedResult)); 
} 

In our test we define an expectedResult, part of the JSON returned as answer.

To mock the ‘database method’ getResultList() we use the features of mockito that is imported with our spring boot pom:

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId> 
        spring-boot-starter-test 
    </artifactId> 
</dependency> 

The method call this.mvc.perform(get("/result_list")) is a static method that mock the GET request. It builds an HttpServletRequest behind the scenes and wait for the Http answer of the controller.

At this point we can test the result of the controller with the JSON string defined as expected result.

andExpect is part of the interface ResultActions.


You could be interested in

logo of the category: spring-big.svg Spring Boot RestTemplate: test GET request with JSON body is not working

How to test your REST GET controller with Spring Boot
2022-02-11
WebApp built by Marco using SpringBoot 3.2.4 and Java 21, in a Server in Switzerland without 'Cloud'.