→ Test Driven Development (TDD)

Untitled-2024-05-19-2318.svg

Unit Testing

Goal: Test individual components in isolation (e.g., services, repositories).

Frameworks:

  1. 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.

  2. 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.

  3. 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
        }
    }
    

→ Integration Testing

Goal: Ensure that multiple components (like services, repositories, controllers) work together.

Framework:

  1. Spring Boot Test and Test Rest Template: Spring boot test is used this to bootstrap the entire Spring context and test how different layers of the application interact. And Test Rest Template used to test REST APIs by performing real HTTP calls.
  2. Test Containers: Provides Docker containers for actual databases like MySQL, PostgreSQL for testing purposes.

→Inter service Communication Testing (Later)

Framework: WireMock