Testing Framework
The backend uses a comprehensive testing stack:- JUnit 5 - Test framework with
@Test,@BeforeEach, etc. - Spring Boot Test - Integration testing support
- Mockito - Mocking framework for unit tests
- AssertJ - Fluent assertions
- Testcontainers - Dockerized PostgreSQL for integration tests
- WebTestClient - Reactive HTTP client for E2E tests
Test Structure
Tests are organized by type:Running Tests
Run All Tests
Run Specific Test Class
Run Specific Test Method
Run Tests by Category
Run with Coverage
target/site/jacoco/index.html
Skip Tests During Build
Unit Testing
Unit tests focus on individual components in isolation using mocks.Service Unit Test Example
File:unit/services/DistributionServiceUnitTest.java:27
Key Annotations
@ExtendWith(MockitoExtension.class)- Enable Mockito@Mock- Create mock object@InjectMocks- Inject mocks into this object@BeforeEach- Run before each test@Test- Mark as test method
Mockito Patterns
Stubbing:AssertJ Assertions
Integration Testing
Integration tests use a real database (Testcontainers) and Spring context.Repository Integration Test
File:integration/repositories/ProductRepositoryIntegrationTest.java:20
Key Annotations
@DataJpaTest- Configure JPA test slice@ActiveProfiles("test")- Use test configuration@Autowired- Inject real Spring beans@Transactional- Automatic rollback after each test
Test Configuration
File:src/test/resources/application-test.properties:13
jdbc:tc: prefix automatically starts a PostgreSQL container.
Testcontainers
Testcontainers provides lightweight, throwaway PostgreSQL instances.Configuration
Dependency in pom.xml:How It Works
- Test starts → Testcontainers detects
jdbc:tc:URL - Container launches → PostgreSQL 16 Alpine image pulled/started
- Flyway runs → Database schema created from migrations
- Tests execute → Each test runs in a transaction (auto-rollback)
- Test completes → Container stopped and removed
Benefits
- Real database - Tests against actual PostgreSQL
- Isolated - Each test run uses fresh database
- Fast - Containers reused within test run
- No manual setup - No local PostgreSQL required
- CI/CD friendly - Works anywhere Docker is available
Custom Container Configuration
For more control, create a custom container:End-to-End Testing
E2E tests validate full request/response cycles through REST API.Controller E2E Test
File:e2e/controllers/ProductControllerE2ETest.java:22
Key Annotations
@SpringBootTest(webEnvironment = RANDOM_PORT)- Start full server on random port@AutoConfigureWebTestClient- Configure WebTestClient@Transactional- Rollback database changes after test
WebTestClient Patterns
GET Request:Code Coverage with JaCoCo
JaCoCo tracks test coverage and generates reports.Maven Configuration
In pom.xml:Generate Coverage Report
View Report
Open in browser:Coverage Metrics
- Instructions - Bytecode instructions executed
- Branches - If/else branches covered
- Lines - Source code lines executed
- Methods - Methods invoked
- Classes - Classes loaded