# Sprint 11 Analysis — Quality Foundation: Backend Test Coverage

**Date:** 2026-06-15
**Sprint Theme:** Quality Foundation — Backend Test Coverage
**Author:** Patrick Plate / Roo (Architect)
**Status:** Draft v1

---

## 1. Current State Assessment

### 1.1 Codebase Metrics

| Metric | Value |
|--------|-------|
| Backend LOC (Java) | ~29,000 |
| Service classes | 42 (main) + 12 (bankimport) + 19 (report generators) |
| Existing unit tests | 9 test classes in `cannamanage-service` |
| Existing integration tests | 6 test classes in `cannamanage-api` |
| Existing Playwright E2E tests | 202 |
| Estimated current line coverage | ~12% |
| Target line coverage | ≥80% overall, ≥90% for financial/compliance |

### 1.2 Existing Test Inventory

**Unit Tests (`cannamanage-service/src/test/`):**

| Test Class | Service Under Test | Approx. Coverage |
|------------|-------------------|-----------------|
| `ClubServiceTest` | ClubService | Partial |
| `ComplianceServiceTest` | ComplianceService | Good (quota enforcement) |
| `EmailServiceTest` | EmailService | Basic |
| `PdfReportGeneratorTest` | PdfReportGenerator | Basic |
| `PortalServiceTest` | PortalService | Partial |
| `PreventionOfficerServiceTest` | PreventionOfficerService | Good |
| `ReportServiceTest` | ReportService | Partial |
| `StaffServiceTest` | StaffService | Partial |
| `TokenRevocationServiceTest` | TokenRevocationService | Good |

**Integration Tests (`cannamanage-api/src/test/`):**

| Test Class | Scope |
|------------|-------|
| `AbstractIntegrationTest` | Base class (Testcontainers PostgreSQL) |
| `AuthIntegrationTest` | Full auth flow |
| `PortalIntegrationTest` | Member portal endpoints |
| `ReportIntegrationTest` | Report generation endpoints |
| `StaffPermissionIntegrationTest` | RBAC enforcement |
| `TenantIsolationTest` | Multi-tenant data isolation |
| `TokenRevocationIntegrationTest` | Token lifecycle |
| `AuthControllerIntegrationTest` | Auth controller |
| `ClubControllerTest` | Club CRUD |
| `ComplianceControllerIntegrationTest` | Compliance endpoints |
| `StaffPermissionCheckerTest` | Permission checker logic |

### 1.3 Untested Services (Coverage Gaps)

**Critical — Zero Test Coverage:**

| Service | LOC | Complexity | Risk |
|---------|-----|-----------|------|
| `FinanceService` | 371 | High (ledger, payments, fees) | 🔴 Financial |
| `PaymentMatchingService` | 507 | Very High (scoring algorithm) | 🔴 Financial |
| `BankImportService` | ~400 | High (stateful session) | 🔴 Financial/GoBD |
| `Mt940Parser` | ~300 | High (state machine) | 🔴 Financial |
| `Camt053Parser` | ~250 | High (StAX XML) | 🔴 Security (XXE) |
| `CsvBankParser` | ~200 | Medium | 🟡 Financial |
| `RetentionService` | ~200 | Medium (GDPR logic) | 🔴 Compliance |
| `ReportGeneratorService` | ~150 | Medium (dispatch) | 🟡 Compliance |
| `EurReportGenerator` | ~300 | High (§4(3) EStG) | 🔴 Financial |
| `AnnualAuthorityReportGenerator` | ~250 | High (CanG §26) | 🔴 Compliance |
| `AssemblyService` | ~350 | High (quorum, voting) | 🟡 Legal |
| `EventService` | ~250 | Medium (RSVP, iCal) | 🟢 Standard |
| `ForumService` | ~200 | Medium | 🟢 Standard |
| `InfoBoardService` | ~150 | Low | 🟢 Standard |
| `NotificationDispatchService` | ~200 | Medium (fan-out) | 🟡 Reliability |
| `JwtService` | ~120 | Medium (crypto) | 🔴 Security |
| `LoginRateLimiter` | ~80 | Low | 🔴 Security |
| `TenantFilterAspect` | ~60 | Low (AOP) | 🔴 Security |
| `DocumentService` | ~200 | Medium (file I/O) | 🔴 Security |

### 1.4 Test Infrastructure Status

| Infrastructure | Status |
|---------------|--------|
| JUnit 5 | ✅ Available (via spring-boot-starter-test) |
| Mockito | ✅ Available (via spring-boot-starter-test) |
| AssertJ | ✅ Available (explicit dependency) |
| Testcontainers PostgreSQL | ✅ Available + configured |
| AbstractIntegrationTest base class | ✅ Exists with helper methods |
| JaCoCo coverage plugin | ❌ Not configured |
| Test profiles (application-test.properties) | ✅ Exists |
| Integration profile (application-integration.properties) | ✅ Exists |

---

## 2. Risk Analysis

### 2.1 Why 12% Coverage is a Production Blocker

