Goal: Test individual components in isolation (e.g., services, repositories).
Frameworks:
JUnit 5: Core framework that provides the structure and foundation for writing and running tests. It helps us structure and execute our tests and perform assertions on results.
Mockito: It is a mocking framework used to create mock objects for dependencies (services, external APIs etc) that we don’t want to test directly, allowing us to isolate the unit of code under test.
Combining JUnit and Mockito for TDD :
@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
@Mock
private UserRepository userRepository; // Mock the repository
@InjectMocks
private UserService userService; // Inject mocks into the service
@Test
void testGetUserById() {
// Given
User user = new User(1, "John");
when(userRepository.findById(1)).thenReturn(user); // Stubbing repository
// When
User result = userService.getUserById(1);
// Then
assertEquals("John", result.getName()); // JUnit's assertion
verify(userRepository).findById(1); // Mockito's verification
}
}
Goal: Ensure that multiple components (like services, repositories, controllers) work together.
Framework:
Framework: WireMock