← All blogs

FullStack Engineering CourseLesson 17 of 20 23 min

Testing: From Unit Tests to Load, Chaos and Security Testing

A test strategy, not just tests

Tests exist to let a team change code with confidence. A good test suite catches real problems, runs fast enough to run on every change, fails only when something is actually broken, and does not need rewriting every time the code is refactored. Getting there needs a strategy: which kinds of test to write, for what, and how many.

Kind of testChecksSpeedExample
UnitOne small piece of logic in isolationMillisecondsThe fee calculation for a Medicare claim
IntegrationYour code together with real infrastructure: database, queues, HTTP pipelineSecondsPOST /claims stores the claim in SQL Server and returns 201
ContractThat a provider API still matches what its consumers expectSecondsThe Claims API still returns the fields the web app relies on
End-to-end (E2E)A whole user journey through the real UI and servicesMinutesA biller logs in, submits a claim and sees it as Pending
PerformanceSpeed and stability under loadMinutes to hours50 submissions per second with p95 under 300 ms
ChaosBehaviour when infrastructure failsVariesThe API degrades gracefully when Redis goes down
SecurityVulnerabilities in code, dependencies and the running appVariesNo SQL injection; no packages with known vulnerabilities

The test pyramid and the honeycomb

The classic test pyramid recommends many unit tests at the bottom, fewer integration tests in the middle and a handful of end-to-end tests at the top, because tests get slower, more fragile and more expensive as they go up.

For services that are mostly about integration (an API that validates input, stores it and publishes an event), the testing honeycomb fits better. It puts most effort into integration tests of each service through its real API, with real infrastructure in containers, plus unit tests for complex logic and very few end-to-end tests. These tests check what users actually depend on, and they survive refactoring because they do not test internal structure.

Whichever shape you choose, the rule is the same: test behaviour, not implementation. A test should fail when the behaviour breaks, not when someone renames a private method.

Unit tests with xUnit

Unit tests are best for logic with many cases: business rules, calculations, validation, parsing. Structure each test as Arrange, Act, Assert, and name it after the behaviour it checks:

C#
public class ClaimTests
{
    [Fact]
    public void Submit_without_lines_is_rejected()
    {
        // Arrange
        var claim = new Claim(new ClaimId(42));

        // Act
        var act = () => claim.Submit();

        // Assert
        var error = Assert.Throws<DomainException>(act);
        Assert.Contains("at least one line", error.Message);
    }

    [Fact]
    public void Submit_raises_ClaimSubmitted_with_the_total()
    {
        var claim = new Claim(new ClaimId(42));
        claim.AddLine("99213", new Money(1200m, "INR"));
        claim.AddLine("85025", new Money(300m, "INR"));

        claim.Submit();

        var evt = Assert.Single(claim.DomainEvents.OfType<ClaimSubmitted>());
        Assert.Equal(new Money(1500m, "INR"), evt.Total);
    }

    [Theory]                                            // one test, many cases
    [InlineData(1000, 20)]
    [InlineData(0, 0)]
    [InlineData(99.99, 2)]
    public void Medicare_fee_is_two_percent_rounded(decimal amount, decimal expectedFee)
    {
        var rule = new MedicareFeeRule();
        Assert.Equal(expectedFee, Math.Round(rule.Calculate(new ClaimRecord { Amount = amount }), 0));
    }
}

Test doubles replace dependencies in unit tests. Prefer the simplest one that works:

  • A fake: a working lightweight implementation, such as an in-memory repository, or FakeTimeProvider for time (lesson 3).
  • A stub: returns fixed answers to calls.
  • A mock (NSubstitute or Moq): records calls so a test can check that something was called. Use mocks for important outgoing actions ("an email was sent"), not to check every internal call, or tests break on every refactor.

Do not mock what you do not own, such as DbContext or HttpClient internals. Test those through integration tests with real infrastructure instead.