| Risk | Impact | Probability | Mitigation |
|------|--------|-------------|-----------|
| Financial calculation bug (rounding, fee logic) | Loss of member trust, incorrect Kassenbuch | High | Unit tests for FinanceService with cent-precision assertions |
| Bank import data corruption (GoBD violation) | Legal liability under §147 AO | Medium | Integration tests for immutable session lifecycle |
| Payment matching false positive (wrong member) | Incorrect bookkeeping, member disputes | Medium | Unit tests with realistic German bank statement data |
| MT940 parser crash on edge cases | Import failure blocks payment reconciliation | High | Fuzz-style tests with malformed input |
| GDPR retention logic error | Supervisory authority fine (up to 4% revenue) | Low | Unit tests for anonymization completeness |
| Quota enforcement bypass | CanG violation, club loses license | Medium | Already tested (ComplianceServiceTest) — verify edge cases |
| JWT token validation bypass | Unauthorized access | Low-Medium | Unit tests for expiry, tampering, revocation |
| Tenant isolation breach | Data leak between clubs | Critical | Already tested (TenantIsolationTest) — extend |

### 2.2 Coverage Targets by Risk Category

| Category | Target | Rationale |
|----------|--------|-----------|
| Financial (FinanceService, BankImport, Parsers, Matching) | ≥90% | Money handling requires near-complete coverage |
| Compliance (Retention, ComplianceService, Reports) | ≥90% | Regulatory requirements |
| Security (JWT, RateLimiter, Tenant, Document) | ≥80% | Attack surface minimization |
| Core Business (Assembly, Events, Forum, InfoBoard) | ≥75% | Functional correctness |
| Infrastructure (Notifications, Schedulers) | ≥60% | Reliability baseline |

---

## 3. Testing Strategy

### 3.1 Test Pyramid

```
        /‾‾‾‾‾‾‾‾‾‾‾‾\
       /   Playwright    \     202 existing (unchanged)
      /    E2E (202)      \
     /____________________\
    /                      \
   /  Integration (~12)     \   ~12 new (Testcontainers)
  /    API + DB flows        \
 /__________________________\
/                            \
/   Unit Tests (~95+)          \   ~95 new (Mockito)
/    Service logic isolation    \
/________________________________\
```

### 3.2 Unit Test Approach

- **Pattern:** JUnit 5 + Mockito + AssertJ (matching existing ComplianceServiceTest style)
- **Naming:** `test<Method>_<Scenario>_<Expected>()` with `@DisplayName`
- **Structure:** Given-When-Then with clear section comments
- **Mocking:** All repository dependencies mocked; test pure business logic
- **Edge cases:** null inputs, boundary values, German locale specifics (umlauts, date formats)

### 3.3 Integration Test Approach

- **Base class:** Extend existing `AbstractIntegrationTest` (Testcontainers PostgreSQL)
- **Scope:** Full request → DB → response cycles
- **Auth:** Use helper methods to create users and obtain JWT tokens
- **Data isolation:** Each test creates its own club/user context
- **Cleanup:** `@Transactional` rollback or manual cleanup in `@AfterEach`

### 3.4 Coverage Measurement

- **Tool:** JaCoCo Maven plugin
- **Report:** HTML + XML (for CI parsing)
- **Enforcement:** `<rule>` element with minimum 60% line coverage
- **Exclusions:** Generated code, DTOs, enums, configuration classes

---

## 4. Sprint Scope

### 4.1 In Scope

- 296+ new unit tests across 30+ service classes (includes report generators, schedulers, CRUD services)
- 29+ new integration tests for critical flows (incl. SecurityConfig and Flyway migration verification)
- JaCoCo plugin configuration with 80% enforcement
- Maven Surefire parallelization (forkCount=2) for build speed
- Test fixtures and builders for realistic German data (incl. real Sparkasse MT940)
- Coverage from 12% → 80%+ overall (realistically achievable with +70 easy-win tests in v3)

### 4.2 Out of Scope

- New features
- Frontend changes
- Playwright test additions
- CI/CD pipeline changes (deferred to Sprint 12)
- Performance testing

---

## 5. Dependencies

| Dependency | Status | Action |
|-----------|--------|--------|
| Testcontainers | ✅ Already in POM | None |
| JaCoCo | ❌ Missing | Add to parent POM |
| Test fixtures (MT940 samples, CAMT053 XML) | ❌ Missing | Create in src/test/resources |
| Mockito (for unit tests) | ✅ via starter-test | None |
| AssertJ | ✅ Explicit dependency | None |

---

## 6. Success Criteria

| Criterion | Threshold | Measurement |
|-----------|-----------|-------------|
| Overall line coverage | ≥80% | JaCoCo report |
| Financial module coverage | ≥90% | JaCoCo per-package |
| Compliance module coverage | ≥90% | JaCoCo per-package |
| Security module coverage | ≥85% | JaCoCo per-package (boosted by GlobalExceptionHandler tests) |
| Core business coverage | ≥75% | JaCoCo per-package |
| Infrastructure coverage (Schedulers + Notifications) | ≥70% | JaCoCo per-package |
| All tests pass | 100% green | `mvn test` exit code 0 |
| Total backend tests | ≥345 | Surefire report count |
| No new features introduced | 0 feature commits | Git log review |
| Build time increase | ≤3 minutes | Maven timing (with forkCount=2) |
