30.14. Developing REST APIs with Spring Boot: Unit and integration tests
When developing a REST API with Spring Boot, ensuring code quality and endpoint reliability is essential. An effective way to achieve this goal is to implement unit and integration tests. In this section, we'll explore how to create and run these tests within a Spring Boot project, ensuring your REST API works as expected.
Unit Tests
Unit testing is the basis for any testing strategy in software development. They are fast, isolated and focus on a small part of the code, such as methods or classes. In the context of Spring Boot, we generally use frameworks like JUnit and Mockito to write unit tests.
JUnit
JUnit is a testing framework for the Java programming language that allows us to write and run repeatable tests. With JUnit, we can ensure that our classes' methods are working as expected.
Mockito
Mockito is a framework that allows you to create mock objects in unit tests. This is useful when we need to test the logic of a class without relying on its external dependencies, such as databases or other services.
Unit Test Example
@SpringBootTest
public class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
public void whenSaveUser_thenSuccess() {
User user = new User("John Doe", "john.doe@example.com");
Mockito.when(userRepository.save(user)).thenReturn(user);
User created = userService.createUser(user);
assertThat(created.getName()).isEqualTo(user.getName());
assertThat(created.getEmail()).isEqualTo(user.getEmail());
}
}
In the example above, we are testing the createUser
method of UserService
. We use @MockBean
to simulate the UserRepository
and @Autowired
to inject the UserService
instance that we want to test. With Mockito, we simulate the behavior of the repository's save
method to return the user we are creating. This way, we can check if the service is working correctly without having to interact with the database.
Integration Tests
Integration testing is important to ensure that different parts of the system work together. In Spring Boot, we can use the Spring MVC Test Framework to simulate HTTP calls to the API and check the behavior of the application as a whole.
Spring MVC Test Framework
This framework allows you to write tests that send HTTP requests to the DispatcherServlet (the Spring MVC front controller) and check the responses. With this, it is possible to test controllers, routes and response status without the need to deploy the application on a real web server.
Integration Test Example
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class UserControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void whenGetUser_thenStatus200() throws Exception {
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John Doe"))
.andExpect(jsonPath("$.email").value("john.doe@example.com"));
}
}
In the example above, we used @SpringBootTest
with the webEnvironment
option to launch the Spring Boot context and make a web server available on a random port. With @AutoConfigureMockMvc
, Spring Boot automatically configures MockMvc
, which is a central point for integration testing in Spring MVC. We use MockMvc
to simulate a GET request to the /users/1
endpoint and check whether the response has HTTP status 200 (OK), in addition to checking whether the content of the response contains the expected data.
Final Considerations
Unit and integration tests are fundamental in developing REST APIs with Spring Boot. They help ensure that each part of the code works in isolation and that all parts work together as expected. Using frameworks like JUnit and Mockito, along with the capabilities of the Spring MVC Test Framework, you can build a robust set of tests that will increase confidence in your code and reduce the possibility of bugs in production.
In addition, a well-defined testing strategy facilitates the maintenance and evolution of the application, as any change that breaks existing functionality will be promptly identified by tests. So invest timeand resources to write and maintain quality tests, and your REST API with Spring Boot will be much more solid and reliable.