---
name: step-07-tests
description: Generate backend tests with real integration testing and security coverage
prev_step: steps/step-06-migration.md
next_step: steps/step-08-documentation.md
---

# Step 7: Test Generation & Verification

## MANDATORY EXECUTION RULES

- ALWAYS use MCP `scaffold_tests` for test generation
- ALWAYS generate test infrastructure FIRST (once per project)
- ALWAYS generate at least 3 test categories: controller, service, entity
- ALWAYS follow naming convention: `{Method}_When{Condition}_Should{Result}`
- ALWAYS pass `testTypes: ['unit', 'integration']` for controller tests
- ALWAYS pass `testTypes: ['integration']` for repository tests
- **ALL tests MUST compile AND pass** - this step is BLOCKING
- YOU ARE AN ORCHESTRATOR calling MCP, not a generator

## YOUR TASK

Use MCP tools to generate test files covering:
1. **Test infrastructure** (WebApplicationFactory, IntegrationTestBase, TestAuthHandler)
2. Controller integration tests (REAL API endpoints with real DB)
3. Service unit tests (business logic)
4. Entity unit tests (domain rules)
5. Validator unit tests (input validation)
6. Repository integration tests (data access)
7. Security tests (OWASP coverage)

---

## AVAILABLE STATE

From previous steps:

| Variable | Description |
|----------|-------------|
| `{entity_name}` | PascalCase entity name |
| `{entity_code}` | kebab-case code |
| `{full_path}` | Complete navigation path (navRoute) |
| `{namespace}` | .NET namespace |
| `{api_route}` | API endpoint path |

---

## PRE-REQUISITES

See [references/test-prerequisites.md](../references/test-prerequisites.md) for the complete setup:
1. Verify test project exists (create xunit project if missing)
2. Install required NuGet packages (xunit, FluentAssertions, Moq, Mvc.Testing, EF Sqlite, etc.)
3. Add project references (API, Application, Domain, Infrastructure)
4. Ensure Program.cs is accessible for WebApplicationFactory (BLOCKING)

---

## EXECUTION SEQUENCE

### 0. Generate Test Infrastructure (ONCE PER PROJECT)

Check if `Tests/Integration/SmartStackTestFactory.cs` exists. If NOT:

```
Tool: mcp__smartstack__scaffold_tests
Args:
  target: "infrastructure"
  name: "{SolutionName}"
```

This generates:
- `Tests/Integration/SmartStackTestFactory.cs` - WebApplicationFactory with SQLite
- `Tests/Integration/IntegrationTestBase.cs` - Base class for integration tests
- `Tests/Integration/TestAuthHandler.cs` - Fake auth handler (bypasses JWT)
- `Tests/Integration/TestDataSeeder.cs` - Minimal test data seeder

**Review** `TestDataSeeder.cs` and add project-specific seeding logic if needed (tenant creation, base permissions, etc.).

### 1. Generate Controller Tests

```
Tool: mcp__smartstack__scaffold_tests
Args:
  target: "controller"
  name: "{entity_name}"
  testTypes: ["unit", "integration"]
  options:
    namespace: "{namespace}"
    navRoute: "{full_path}"
    includeAuthorization: true
    isSystemEntity: false
```

This generates:
- `Tests/Integration/Controllers/{EntityName}ControllerTests.cs` (mock-based, validates controller routing)
- `Tests/Integration/Controllers/{EntityName}ControllerIntegrationTests.cs` (REAL tests with actual DB)

**REAL Integration Test Coverage:**
- GET all -> 200 with list
- GET by ID -> 200 when exists, 404 when not
- POST -> 201/200 when valid, persist to DB, read back to verify
- POST -> 400 when invalid data
- POST -> 409 when duplicate code
- PUT -> 200 when valid, persist changes, read back to verify
- PUT -> 404 when not exists
- DELETE -> 204 when exists
- DELETE -> 404 when not exists
- Tenant isolation -> create in tenant A, invisible in tenant B (REAL DB)
- Authorization -> 401 when not authenticated

### 2. Generate Service Tests

```
Tool: mcp__smartstack__scaffold_tests
Args:
  target: "service"
  name: "{entity_name}"
  testTypes: ["unit"]
  options:
    namespace: "{namespace}"
    includeSoftDelete: true
    isSystemEntity: false
```

