Quality & GrowthComplete guide

Testing

Testing provides layered evidence that units, integrations, contracts, and complete user flows behave as intended.

Overview

A production test strategy allocates evidence according to risk. Unit tests give fast, deterministic feedback on policy and edge cases; integration tests exercise real framework, serialization, persistence, and authentication boundaries; contract tests protect the shape and meaning exchanged between independently changing components; and a deliberately small set of end-to-end tests proves critical user outcomes in a deployed environment. Test doubles belong at narrow controllable boundaries, not around every class. Reliable suites control time, randomness, identifiers, concurrency, data, and asynchronous completion. They report the violated behavior clearly, run independently in any order, and fail for one diagnosable reason. Coverage is a gap-finding signal rather than a quality target. Teams should define test ownership, quarantine rules, retry policy, fixtures, data reset, and CI lanes, then track flake rate and time-to-diagnosis alongside pass rate.

What you will learn

  • Map test levels to concrete product risks.
  • Write deterministic behavior-focused unit tests.
  • Exercise the real ASP.NET Core HTTP pipeline.
  • Protect success and error contracts.
  • Control fixtures, time, data, and concurrency.
  • Operate a fast and trusted CI suite.

Prerequisites

  • C# async code, dependency injection, HTTP, and JSON fundamentals.
  • A list of critical journeys and expensive failure modes.
  • Basic xUnit or equivalent test-runner experience.

When to use Testing

Good fit

  • Unit tests for dense deterministic policy.
  • Integration tests where framework or provider behavior matters.
  • End-to-end tests for a small set of critical journeys.

Choose another approach when

  • Mocking every internal collaborator.
  • Using one test level for every risk.
  • Retrying failures until a flaky suite looks green.

Key concepts

Risk-based strategy

Choose evidence from failure impact and uncertainty instead of enforcing a fixed pyramid quota.

Unit tests

Exercise deterministic policy and edge cases quickly without infrastructure or process boundaries.

Integration tests

Verify real framework, database, HTTP, serialization, identity, or broker behavior at selected boundaries.

Contract tests

Protect request, response, event, and error compatibility between producers and consumers.

End-to-end journeys

Prove a few business-critical outcomes through the deployed surface and its real integrations.

Test doubles

Use fakes, stubs, or mocks at narrow outbound seams when control or observation is valuable.

Determinism and isolation

Control time, randomness, concurrency, and data so tests can run independently in any order.

Suite operations

Flake ownership, diagnostics, parallel lanes, and failure triage determine whether tests remain trusted.

Architecture

A balanced suite gives broad, fast domain feedback and progressively narrower but higher-fidelity checks at system boundaries.

Unit tests
Integration tests
Contract tests
Critical journeys

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The sample separates deterministic order policy tests from real ASP.NET Core HTTP integration, validation-contract checks, and a create-then-read journey.

  1. 01
    List risks

    Rank critical outcomes, complex policy, integration uncertainty, and costly regressions.

  2. 02
    Assign evidence

    Select the cheapest test level that can reveal each important failure.

  3. 03
    Create deterministic seams

    Inject time and external boundaries while keeping domain objects concrete.

  4. 04
    Test policy

    Cover nominal behavior, boundaries, invalid input, and invariants with fast unit tests.

  5. 05
    Test integrations

    Run the actual HTTP pipeline, serialization, middleware, and provider where behavior differs.

  6. 06
    Protect contracts

    Assert stable success, validation, error, and event shapes without overspecifying internals.

  7. 07
    Operate the suite

    Parallelize safe tests, capture diagnostics, measure flakes, and remove redundant slow checks.

Code example

A useful test names the behavior, arranges only relevant state, and asserts an externally meaningful outcome.

OrderTests.cs
public sealed class OrderTests
{
    [Fact]
    public void AddLine_WhenQuantityIsZero_RejectsChange()
    {
        var order = Order.Create(CustomerId.New());

        var action = () => order.AddLine(ProductId.New(), quantity: 0);

        action.Should().Throw<DomainException>()
            .WithMessage("Quantity must be positive.");
        order.Lines.Should().BeEmpty();
    }
}