Test-driven development (TDD) writes the test first: write a failing test (red), write the simplest code that passes (green), then improve the code with the test as a safety net (refactor). It works especially well for business rules and bug fixes: first write a test that reproduces the bug. Behaviour-driven development (BDD) describes behaviour as Given/When/Then scenarios in language the business can read, sometimes run as tests with tools such as Reqnroll (the successor to SpecFlow).

Integration tests with WebApplicationFactory and Testcontainers

Integration tests run the real application in memory, with its real middleware, dependency injection, serialisation and database access. WebApplicationFactory starts the app inside the test process. Testcontainers starts real dependencies (SQL Server, PostgreSQL, Redis, even Service Bus emulators) in Docker containers for the test run, so tests use the same database engine as production, not an in-memory imitation that behaves differently.

C#
// Packages: Microsoft.AspNetCore.Mvc.Testing, Testcontainers.MsSql, xunit.v3
public sealed class ClaimsApiFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
    private readonly MsSqlContainer _sql = new MsSqlBuilder().Build();   // a real SQL Server in Docker

    public async ValueTask InitializeAsync()
    {
        await _sql.StartAsync();
        using var scope = Services.CreateScope();
        await scope.ServiceProvider.GetRequiredService<ClaimsDbContext>().Database.MigrateAsync();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder) =>
        builder.ConfigureTestServices(services =>
        {
            services.RemoveAll<DbContextOptions<ClaimsDbContext>>();
            services.AddDbContext<ClaimsDbContext>(o => o.UseSqlServer(_sql.GetConnectionString()));
            services.AddAuthentication(TestAuthHandler.Scheme)                        // a fake sign-in for tests
                    .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.Scheme, _ => { });
        });

    public override async ValueTask DisposeAsync()
    {
        await _sql.DisposeAsync();
        await base.DisposeAsync();
    }
}

