testing.md
docs/testing.md
1# Testing23## Testing Stack45- **Frameworks:** JUnit 6, Mockito, AssertJ.67## Layer-Specific Testing89Tests mirror the feature's layer subpackages:1011- **Service tests:** Always required. Core business logic, validation rules, and error conditions live in the service layer.12- **Controller tests (`@WebMvcTest`):** Needed once an endpoint introduces request validation, HTTP status code mappings, security constraints, or a response shape worth asserting.13- **Persistence adapter tests (`@DataJpaTest`):** Cover domain/entity mapping, managed relationships, membership identity, and stale-version handling.14- **Repository tests (`@DataJpaTest`):** Reserved for custom `@Query` methods or `Specification` logic — never write tests for plain CRUD operations already provided and tested by Spring Data JPA.1516## Mocking Rules1718- In the service's own unit test, `@InjectMocks` must target the implementation class `<Feature>ServiceImpl` (Mockito cannot instantiate an interface).19- In controller tests, mock the service interface (`@Mock` / `@MockitoBean <Feature>Service`).20- Field injection (`@Mock`, `@InjectMocks`, `@Autowired`) is allowed in test classes (forbidden in production code).2122## Test Conventions2324- **Naming:** Use snake_case ending with `_ok` or `_ko` (e.g., `create_task_ok()`, `get_task_not_found_ko()`). Longer descriptive names are acceptable when they clearly convey intent.25- **Structure:** Follow `// given`, `// when`, `// then` block separators.26- **Assertions:** Use AssertJ (`assertThat`, `assertThatThrownBy`). Group related checks into `assertAll(...)` so failures report all mismatches simultaneously rather than stopping on the first one.27- **Variable style:** Use `var` for local variables and omit `final` (same style as controllers).28- **No business logic in tests:** Do not write loops, conditionals (`if`), or reflection inside test methods. If complex test data is needed, create private factory helper methods.2930## Required Service Test Coverage3132For each service, ensure tests cover:331. **Happy path:** Normal successful execution of each operation.342. **Find or 404:** Throws `AppException` when an entity is not found.353. **Guard clauses:** Preconditions that fail before calling repository save:36 ```java37 verify(repository, never()).save(any());38 ```394. **PATCH semantics:** Partial updates modify only provided fields and preserve unmodified existing values.4041## Quality Gate4243Nothing is merged without passing formatting checks and test suites:4445```bash46./gradlew spotlessCheck && ./gradlew test47```4849Service unit tests mock domain persistence interfaces and use domain model fixtures.50The persistence boundary test prevents business layers from importing JPA implementation details.51The application context test checks that no service constructor depends on another service,52including dependencies injected through interfaces.53