Testing in Spring Boot (Unit + Integration) [Java Spring Boot Mastery Series – Part 12]
Testing ensures the reliability and maintainability of your codebase.
✅ 1. Unit Testing with JUnit and Mockito
Dependency (Maven)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Sample Unit Test (Service Layer)
@SpringBootTest
public class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
public void testGetUserById() {
User mockUser = new User(1L, "Alice", "[email protected]");
Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));
User user = userService.getUserById(1L);
assertEquals("Alice", user.getName());
}
}
Explanation:
@MockBeanis used to mock dependencies.@SpringBootTestloads context.- Use
Mockito.whento simulate data returns
🔄 2. Integration Testing with TestRestTemplate
Sample Test
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testGetUser() {
ResponseEntity<User> response = restTemplate.getForEntity("/api/users/1", User.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
}
}
Explanation:
- Uses a real Spring Boot context and in-memory server.
TestRestTemplateis used to simulate REST calls.
🧹 3. Best Practices for Testing
- Separate unit vs. integration tests using naming or packages.
- Use
@DataJpaTestfor repository testing. - Use
@WebMvcTestfor controller-only tests. - Keep tests independent and stateless.
➡️ Next Up: Part 13 – Spring Boot with Docker & Deployment
