The Standard Testing
What this skill is
This skill governs how The Standard is tested, verified, and proven.
It covers test-driven development, validation strategies, exception mapping, unit test structure, controller tests, and UI component tests.
Explicit coverage map
This skill explicitly covers:
- Foundation-service implementation and validation/testing patterns from the Services chapter
- Structural, logical, external, and dependency validation testing
- Exception mapping and category testing
- Processing-service testing responsibilities
- Orchestration-service call-order testing
- Aggregation-service testing restrictions
- REST controller unit and acceptance tests
- UI component testing for bases, core components, and pages
- The supplied implementation specification sections on unit testing, partial test organization, conventions, AAA, and test order
- TDD FAIL/PASS discipline relevant to test creation and implementation verification
When to use
Use this skill whenever writing, reviewing, expanding, fixing, or sequencing tests.
Use it whenever deciding what to test first, how to map exceptions in tests, or how to prove a Standard-compliant flow.
Core testing doctrine
- Follow TDD.
- Write the failing test first.
- Verify the test actually fails.
- Write the minimum implementation required to pass.
- Verify the full relevant suite passes.
- Refactor without changing behavior.
- Repeat.
Validation testing rules
Validation Source of Truth
Validation rules MUST be inferred from all authoritative sources:
- Foundation service business rules
- Storage-layer configuration (
StorageBroker.[Entity].Configurations.cs)
- Domain expectations implied by usage
The storage configuration represents minimum enforced constraints:
- Required vs optional
- Maximum length
- Minimum length (if configured)
- Precision / scale / format where applicable
Foundation services represent the enforcement boundary:
- All constraints that can cause persistence failure MUST be validated before reaching storage
- Validation must prevent database exceptions where deterministically possible
Validation Alignment Rules
Foundation validation MUST be equal to or stricter than storage constraints.
The following are ALLOWED (strengthening rules):
- Storage: optional → Foundation: required
- Storage: optional → Foundation: constrained (min/max length)
- Storage: max length → Foundation: smaller max length
The following are NOT ALLOWED (weakening or missing rules):
- Storage: required → Foundation: not validated as required
- Storage: max length → Foundation: no length validation
Violations of alignment MUST be treated as:
- A design defect
- A test failure condition
- A review blocker
Validation Responsibility Rule
The database MUST NOT be relied upon to enforce:
- Required field validation
- Length validation
- Format validation
The ONLY acceptable database-enforced constraints without prior validation are:
- Foreign key constraints
- Uniqueness / duplicate key constraints
- Concurrency constraints
Any validation that can be performed deterministically in the foundation service MUST be performed there
Validation Test Derivation from Storage Configuration
Storage configuration (StorageBroker.[Entity].Configurations.cs) defines constraints, not validation behavior.
For every constraint defined in storage configuration, there MUST exist a corresponding validation rule in the foundation service:
- Required fields
- Length constraints (min/max)
- Precision / format constraints where applicable
Validation tests MUST:
- Target the foundation service validation methods only
- NOT directly test storage configuration behavior
- Prove that each storage-defined constraint is enforced at the foundation layer
For each property constraint, validation tests MUST focus on constraint violations and boundary breaches:
Valid scenarios (within acceptable range) are covered by logic tests and MUST NOT be redundantly tested in validation tests.
Missing alignment between storage configuration and foundation validation MUST be treated as:
- A design defect
- A test failure condition
- A review blocker
Automation MAY assist in identifying constraints (e.g., via EF metadata), but:
- Generated tests MUST still validate foundation behavior
- Automation MUST NOT result in tests that validate the database layer directly
All validation tests MUST:
- Follow Standard naming conventions
- Be explicit and intention-revealing
Validation order
- Structural validations first.
- Logical validations second.
- External validations third.
- Dependency validations when the external resource is the source of the failure.
Circuit-breaking validations
- Null checks and other hard-stop guards must break immediately.
- If continuing would create invalid dereference or meaningless work, stop immediately.
Continuous validations
- When multiple fields can be invalid independently, collect them before throwing.
- Use upsertable exception data.
- Use dynamic rules with condition + message.
- Use a validations collector routine.
- Throw once the collector contains errors.
Hybrid continuous validations
- Validate parent objects before validating child properties.
- Split nested validation into levels to avoid unintended null-reference failures.
Foundation-service test rules
- Test the happy path first.
- Then test structural validations.
- Then test logical validations.
- Then test external validations.
- Then test dependency validations.
- Then test dependency exceptions.
- Then test service exceptions.
- Always verify logging and broker calls.
- Always verify no unwanted calls occurred.
- Always keep validation and exception behaviors local and explicit.
Processing-service test rules
- Test higher-order logic, not primitive broker details.
- Validate only what the processing service uses.
- Test shifters.
- Example: object -> bool or object -> count.
- Test combinations.
- Example: retrieve + add, retrieve + modify, ensure-exists, upsert.
- Test processing exception mapping from foundation exceptions.
Orchestration-service test rules
- Test multi-entity flow combinations.
- Test mapping/branching between contracts when present.
- Test call order when the flow depends on order.
- Prefer natural order when inputs/outputs force sequencing.
- Use explicit order verification when sequencing is not naturally encoded.
- Verify orchestration-level exception wrapping and unwrapping.
- Test normalization outcomes indirectly through dependency shape and resulting behavior.
Aggregation-service test rules
- Do not test dependency call order in aggregation services.
- Do not use mock-sequence style order assertions for aggregation services.
- Test only basic structural validations and exposure-level aggregation behavior.
- Aggregation services may multi-call or pass-through; test the contract and exposure abstraction, not orchestration logic.
Controller and protocol test rules
- Controllers require unit tests for mapping logic.
- Unit-test success code mappings.
- Unit-test validation / dependency / service error mappings.
- Unit-test security i.e authorization / authentication failure mappings.
- Acceptance-test every endpoint.
- Clean up test data after acceptance tests.
- Emulate external resources not owned by the microservice when running acceptance tests.
- Integration and end-to-end testing are valid beyond unit + acceptance.
UI component test rules
Base components
- Treat bases as thin wrappers.
- Test their exposed APIs and wrapper behavior when needed.
- Do not put business logic into bases.
Core components
- Core components are test-driven.
- Test elements.
- Existence
- Properties
- Actions
- Existence may be tested by property assignment, searching by id, or general search.
- Test styles when styles are part of the component contract.
- Test actions that mutate state, create components, or trigger service calls.
- Core components should integrate with one and only one view service.
Pages / containers
- Pages are simpler route containers.
- They generally do not require unit tests.
- They should not contain business logic.
Unit-test conventions from the supplied implementation profile
- Mirror partial-class split in tests.
- Use setup/helpers in the root test file.
- Split tests into logic, validations, and exceptions files.
- Use GWT: Given / When / Then.
- Mock all dependencies.
- Use readable assertions.
- Use deep cloning to protect expectation identity.
- Use randomized data by default.
- Verify exact dependency calls.
- End with VerifyNoOtherCalls.
- Keep naming explicit and scenario-driven.
Exact test implementation order for foundation-service add routines
When implementing an Add{Entity}Async routine under the implementation profile, follow this order:
- ShouldAdd{Entity}Async
- ShouldThrowValidationExceptionOnAddIf{Entity}IsNullAndLogItAsync
- ShouldThrowValidationExceptionOnAddIf{Entity}IsInvalidAndLogItAsync
- ShouldThrowDependencyValidationExceptionOnAddIfBadRequestErrorOccursAndLogItAsync
- ShouldThrowDependencyValidationExceptionOnAddIfConflictErrorOccursAndLogItAsync
- ShouldThrowCriticalDependencyExceptionOnAddIfUnauthorizedErrorOccursAndLogItAsync
- ShouldThrowCriticalDependencyExceptionOnAddIfForbiddenErrorOccursAndLogItAsync
- ShouldThrowCriticalDependencyExceptionOnAddIfNotFoundErrorOccursAndLogItAsync
- ShouldThrowCriticalDependencyExceptionOnAddIfUrlNotFoundErrorOccursAndLogItAsync
- ShouldThrowDependencyExceptionOnAddIfInternalServerErrorOccursAndLogItAsync
- ShouldThrowDependencyExceptionOnAddIfServiceUnavailableErrorOccursAndLogItAsync
- ShouldThrowCriticalDependencyExceptionOnAddIfHttpRequestErrorOccursAndLogItAsync
- ShouldThrowServiceExceptionOnAddIfServiceErrorOccursAndLogItAsync
For storage-based services, substitute the storage equivalents such as duplicate-key, DbUpdate, and SQL exceptions.
Testing and exception/localization addendum from the supplied implementation profile
8. Unit Testing
Unit tests follow The Standard's partial-class + three-axis approach.
8.1 Test Class Structure
Each entity's tests mirror the same partial-class split as the service:
| Partial file |
Tests |
{Entity}ServiceTests.cs |
Setup, mocks, helpers (CreateRandom{Entity}, etc.) |
{Entity}ServiceTests.Logic.{Method}.cs |
Happy-path / success-case tests |
{Entity}ServiceTests.Validations.{Method}.cs |
Validation failure tests |
{Entity}ServiceTests.Exceptions.{Method}.cs |
Dependency & service exception tests |
8.2 Conventions
| Convention |
Detail |
| Mocking |
Moq — Mock<IStorageBroker>, Mock<IModernApiBroker>, Mock<ILoggingBroker> |
| Assertions |
FluentAssertions — Should().BeEquivalentTo() |
| Deep cloning |
DeepCloner — to isolate input/expected/actual objects |
| Data generation |
Tynamix.ObjectFiller — Filler<{Entity}> with custom property setup |
| Exception comparison |
Xeption.SameExceptionAs() via SameExceptionAs expression helper |
| Test naming |
Should{Action}Async / ShouldThrow{Exception}On{Action}If{Condition}AndLogItAsync |
| Verify calls |
Every test verifies broker calls (Times.Once / Times.Never) and ends with VerifyNoOtherCalls() |
| Test framework |
xUnit — [Fact] for single cases, [Theory] [InlineData] for parameterised cases |
8.3 Test Pattern — GWT (Given / When / Then)
// given — build input, configure mocks, construct expected exception
// when — invoke the service method
// then — assert result / exception, verify broker interactions
8.4 Test Implementation Order
Tests must be written and committed in the following strict order. This ordering ensures
each category builds upon the prior one:
- Happy Path —
ShouldAdd{Entity}Async
- Structural Validations — null entity check (
ShouldThrowValidationExceptionOnAddIf{Entity}IsNullAndLogItAsync)
- Logical Validations — property-level checks using
[Theory] [InlineData] (ShouldThrowValidationExceptionOnAddIf{Entity}IsInvalidAndLogItAsync)
- External Dependency Validation Exceptions —
BadRequest → Conflict
- External Critical Dependency Exceptions —
Unauthorized → Forbidden → NotFound → UrlNotFound
- External Non-Critical Dependency Exceptions —
InternalServerError → ServiceUnavailable
- Transport-Level Exception —
HttpRequestException
- Catch-All Service Exception —
Exception
For storage-based services, steps 4–7 are replaced with the corresponding SQL/EF exceptions
(DuplicateKeyException, DbUpdateException, SqlException).
Rule — Test Verification Before Commit: Each FAIL commit must have the test
actually running and failing. Each PASS commit must have all tests
running and passing. Never commit a FAIL without verifying the test runner
reports a genuine failure. See Section 12.1.3 — Commits for details.
9. Key Libraries
| Package |
Purpose |
Xeption |
Enhanced exceptions with data aggregation |
EFxceptions |
EF Core wrapper that throws meaningful exceptions |
RESTFulSense |
HTTP client wrapper for external API brokers |
Moq |
Mock framework for unit tests |
FluentAssertions |
Readable assertion syntax |
DeepCloner |
Value-based deep cloning of test objects |
Tynamix.ObjectFiller |
Random test data generation |
xunit |
Unit test framework |
Exception Handling Principles
0. Scope
These rules govern exception design, localisation, categorisation, propagation, and testing across all service layers.
1. Localisation (MANDATORY)
- External (non-local) exceptions MUST be localised at the boundary (Foundation).
- Native exceptions (SQL, HTTP, SDK) MUST NOT cross service boundaries.
- Localisation MUST convert native exceptions into domain-specific exceptions.
Data Preservation (MANDATORY)
ALL relevant data from the external exception MUST be copied to the local exception:
Data dictionary
- Constraint / validation metadata
- Identifiers / keys
The localised exception MUST carry this data so that:
- The immediate inner exception contains full validation detail after categorisation.
2. Categorisation
All exceptions MUST be categorised into one of:
- Validation
- DependencyValidation
- Dependency
- Service
Categorisation defines upstream handling and exposer mapping.
3. Propagation (Unwrap / Rewrap)
Each service layer MUST:
- Catch downstream exceptions
- UNWRAP the categorical exception
- PRESERVE the LOCAL exception
- REWRAP into its OWN categorical exception
This prevents leakage of lower-layer concerns and enforces layer contracts.
4. Inner Exception Preservation (MANDATORY)
- The original local exception MUST always be preserved as the inner exception.
- No layer may discard or replace the local exception.
This guarantees:
- Traceability
- Correct exposer mapping (e.g. HTTP Conflict / FailedDependency)
- Retention of validation data
5. Layer Responsibilities
Foundation
- Localise external exceptions
- Populate local exception data
- Categorise into Validation / DependencyValidation / Dependency / Service
Processing
- MUST ONLY handle categorised exceptions
- MUST NOT depend on foundation exception types
- MUST rewrap into processing-level exceptions
Orchestration
- MUST handle exceptions from all dependencies
- MUST unify into a single categorical exception per type
- MUST unwrap and preserve inner exceptions
6. Catch-All (MANDATORY)
- Every service MUST implement:
- MUST map to ServiceException
This prevents leakage of unknown failures.
7. Logging
- Each layer MUST log BEFORE rethrowing
- MUST log the categorised exception only
8. Testing
Orchestration Exception Tests
- SHOULD use
[Theory]
- MUST cover multiple dependency exception types in a single test
- MUST avoid duplication
9. Design Intent
These rules ensure:
- Full abstraction from external systems
- Stable layer contracts
- Simplified exposer logic
- Complete validation visibility at the local exception level
Exception Handling Cross-References (Enforcement)
Validation Testing Alignment
All validation tests MUST align with Exception Handling Principles:
- Localisation MUST be verified (no native exceptions exposed)
- Data preservation MUST be verified on local exceptions
- Validation exceptions MUST contain full error details in inner exception
- From processing service layer upwards, validation exceptions and dependency validation exceptions from its dependencies rewrap to [Entity][Layer]DependencyValidationExceptions
- From processing service layer upwards, dependency exceptions and service exceptions from its dependencies rewrap to [Entity][Layer]DependencyExceptions
Validation tests MUST assert:
- Correct local exception type
- Correct categorised exception type
- Inner exception contains validation data (Data dictionary populated)
Foundation Exception Tests (Enforcement)
Tests MUST verify localisation:
- Native exception → Local exception → Categorised exception
Tests MUST verify:
- External exception data is copied to local exception
- Local exception is preserved as inner exception
Tests MUST NOT allow:
- Native exception leakage
- Missing Data dictionary propagation
Processing Exception Tests (Enforcement)
Tests MUST assert:
- Rewrapping into processing-level exception
- Inner exception preservation
Tests SHOULD:
- Use
[Theory] to test multiple dependency validation exceptions of the same type in one test
- Use
[Theory] to test multiple dependency exceptions of the same type in one test
- Avoid duplication by testing multiple cases in a single test method
Orchestration Exception Tests (Enforcement)
Tests MUST assert:
- Rewrapping into orchestration-level exception
- Inner exception is preserved (local exception)
- Categorical exception is replaced at orchestration level
Tests SHOULD:
- Use
[Theory] to test multiple dependency validation exceptions of the same type in one test
- Use
[Theory] to test multiple dependency exceptions of the same type in one test
- Avoid duplication by testing multiple cases in a single test method
Catch-All Enforcement
- Tests MUST verify:
- Unknown exceptions are mapped to ServiceException
- No raw Exception escapes any service layer
Logging Enforcement
- Tests MUST verify:
- Logging occurs before exception is thrown
- Logged exception is the categorised exception
Design Integrity Rule
- Any violation of exception handling principles MUST be treated as:
- A design defect
- A test failure
- A review blocker
1---2name: the-standard-testing3description: Enforces Standard TDD discipline, validation testing, exception mapping, controller acceptance tests, and UI component testing.4---56# The Standard Testing78## What this skill is910This skill governs how The Standard is tested, verified, and proven.11It covers test-driven development, validation strategies, exception mapping, unit test structure, controller tests, and UI component tests.1213## Explicit coverage map1415This skill explicitly covers:1617- Foundation-service implementation and validation/testing patterns from the Services chapter18- Structural, logical, external, and dependency validation testing19- Exception mapping and category testing20- Processing-service testing responsibilities21- Orchestration-service call-order testing22- Aggregation-service testing restrictions23- REST controller unit and acceptance tests24- UI component testing for bases, core components, and pages25- The supplied implementation specification sections on unit testing, partial test organization, conventions, AAA, and test order26- TDD FAIL/PASS discipline relevant to test creation and implementation verification2728## When to use2930Use this skill whenever writing, reviewing, expanding, fixing, or sequencing tests.31Use it whenever deciding what to test first, how to map exceptions in tests, or how to prove a Standard-compliant flow.3233## Core testing doctrine34350. Follow TDD.361. Write the failing test first.372. Verify the test actually fails.383. Write the minimum implementation required to pass.394. Verify the full relevant suite passes.405. Refactor without changing behavior.416. Repeat.4243## Validation testing rules4445### Validation Source of Truth46470. Validation rules MUST be inferred from all authoritative sources:48 - Foundation service business rules49 - Storage-layer configuration (`StorageBroker.[Entity].Configurations.cs`)50 - Domain expectations implied by usage51521. The storage configuration represents **minimum enforced constraints**:53 - Required vs optional54 - Maximum length55 - Minimum length (if configured)56 - Precision / scale / format where applicable57582. Foundation services represent **the enforcement boundary**:59 - All constraints that can cause persistence failure MUST be validated before reaching storage60 - Validation must prevent database exceptions where deterministically possible6162### Validation Alignment Rules63640. Foundation validation MUST be **equal to or stricter than** storage constraints.65661. The following are **ALLOWED (strengthening rules)**:67 - Storage: optional → Foundation: required68 - Storage: optional → Foundation: constrained (min/max length)69 - Storage: max length → Foundation: smaller max length70712. The following are **NOT ALLOWED (weakening or missing rules)**:72 - Storage: required → Foundation: not validated as required73 - Storage: max length → Foundation: no length validation74753. Violations of alignment MUST be treated as:76 - A design defect77 - A test failure condition78 - A review blocker7980### Validation Responsibility Rule81820. The database MUST NOT be relied upon to enforce:83 - Required field validation84 - Length validation85 - Format validation86871. The ONLY acceptable database-enforced constraints without prior validation are:88 - Foreign key constraints89 - Uniqueness / duplicate key constraints90 - Concurrency constraints91922. Any validation that can be performed deterministically in the foundation service MUST be performed there939495### Validation Test Derivation from Storage Configuration96970. Storage configuration (`StorageBroker.[Entity].Configurations.cs`) defines **constraints**, not validation behavior.98991. For every constraint defined in storage configuration, there MUST exist a corresponding validation rule in the foundation service:100 - Required fields101 - Length constraints (min/max)102 - Precision / format constraints where applicable1031042. Validation tests MUST:105 - Target the **foundation service validation methods only**106 - NOT directly test storage configuration behavior107 - Prove that each storage-defined constraint is enforced at the foundation layer1081093. For each property constraint, validation tests MUST focus on constraint violations and boundary breaches:110111 - Invalid case (violates constraint) → FAIL112 - Required field missing / null113 - Value exceeding maximum length114 - Value below minimum length (if applicable)115116 - Boundary violation cases:117 - Just above maximum → FAIL118 - Just below minimum → FAIL (if applicable)1191204. Valid scenarios (within acceptable range) are covered by logic tests and MUST NOT be redundantly tested in validation tests.1211225. Missing alignment between storage configuration and foundation validation MUST be treated as:123 - A design defect124 - A test failure condition125 - A review blocker1261276. Automation MAY assist in identifying constraints (e.g., via EF metadata), but:128 - Generated tests MUST still validate foundation behavior129 - Automation MUST NOT result in tests that validate the database layer directly1301317. All validation tests MUST:132 - Follow Standard naming conventions133 - Be explicit and intention-revealing134135136### Validation order1371380. Structural validations first.1391. Logical validations second.1402. External validations third.1413. Dependency validations when the external resource is the source of the failure.142143### Circuit-breaking validations1441450. Null checks and other hard-stop guards must break immediately.1461. If continuing would create invalid dereference or meaningless work, stop immediately.147148### Continuous validations1491500. When multiple fields can be invalid independently, collect them before throwing.1511. Use upsertable exception data.1522. Use dynamic rules with condition + message.1533. Use a validations collector routine.1544. Throw once the collector contains errors.155156### Hybrid continuous validations1571580. Validate parent objects before validating child properties.1591. Split nested validation into levels to avoid unintended null-reference failures.160161## Foundation-service test rules1621630. Test the happy path first.1641. Then test structural validations.1652. Then test logical validations.1663. Then test external validations.1674. Then test dependency validations.1685. Then test dependency exceptions.1696. Then test service exceptions.1707. Always verify logging and broker calls.1718. Always verify no unwanted calls occurred.1729. Always keep validation and exception behaviors local and explicit.173174## Processing-service test rules1751760. Test higher-order logic, not primitive broker details.1771. Validate only what the processing service uses.1782. Test shifters.179 - Example: object -> bool or object -> count.1803. Test combinations.181 - Example: retrieve + add, retrieve + modify, ensure-exists, upsert.1824. Test processing exception mapping from foundation exceptions.183184## Orchestration-service test rules1851860. Test multi-entity flow combinations.1871. Test mapping/branching between contracts when present.1882. Test call order when the flow depends on order.1893. Prefer natural order when inputs/outputs force sequencing.1904. Use explicit order verification when sequencing is not naturally encoded.1915. Verify orchestration-level exception wrapping and unwrapping.1926. Test normalization outcomes indirectly through dependency shape and resulting behavior.193194## Aggregation-service test rules1951960. Do not test dependency call order in aggregation services.1971. Do not use mock-sequence style order assertions for aggregation services.1982. Test only basic structural validations and exposure-level aggregation behavior.1993. Aggregation services may multi-call or pass-through; test the contract and exposure abstraction, not orchestration logic.200201## Controller and protocol test rules2022030. Controllers require unit tests for mapping logic.2041. Unit-test success code mappings.2052. Unit-test validation / dependency / service error mappings.2063. Unit-test security i.e authorization / authentication failure mappings.2073. Acceptance-test every endpoint.2084. Clean up test data after acceptance tests.2095. Emulate external resources not owned by the microservice when running acceptance tests.2106. Integration and end-to-end testing are valid beyond unit + acceptance.211212## UI component test rules213214### Base components2152160. Treat bases as thin wrappers.2171. Test their exposed APIs and wrapper behavior when needed.2182. Do not put business logic into bases.219220### Core components2212220. Core components are test-driven.2231. Test elements.224 - Existence225 - Properties226 - Actions2272. Existence may be tested by property assignment, searching by id, or general search.2283. Test styles when styles are part of the component contract.2294. Test actions that mutate state, create components, or trigger service calls.2305. Core components should integrate with one and only one view service.231232### Pages / containers2332340. Pages are simpler route containers.2351. They generally do not require unit tests.2362. They should not contain business logic.237238## Unit-test conventions from the supplied implementation profile2392400. Mirror partial-class split in tests.2411. Use setup/helpers in the root test file.2422. Split tests into logic, validations, and exceptions files.2433. Use GWT: Given / When / Then.2444. Mock all dependencies.2455. Use readable assertions.2466. Use deep cloning to protect expectation identity.2477. Use randomized data by default.2488. Verify exact dependency calls.2499. End with VerifyNoOtherCalls.25010. Keep naming explicit and scenario-driven.251252## Exact test implementation order for foundation-service add routines253254When implementing an Add{Entity}Async routine under the implementation profile, follow this order:2552560. ShouldAdd{Entity}Async2571. ShouldThrowValidationExceptionOnAddIf{Entity}IsNullAndLogItAsync2582. ShouldThrowValidationExceptionOnAddIf{Entity}IsInvalidAndLogItAsync2593. ShouldThrowDependencyValidationExceptionOnAddIfBadRequestErrorOccursAndLogItAsync2604. ShouldThrowDependencyValidationExceptionOnAddIfConflictErrorOccursAndLogItAsync2615. ShouldThrowCriticalDependencyExceptionOnAddIfUnauthorizedErrorOccursAndLogItAsync2626. ShouldThrowCriticalDependencyExceptionOnAddIfForbiddenErrorOccursAndLogItAsync2637. ShouldThrowCriticalDependencyExceptionOnAddIfNotFoundErrorOccursAndLogItAsync2648. ShouldThrowCriticalDependencyExceptionOnAddIfUrlNotFoundErrorOccursAndLogItAsync2659. ShouldThrowDependencyExceptionOnAddIfInternalServerErrorOccursAndLogItAsync26610. ShouldThrowDependencyExceptionOnAddIfServiceUnavailableErrorOccursAndLogItAsync26711. ShouldThrowCriticalDependencyExceptionOnAddIfHttpRequestErrorOccursAndLogItAsync26812. ShouldThrowServiceExceptionOnAddIfServiceErrorOccursAndLogItAsync269270For storage-based services, substitute the storage equivalents such as duplicate-key, DbUpdate, and SQL exceptions.271272## Testing and exception/localization addendum from the supplied implementation profile273274## 8. Unit Testing275276Unit tests follow The Standard's **partial-class + three-axis** approach.277278### 8.1 Test Class Structure279280Each entity's tests mirror the same partial-class split as the service:281282| Partial file | Tests |283| ------------------------------------------------- | ------------------------------------------------------ |284| `{Entity}ServiceTests.cs` | Setup, mocks, helpers (`CreateRandom{Entity}`, etc.) |285| `{Entity}ServiceTests.Logic.{Method}.cs` | Happy-path / success-case tests |286| `{Entity}ServiceTests.Validations.{Method}.cs` | Validation failure tests |287| `{Entity}ServiceTests.Exceptions.{Method}.cs` | Dependency & service exception tests |288289### 8.2 Conventions290291| Convention | Detail |292| -------------------- | ------------------------------------------------------------------------------------------- |293| Mocking | **Moq** — `Mock<IStorageBroker>`, `Mock<IModernApiBroker>`, `Mock<ILoggingBroker>` |294| Assertions | **FluentAssertions** — `Should().BeEquivalentTo()` |295| Deep cloning | **DeepCloner** — to isolate input/expected/actual objects |296| Data generation | **Tynamix.ObjectFiller** — `Filler<{Entity}>` with custom property setup |297| Exception comparison | `Xeption.SameExceptionAs()` via `SameExceptionAs` expression helper |298| Test naming | `Should{Action}Async` / `ShouldThrow{Exception}On{Action}If{Condition}AndLogItAsync` |299| Verify calls | Every test verifies broker calls (`Times.Once` / `Times.Never`) and ends with `VerifyNoOtherCalls()` |300| Test framework | **xUnit** — `[Fact]` for single cases, `[Theory] [InlineData]` for parameterised cases |301302### 8.3 Test Pattern — GWT (Given / When / Then)303304```305// given — build input, configure mocks, construct expected exception306// when — invoke the service method307// then — assert result / exception, verify broker interactions308```309310### 8.4 Test Implementation Order311312Tests **must** be written and committed in the following strict order. This ordering ensures313each category builds upon the prior one:3143151. **Happy Path** — `ShouldAdd{Entity}Async`3162. **Structural Validations** — null entity check (`ShouldThrowValidationExceptionOnAddIf{Entity}IsNullAndLogItAsync`)3173. **Logical Validations** — property-level checks using `[Theory] [InlineData]` (`ShouldThrowValidationExceptionOnAddIf{Entity}IsInvalidAndLogItAsync`)3184. **External Dependency Validation Exceptions** — `BadRequest` → `Conflict`3195. **External Critical Dependency Exceptions** — `Unauthorized` → `Forbidden` → `NotFound` → `UrlNotFound`3206. **External Non-Critical Dependency Exceptions** — `InternalServerError` → `ServiceUnavailable`3217. **Transport-Level Exception** — `HttpRequestException`3228. **Catch-All Service Exception** — `Exception`323324For storage-based services, steps 4–7 are replaced with the corresponding SQL/EF exceptions325(`DuplicateKeyException`, `DbUpdateException`, `SqlException`).326327> **Rule — Test Verification Before Commit:** Each FAIL commit must have the test328> **actually running and failing**. Each PASS commit must have **all** tests329> running and passing. Never commit a FAIL without verifying the test runner330> reports a genuine failure. See [Section 12.1.3 — Commits](#1213-commits) for details.331332---333334## 9. Key Libraries335336| Package | Purpose |337| ---------------------- | ------------------------------------------------- |338| `Xeption` | Enhanced exceptions with data aggregation |339| `EFxceptions` | EF Core wrapper that throws meaningful exceptions |340| `RESTFulSense` | HTTP client wrapper for external API brokers |341| `Moq` | Mock framework for unit tests |342| `FluentAssertions` | Readable assertion syntax |343| `DeepCloner` | Value-based deep cloning of test objects |344| `Tynamix.ObjectFiller` | Random test data generation |345| `xunit` | Unit test framework |346347---348349## Exception Handling Principles350351### 0. Scope352353These rules govern exception design, localisation, categorisation, propagation, and testing across all service layers.354355---356357### 1. Localisation (MANDATORY)3583590. External (non-local) exceptions MUST be localised at the boundary (Foundation).3601. Native exceptions (SQL, HTTP, SDK) MUST NOT cross service boundaries.3612. Localisation MUST convert native exceptions into domain-specific exceptions.362363**Data Preservation (MANDATORY)**3643653. ALL relevant data from the external exception MUST be copied to the local exception:366 - `Data` dictionary367 - Constraint / validation metadata368 - Identifiers / keys3693704. The localised exception MUST carry this data so that:371 - The **immediate inner exception** contains full validation detail after categorisation.372373---374375### 2. Categorisation3763770. All exceptions MUST be categorised into one of:378 - Validation379 - DependencyValidation380 - Dependency381 - Service3823831. Categorisation defines upstream handling and exposer mapping.384385---386387### 3. Propagation (Unwrap / Rewrap)388389Each service layer MUST:3903910. Catch downstream exceptions 3921. UNWRAP the categorical exception 3932. PRESERVE the LOCAL exception 3943. REWRAP into its OWN categorical exception 395396This prevents leakage of lower-layer concerns and enforces layer contracts.397398---399400### 4. Inner Exception Preservation (MANDATORY)4014020. The original local exception MUST always be preserved as the inner exception.4031. No layer may discard or replace the local exception.404405This guarantees:406- Traceability407- Correct exposer mapping (e.g. HTTP Conflict / FailedDependency)408- Retention of validation data409410---411412### 5. Layer Responsibilities413414#### Foundation4150. Localise external exceptions 4161. Populate local exception data 4172. Categorise into Validation / DependencyValidation / Dependency / Service 418419#### Processing4200. MUST ONLY handle categorised exceptions 4211. MUST NOT depend on foundation exception types 4222. MUST rewrap into processing-level exceptions 423424#### Orchestration4250. MUST handle exceptions from all dependencies 4261. MUST unify into a single categorical exception per type 4272. MUST unwrap and preserve inner exceptions 428429---430431### 6. Catch-All (MANDATORY)4324330. Every service MUST implement:434 - `catch (Exception)`4351. MUST map to ServiceException436437This prevents leakage of unknown failures.438439---440441### 7. Logging4424430. Each layer MUST log BEFORE rethrowing 4441. MUST log the categorised exception only 445446---447448### 8. Testing449450#### Orchestration Exception Tests4514520. SHOULD use `[Theory]` 4531. MUST cover multiple dependency exception types in a single test 4542. MUST avoid duplication 455456---457458### 9. Design Intent459460These rules ensure:4614620. Full abstraction from external systems 4631. Stable layer contracts 4642. Simplified exposer logic 4653. Complete validation visibility at the local exception level 466467---468469## Exception Handling Cross-References (Enforcement)470471### Validation Testing Alignment4724730. All validation tests MUST align with Exception Handling Principles:474 - Localisation MUST be verified (no native exceptions exposed)475 - Data preservation MUST be verified on local exceptions476 - Validation exceptions MUST contain full error details in inner exception477 - From processing service layer upwards, validation exceptions and dependency validation exceptions from its dependencies rewrap to [Entity][Layer]DependencyValidationExceptions 478 - From processing service layer upwards, dependency exceptions and service exceptions from its dependencies rewrap to [Entity][Layer]DependencyExceptions4794801. Validation tests MUST assert:481 - Correct local exception type482 - Correct categorised exception type483 - Inner exception contains validation data (Data dictionary populated)484485---486487### Foundation Exception Tests (Enforcement)4884890. Tests MUST verify localisation:490 - Native exception → Local exception → Categorised exception4914921. Tests MUST verify:493 - External exception data is copied to local exception494 - Local exception is preserved as inner exception4954962. Tests MUST NOT allow:497 - Native exception leakage498 - Missing Data dictionary propagation499500---501502### Processing Exception Tests (Enforcement)5035040. Tests MUST assert:505 - Rewrapping into processing-level exception506 - Inner exception preservation5075081. Tests SHOULD:509 - Use `[Theory]` to test multiple dependency validation exceptions of the same type in one test 510 - Use `[Theory]` to test multiple dependency exceptions of the same type in one test511 - Avoid duplication by testing multiple cases in a single test method512513---514515### Orchestration Exception Tests (Enforcement)5165170. Tests MUST assert:518 - Rewrapping into orchestration-level exception 519 - Inner exception is preserved (local exception)520 - Categorical exception is replaced at orchestration level5215221. Tests SHOULD:523 - Use `[Theory]` to test multiple dependency validation exceptions of the same type in one test 524 - Use `[Theory]` to test multiple dependency exceptions of the same type in one test525 - Avoid duplication by testing multiple cases in a single test method526527---528529### Catch-All Enforcement5305310. Tests MUST verify:532 - Unknown exceptions are mapped to ServiceException533 - No raw Exception escapes any service layer534535---536537### Logging Enforcement5385390. Tests MUST verify:540 - Logging occurs before exception is thrown541 - Logged exception is the categorised exception542543---544545### Design Integrity Rule5465470. Any violation of exception handling principles MUST be treated as:548 - A design defect549 - A test failure550 - A review blocker