This generates:
- `Tests/Unit/Services/{EntityName}ServiceTests.cs`

### 3. Generate Entity Tests

```
Tool: mcp__smartstack__scaffold_tests
Args:
  target: "entity"
  name: "{entity_name}"
  testTypes: ["unit"]
  options:
    namespace: "{namespace}"
    includeSoftDelete: true
    includeAudit: true
    isSystemEntity: false
```

This generates:
- `Tests/Unit/Domain/{EntityName}Tests.cs`

### 4. Generate Validator Tests

```
Tool: mcp__smartstack__scaffold_tests
Args:
  target: "validator"
  name: "{entity_name}"
  testTypes: ["unit"]
  options:
    namespace: "{namespace}"
```

This generates:
- `Tests/Unit/Validators/{EntityName}ValidatorTests.cs`

### 5. Generate Repository Tests

```
Tool: mcp__smartstack__scaffold_tests
Args:
  target: "repository"
  name: "{entity_name}"
  testTypes: ["integration"]
  options:
    namespace: "{namespace}"
    includeSoftDelete: true
    isSystemEntity: false
```

This generates:
- `Tests/Integration/Repositories/{EntityName}RepositoryTests.cs`

### 6. Generate Security Tests

```
Tool: mcp__smartstack__scaffold_tests
Args:
  target: "controller"
  name: "{entity_name}"
  testTypes: ["security"]
  options:
    namespace: "{namespace}"
    isSystemEntity: false
```

This generates:
- `Tests/Security/{EntityName}SecurityTests.cs`

---

## POST-GENERATION VERIFICATION (MANDATORY)

See [references/test-coverage-requirements.md](../references/test-coverage-requirements.md) for:
- **Naming Convention Check** (BLOCKING) — `{Method}_When{Condition}_Should{Result}` pattern
- **Test Structure Check** (BLOCKING) — Arrange-Act-Assert format
- **Dependencies Check** (BLOCKING) — FluentAssertions, Moq, xunit
- **Coverage Check** — Minimum tests per category (CRUD + auth + tenant + persistence + security)
- **Build Check** (BLOCKING) — `dotnet build` must succeed
- **Test Run** (BLOCKING) — `dotnet test` must pass 100%
- **Real Integration Test Coverage** — DB persistence verification
- **Security Test Categories** — OWASP coverage

---

## FRONTEND TESTS (React Components)

See [references/test-frontend.md](../references/test-frontend.md) for the complete frontend test setup:

### 7-8. Infrastructure & Test Generation
- Check Vitest + Testing Library + MSW configuration
- Install packages if missing (`vitest`, `@testing-library/react`, `msw`, etc.)
- Copy infrastructure templates (vitest.config.ts, setup.ts, test-utils.tsx, MSW handlers)
- Generate tests via `mcp__smartstack__scaffold_frontend_tests` (Page, ListView, DetailPage, Hooks, API)

### 9. Run Frontend Tests (BLOCKING)

```bash
cd {WebProjectPath}
npx vitest run --reporter=default
```

**ALL frontend tests MUST pass.** Fix failures before proceeding.

---

## PRESENT OUTPUT TO USER