public sealed class SubmitClaimTests(ClaimsApiFactory factory) : IClassFixture<ClaimsApiFactory>
{
    [Fact]
    public async Task Posting_a_valid_claim_returns_201_and_stores_it()
    {
        HttpClient client = factory.CreateClient();
        var request = new { providerId = 7, externalReference = $"EXT-{Guid.NewGuid()}", lines = new[] { new { code = "99213", amount = 1200m } } };

        var response = await client.PostAsJsonAsync("/api/v1/claims", request, TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        var created = await response.Content.ReadFromJsonAsync<ClaimDto>(TestContext.Current.CancellationToken);
        var fetched = await client.GetFromJsonAsync<ClaimDto>(response.Headers.Location, TestContext.Current.CancellationToken);
        Assert.Equal(created!.Id, fetched!.Id);
    }

    [Fact]
    public async Task Posting_a_claim_without_lines_returns_400_with_problem_details()
    {
        var response = await factory.CreateClient().PostAsJsonAsync("/api/v1/claims",
            new { providerId = 7, externalReference = "EXT-1", lines = Array.Empty<object>() }, TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
    }
}

Practical points:

  • Share one container per test class or per test run (fixtures), because starting containers takes seconds.
  • Keep tests independent: use unique data per test (as with the GUID above), or reset the database between tests with a tool such as Respawn.
  • Replace only what you cannot run locally (third-party APIs, the real identity provider) with fakes or WireMock-style HTTP stubs. Keep everything else real.
  • These tests run in CI too: hosted GitHub Actions runners and most Azure DevOps agents have Docker available.

Contract testing with Pact

With many services, end-to-end tests become slow and fragile, yet you still need to know that a change to the Claims API will not break the web app or the billing service. Contract testing checks this without running everything together. In consumer-driven contract testing with Pact:

  1. Each consumer (for example, the web app) writes tests against a Pact mock server, describing the requests it makes and the parts of the responses it uses.
  2. Running those tests produces a contract file (a "pact") listing those expectations.
  3. The pact is published to a Pact Broker (or PactFlow), a shared store of contracts.
  4. The provider (the Claims API) runs a verification step in its own pipeline: Pact replays each consumer's requests against the real provider and checks the responses match.
  5. Before deploying either side, a can-i-deploy check asks the broker whether the versions about to be deployed are compatible.

Because consumers only list the fields they actually use, the provider can still add fields or change unused ones freely. Contract tests complement, rather than replace, OpenAPI schema checks (lesson 4): the schema says what the API offers, and the pacts say what consumers really depend on.

End-to-end and UI tests

End-to-end tests drive a real browser through key user journeys. Playwright (with TypeScript or .NET) is a common choice. It waits automatically for elements to be ready, which removes the main cause of flaky UI tests (tests that sometimes pass and sometimes fail with no code change):

TypeScript
import { test, expect } from "@playwright/test";

test("a biller submits a claim and sees it as pending", async ({ page }) => {
  await page.goto("/claims/new");
  await page.getByLabel("Provider").selectOption("City Hospital");
  await page.getByLabel("Procedure code").fill("99213");
  await page.getByLabel("Amount").fill("1200");
  await page.getByRole("button", { name: "Submit claim" }).click();

  await expect(page.getByRole("status")).toHaveText(/Pending/);   // waits until it appears
});

Keep end-to-end tests few and focused on the journeys that matter most (sign in, submit, approve, pay). Find elements by role and label, as users do, not by CSS classes that change with styling; this also checks basic accessibility. Give each test its own data, and run them against a dedicated test environment.

For React components, Jest or Vitest with React Testing Library test components the way users use them: render, find by role or label, click or type, check what appears. The front-end lessons cover these.

Performance testing with k6

Functional tests do not show how a system behaves under load. k6 is an open-source load-testing tool where tests are written in JavaScript, and thresholds turn your SLOs (lesson 16) into pass or fail criteria that can run in a pipeline:

JavaScript
import http from "k6/http";
import { check, sleep } from "k6";
import { uuidv4 } from "https://jslib.k6.io/k6-utils/1.4.0/index.js";

export const options = {
  stages: [
    { duration: "2m", target: 50 },     // ramp up to 50 virtual users
    { duration: "10m", target: 50 },    // hold
    { duration: "2m", target: 0 },      // ramp down
  ],
  thresholds: {
    http_req_failed: ["rate<0.001"],                     // fewer than 0.1% errors
    http_req_duration: ["p(95)<300", "p(99)<1000"],      // the SLO, in milliseconds
  },
};

export default function () {
  const body = JSON.stringify({ providerId: 7, externalReference: uuidv4(), lines: [{ code: "99213", amount: 1200 }] });
  const res = http.post(`${__ENV.BASE_URL}/api/v1/claims`, body, {
    headers: { "Content-Type": "application/json", "Idempotency-Key": uuidv4() },
  });
  check(res, { "claim created": (r) => r.status === 201 });
  sleep(1);
}

Different shapes of load answer different questions:

TestLoadFinds
Load testExpected normal and peak trafficWhether SLOs are met at expected load
Stress testIncreasing until it breaksThe breaking point, and whether it fails gracefully and recovers
Soak testNormal load for hoursMemory leaks, connection pool exhaustion, slow growth in latency
Spike testA sudden jump in trafficWhether autoscaling and rate limits react fast enough

Run load tests against an environment sized like production, with realistic data volumes, and watch the server metrics (CPU, GC, thread pool, database) during the test, not only the k6 results.

Chaos engineering

Chaos engineering checks resilience (lesson 7) by causing failures on purpose, in a controlled way:

  1. Define the steady state: the normal values of key metrics, such as successful submissions per minute.
  2. Form a hypothesis: "if Redis becomes unavailable, submissions continue with p95 under 500 ms".
  3. Inject the failure, starting small (one instance, in a test environment): stop a dependency, add network latency, fill a disk, kill pods.
  4. Compare the result with the hypothesis, fix what was wrong, and repeat with a larger scope.

Azure Chaos Studio provides ready-made faults for Azure resources (shutting down VMs, adding latency, failing over Cosmos DB, Chaos Mesh faults in AKS). Game days, planned sessions where the team runs failure scenarios together, also test the human side: alerts, runbooks and on-call response.

Mutation testing

Code coverage shows which lines tests run, not whether tests would notice a bug in them. A test that calls a method without checking its result gives full coverage and no protection. Mutation testing measures the real strength of tests: a tool such as Stryker.NET makes small changes to the code (mutants), such as changing > to >=, + to -, or removing a call, and runs the tests against each one. If the tests still pass, the mutant survived, which shows a gap in the tests. The mutation score is the share of mutants killed.

Shell
dotnet tool install -g dotnet-stryker
cd tests/Claims.Domain.Tests
dotnet stryker            # produces an HTML report of surviving mutants

Mutation testing is slow, so run it on important domain projects, or only on changed code in pull requests, rather than on everything.

Security testing

KindWhat it doesTools
SAST (static application security testing)Analyses source code for vulnerable patterns without running itCodeQL (GitHub Advanced Security), SonarQube, Roslyn security analysers
SCA (software composition analysis)Finds dependencies with known vulnerabilities and licence problemsDependabot, Renovate, dotnet list package --vulnerable, npm audit
Secret scanningFinds keys and passwords committed to the repositoryGitHub secret scanning, Gitleaks
DAST (dynamic application security testing)Attacks the running application from outside, like an attacker wouldOWASP ZAP, Burp Suite
Container and IaC scanningFinds vulnerable base images and insecure infrastructure settingsTrivy, Microsoft Defender for Cloud, Checkov

Run SAST, SCA, secret scanning and image scanning on every pull request, and DAST against the test environment on a schedule. Penetration tests by specialists add a deeper check before major releases.

Keeping the suite healthy

  • Fix or remove flaky tests quickly. A suite that fails randomly teaches people to ignore failures.
  • Keep the pull-request suite fast (ideally under 10 minutes), and run slower suites (E2E, load, mutation) on a schedule or before release.
  • Use coverage to find untested areas, not as a target. A coverage target encourages tests that run code without checking anything.
  • Treat test code as production code: readable, reviewed and refactored.

Check your understanding

QuestionShort answer
Pyramid or honeycomb?The pyramid stresses unit tests; the honeycomb stresses integration tests through the real API, which suits integration-heavy services.
What should a test check?Behaviour, not implementation details, so it survives refactoring.
Fake, stub or mock?A fake is a working lightweight implementation; a stub returns fixed answers; a mock records calls for verification.
Why Testcontainers instead of an in-memory database?Tests run against the same database engine as production, so they catch real SQL behaviour.
What does WebApplicationFactory do?Runs the real ASP.NET Core app in memory for tests, with services that can be replaced.
What is consumer-driven contract testing?Consumers record what they use from an API; the provider verifies those contracts in its own pipeline.
How do you reduce flaky UI tests?Auto-waiting tools such as Playwright, locators by role and label, and independent test data.
Load, stress, soak or spike test?Load checks SLOs at expected traffic; stress finds the breaking point; soak finds slow leaks; spike checks sudden jumps.
What is mutation testing?Changing the code slightly and checking that tests fail; surviving mutants reveal weak tests.
SAST or DAST?SAST analyses source code; DAST attacks the running application.

Summary

  • Choose a test strategy: unit tests for complex logic, integration tests through the real API with real infrastructure, and few E2E tests.
  • Write tests about behaviour, with clear names and the simplest test doubles.
  • Use WebApplicationFactory and Testcontainers for integration tests, with independent data.
  • Use contract tests with Pact to change services independently and safely.
  • Turn SLOs into k6 thresholds, and run load, stress, soak and spike tests where they matter.
  • Prove resilience with chaos experiments, measure test strength with mutation testing, and automate security scanning.
  • Keep the suite fast and trustworthy: no flaky tests, no coverage targets for their own sake.

The next lesson moves to the front end: React architecture, state management with Redux, Context and TanStack Query, optimistic updates, error boundaries, Next.js rendering modes, design systems with Storybook, and monorepos.

Found this useful? Share it: LinkedIn X

Comments