Testing is the process of checking whether your code works as expected.
In Spring, tests help verify:
Why Write Tests?
Benefit | Description |
---|---|
Catch bugs early | Prevent errors before production |
Save time | Easier debugging, faster fixes |
Improve design | Testable code is often cleaner and modular |
Confidence | Safer refactoring and deployment |
Automation | Continuous Integration (CI) tools rely on test automation |
Unit Tests
Unit tests focus on testing individual methods or classes in isolation.
Tools:
Example:
java
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void shouldReturnUserWhenFoundById() {
User mockUser = new User(1L, "Alice");
when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));
User result = userService.getUserById(1L);
assertEquals("Alice", result.getName());
}
}
Unit tests do not load the Spring context.
Integration Tests
Integration tests check how multiple components work together using real Spring beans.