Testing strategy

The testing system itself needs tests and operational rules.

  • Prove tests fail when the behavior is deliberately broken.
  • Run in random order and in parallel.
  • Repeat timing-sensitive tests under stress.
  • Validate fixtures clean up after cancellation.
  • Track runtime and flake rate per lane.
  • Review contract changes as API changes.

Security considerations

Tests must verify authorization boundaries without turning secrets or personal data into fixtures.

  • Include negative authorization tests.
  • Use synthetic non-sensitive data.
  • Keep secrets outside source and test output.
  • Redact captured requests and snapshots.
  • Test abuse limits and validation.

Performance and scalability

Fast feedback is a product feature of the suite.

  • Keep policy tests in the fastest lane.
  • Share expensive immutable fixtures safely.
  • Parallelize isolated tests.
  • Move only critical journeys to end-to-end.
  • Profile slow tests before adding retries.

Deployment and operations

Different evidence runs at different release stages.

  • Run unit and focused integration tests on every change.
  • Run provider and contract tests before merge.
  • Run smoke tests after deployment.
  • Gate promotion on critical journeys.
  • Retain artifacts and diagnostics for failures.

Common problems and fixes

A test passes alone but fails in suite.

Likely cause: State, port, clock, or data is shared.

Fix: Give each test isolated state and remove ordering assumptions.

Async test hangs.

Likely cause: Work is not awaited or cancellation is ignored.

Fix: Await completion, apply a timeout, and propagate cancellation.

Mocks break after refactoring.

Likely cause: Tests specify internal collaboration.

Fix: Assert observable outcomes and mock only stable boundaries.

Integration result differs in production.

Likely cause: A substitute does not match the real provider.

Fix: Use provider-real infrastructure for provider behavior.

Suite is green after retries.

Likely cause: Retry hides nondeterminism.

Fix: Quarantine with ownership and fix the uncontrolled input.

Failures reveal no cause.

Likely cause: Assertions and captured context are vague.

Fix: Name behavior, keep assertions focused, and attach diagnostics.

Best practices

  • Test observable behavior.
  • Choose levels from risk.
  • Control time and randomness.
  • Use real providers where semantics matter.
  • Keep fixtures isolated.
  • Treat flakes as defects.
  • Capture useful failure evidence.
  • Delete redundant slow tests.

Production checklist

  • Critical risks map to test evidence.
  • Unit tests are deterministic and fast.
  • Real boundaries have integration coverage.
  • Success and error contracts are protected.
  • Authorization has negative tests.
  • Fixtures isolate data and clean up.
  • Flake rate and duration are owned.
  • Post-deploy smoke evidence is retained.

Common interview questions

What should be mocked?

Mock narrow outbound boundaries when controlling behavior is valuable; keep domain collaborators concrete.

Unit versus integration test?

A unit test isolates deterministic policy; an integration test verifies collaboration with a real framework or provider boundary.

What is a contract test?

It verifies the shape and meaning one component promises another without requiring the entire deployed journey.

How do you reduce flakes?

Control time, concurrency, data, ports, and async completion, then assign ownership instead of retrying blindly.

Why not maximize code coverage?

Coverage shows executed lines, not meaningful assertions, missing risks, or production compatibility.

When is an end-to-end test justified?

For a small business-critical journey whose value depends on the deployed components working together.

How should CI tests be layered?

Fast deterministic checks first, provider and contract evidence before merge, and deployment smoke journeys after release.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Testing Orders API

A .NET 10 API demonstrating deterministic unit tests, ASP.NET Core HTTP integration, validation contracts, and a critical create-then-read journey.

ASP.NET Core 10xUnitWebApplicationFactoryTimeProvider
dedicated-sampleunit-testingintegration-testingcontract-testing
Run
dotnet run --project src/TestingOrdersApi
Test
dotnet test TestingOrdersApi.slnx