```markdown
## Test Suite Generated

### Test Files

| File | Category | Tests |
|------|----------|-------|
| `Tests/Integration/SmartStackTestFactory.cs` | Infrastructure | - |
| `Tests/Integration/IntegrationTestBase.cs` | Infrastructure | - |
| `Tests/Integration/TestAuthHandler.cs` | Infrastructure | - |
| `Tests/Integration/TestDataSeeder.cs` | Infrastructure | - |
| `Tests/Integration/Controllers/{EntityName}ControllerTests.cs` | Controller (mock) | ~12 |
| `Tests/Integration/Controllers/{EntityName}ControllerIntegrationTests.cs` | Controller (REAL) | ~12 |
| `Tests/Unit/Services/{EntityName}ServiceTests.cs` | Service | ~10 |
| `Tests/Unit/Domain/{EntityName}Tests.cs` | Entity | ~8 |
| `Tests/Unit/Validators/{EntityName}ValidatorTests.cs` | Validator | ~12 |
| `Tests/Integration/Repositories/{EntityName}RepositoryTests.cs` | Repository | ~12 |
| `Tests/Security/{EntityName}SecurityTests.cs` | Security | ~15 |

### Test Categories

| Category | Coverage |
|----------|----------|
| CRUD Operations | All endpoints tested with REAL database |
| Data Persistence | POST then GET to verify data in DB |
| Authentication | 401 for unauthenticated |
| Authorization | 403 for insufficient permissions |
| Tenant Isolation | Cross-tenant access blocked (REAL) |
| Input Validation | XSS, SQL injection, path traversal |
| Error Handling | ProblemDetails format |

### Frontend Tests

| File | Category | Tests |
|------|----------|-------|
| `src/pages/.../__tests__/{EntityName}Page.test.tsx` | Page | ~5 |
| `src/pages/.../__tests__/{EntityName}ListView.test.tsx` | List | ~8 |
| `src/pages/.../__tests__/{EntityName}DetailPage.test.tsx` | Detail | ~5 |
| `src/hooks/__tests__/use{EntityName}Preferences.test.ts` | Hooks | ~6 |
| `src/services/api/__tests__/{entityName}Api.test.ts` | API Client | ~5 |

### Test Execution Result
- Backend Build: PASS
- Backend Tests: PASS ({backend_test_count} tests)
- Frontend Tests: PASS ({frontend_test_count} tests)
```

---

## SUCCESS METRICS

### Backend
- Test project exists in solution
- Test infrastructure generated (SmartStackTestFactory, IntegrationTestBase, TestAuthHandler)
- All 7 test categories generated (infrastructure + 6 test types)
- Naming convention `{Method}_When{Condition}_Should{Result}` respected
- Arrange-Act-Assert structure in all tests
- FluentAssertions used (not Assert.Equal)
- Moq used for mocking (only in mock-based tests)
- **Test project builds successfully**
- **ALL backend tests pass** (BLOCKING)
- Minimum test count met per category
- Real integration tests verify actual DB persistence

### Frontend
- Vitest + Testing Library + MSW infrastructure deployed
- Test files generated for all scaffolded components (page, list, detail, hooks, api)
- MSW handlers mock API endpoints correctly
- **ALL frontend tests pass** (BLOCKING)

## FAILURE MODES

### Backend
- Test project doesn't exist -> Create it first
- Missing NuGet packages -> Install them
- Program.cs not accessible -> Add `public partial class Program { }`
- Build failures -> Fix compilation errors
- **Test failures -> Fix the code or tests before proceeding**
- Wrong naming convention -> Rename tests
- Missing test categories -> Generate missing ones

### Frontend
- Vitest not configured -> Deploy infrastructure templates
- Missing npm packages -> Run `npm install -D vitest @testing-library/react ...`
- MSW handlers missing -> Check `src/test/msw/handlers.ts`
- Import errors -> Check path aliases in `vitest.config.ts`
- **Test failures -> Fix the components or tests before proceeding**

---

## CODE REVIEW (RECOMMENDED)

After all tests pass, run a code quality audit on the generated feature:

```
Tool: mcp__smartstack__review_code
Args:
  scope: "{entity_name}"
  focus: ["security", "architecture", "clean-code", "performance"]
```

This reviews:
- **Security (OWASP)**: SQL injection, XSS, CSRF, auth bypass, tenant isolation
- **Architecture**: Layer violations, DI patterns, SOLID principles
- **Clean Code**: Naming, complexity, duplication, dead code
- **Performance**: N+1 queries, missing indexes, unnecessary allocations

IF critical issues found: Fix them before proceeding. Non-critical findings can be noted for future improvement.

---

## END OF WORKFLOW

This step concludes the test generation. The user now has:
- Full navigation structure (step 01)
- RBAC permissions (step 02)
- Role mappings (step 03)
- Client seed provider (step 03b, if applicable)
- Backend CRUD API (step 04)
- Frontend components + i18n + routes (step 05)
- Database migration (step 06)
- **Complete backend test suite with REAL integration tests (step 07)**
- **Complete frontend test suite with Vitest + Testing Library + MSW (step 07)**
- All backend and frontend tests compile and pass
