Spring Boot
Article 17: Testing Spring Boot Applications
By Utility Zone · 2026-01-27T18:28:51.415811
1. Introduction
If code is not tested, it is not trustworthy.
Testing helps you:
- Catch bugs early
- Refactor safely
- Deploy with confidence
Spring Boot provides excellent support for unit tests and integration tests.
2. Types of Tests in Spring Boot
2.1 Unit Tests
- Test one class at a time
- No Spring context
- Very fast
2.2 Integration Tests
- Load Spring context
- Test multiple layers together
- Slightly slower but realistic
Both are important.
3. Testing Tools You’ll Use
Spring Boot testing stack includes:
- JUnit 5
- Mockito
- Spring Test
- MockMvc
Most are included via:
spring-boot-starter-test
4. Unit Testing a Service (Mockito)
4.1 Example Service
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getUser(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new RuntimeException("User not found"));
}
}
4.2 Writing Unit Test
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void shouldReturnUserWhenFound() {
User user = new User("Bharat", "bharat@email.com");
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
User result = userService.getUser(1L);
assertEquals("Bharat", result.getName());
}
}
✔ Fast
✔ No Spring startup
5. Integration Testing with @SpringBootTest
5.1 Load Full Context
@SpringBootTest
class UserServiceIntegrationTest {
@Autowired
private UserService userService;
@Test
void contextLoads() {
assertNotNull(userService);
}
}
6. Testing Controllers with MockMvc
6.1 Example Controller Test
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void shouldReturnUsers() throws Exception {
mockMvc.perform(get("/users"))
.andExpect(status().isOk());
}
}
MockMvc:
- Simulates HTTP calls
- No real server started
7. Testing JSON Responses
mockMvc.perform(get("/users"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].name").exists());
8. Using Test Profiles
Create:
application-test.properties
Activate:
@ActiveProfiles("test")
Useful for:
- In-memory DB
- Isolated configs
9. Common Testing Mistakes
❌ Not testing service layer
❌ Only integration tests
❌ Hardcoded data
❌ Ignoring edge cases
10. Best Practices
✔ Write unit tests for logic
✔ Use integration tests for wiring
✔ Keep tests independent
✔ Tests should be readable
11. What You Should Understand Before Moving On
You should now know:
- Difference between unit & integration tests
- How Mockito works
- How to test controllers
- How Spring Boot supports testing
12. What’s Next?
➡ Article 18: External Configuration & Secrets
- Environment variables
- Config best practices
Type Next when you’re ready.