Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 8 · Lesson 71 · 7 min read

Testing Pyramid for Full-Stack Apps

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Test Plan for Moving a Task, by Layer
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Choose the right kind of test for each risk across a React and .NET system, balance speed against confidence using the test pyramid and the testing trophy, plan tests for a feature by layer including security, and keep the suite fast, deterministic and trustworthy.

Concept Explanation

Tests exist to let you change code without fear, and every test type trades three things: how fast it runs, how much of the real system it exercises, and how easily it breaks for reasons unrelated to bugs. Unit tests are fast and precise but only prove that a piece works alone. End-to-end tests drive a real browser against a real deployment and prove the whole thing works, but they are slow and flaky. The test pyramid, described by Mike Cohn in 2009, says to write many unit tests, fewer integration tests, and very few end-to-end tests. Google's testing blog made the same argument in 2015, suggesting roughly a 70, 20, 10 split and warning that leaning on end-to-end tests leads to slow, unreliable pipelines.

Modern full-stack teams often adjust the shape. The testing trophy, associated with Kent C. Dodds, puts most of the weight on integration tests, because in a framework-heavy application most bugs live in the wiring between pieces, not in isolated logic. Guillermo Rauch summed it up in a widely quoted line: write tests, not too many, mostly integration. For an ASP.NET Core API that means the highest-value tests exercise the real pipeline and a real database through WebApplicationFactory and Testcontainers, while pure domain rules get fast unit tests. For React it means testing components through their accessible interface with realistic mocked network responses, and using a handful of real-browser tests for the critical journeys.

Assign tests by asking what kind of failure you are guarding against. A wrong state transition in the domain model is a unit test. A route that is mapped incorrectly, a validator that never runs, a query that fails to translate to SQL, or an authorization filter that is missing are integration failures, invisible to unit tests. A form that does not show a server error, or a loading state that never resolves, is a component test. A broken login redirect across the BFF and identity provider, or a build that ships without the right environment configuration, is an end-to-end or smoke test. The contract between the two halves, that the client's types match the server's actual responses, is guarded by the OpenAPI drift check from Day 30.

Security testing belongs in every layer, not in a separate phase at the end. Unit tests cover validators and sanitizers with hostile inputs. Integration tests cover the authorization matrix, tenant isolation, security headers, and CORS. Component tests cover safe rendering of malicious content. Pipeline scans cover dependencies and secrets. Keep the whole suite trustworthy: make tests deterministic by controlling time and randomness, isolate them so order does not matter, delete or fix flaky tests immediately since a suite people ignore is worse than none, and track the run time, because a suite that takes an hour will not be run before every commit.

LayerSpeedConfidence inTypical tools
Unit, .NETMillisecondsDomain rules, validators, pure logicxUnit, NSubstitute, FakeTimeProvider
Component, ReactTens of millisecondsRendering, states, forms, accessibilityVitest, Testing Library, MSW
Integration, APIHundreds of millisecondsRouting, binding, SQL, authorization, wiringWebApplicationFactory, Testcontainers, Respawn
ContractSecondsClient and server agree on shapesOpenAPI drift check, generated types
End to endSeconds to minutesCritical journeys across the real systemPlaywright
Security and performanceVariesAbuse cases, load behaviorAccess matrix, ZAP, k6

Worked Example: A Test Plan for Moving a Task, by Layer

The plan below assigns each risk of the move-task feature to the cheapest layer that can catch it. The folder layout and pipeline stages show how the suite is organized and run.

Code
Feature: a member moves a task to another column (Day 60)

Risk                                              Layer          Test
-------------------------------------------------------------------------------------------------
Illegal transition (Todo to Done) allowed         Unit .NET      TaskItem.MoveTo rejects; table-driven over all pairs
Completion date set only when Done                Unit .NET      MoveTo sets and clears CompletedAt
Status outside 0..3 accepted                      Integration    400 with a field error (validation actually wired)
Viewer or outsider can move a task                Integration    Access matrix rows: 404 for both
Stale ETag overwrites newer data                  Integration    Second PATCH with old ETag returns 412
SQL translation of the membership filter fails    Integration    Runs against real SQL Server in a container
Board shows the wrong column after a move         Component      Optimistic move rendered, rolled back on 412
Server error text leaks into the page             Component      Error response with a stack trace shows only a friendly message
Client types drift from the API                   Contract       Regenerate OpenAPI and types, fail if they differ
User can sign in and move a card in a real browser  End to end   One Playwright journey, run against staging
Attacker script in a task title runs on the board  Component     Title with an XSS payload renders as text
Dependencies with known vulnerabilities           Pipeline       dotnet list package --vulnerable, npm audit
Code
tests/
  Unit/            TaskBoard.Domain.Tests           runs in < 5 s, no I/O
  Integration/     TaskBoard.Api.Tests              real pipeline + SQL Server container, runs in ~1 to 2 min
  Architecture/    TaskBoard.Architecture.Tests     dependency and module rules
web/src/**/*.test.tsx                                Vitest + Testing Library + MSW, runs in ~30 s
e2e/               Playwright specs                  3 to 5 critical journeys, run after deploy to staging
YAML
# CI stages: cheapest and fastest first, so failures are reported quickly.
stages:
  - fast:        [dotnet test tests/Unit tests/Architecture, "npm test -- --run", "npx tsc --noEmit", lint]
  - integration: [dotnet test tests/Integration]           # needs Docker
  - contract:    [build openapi, "git diff --exit-code openapi/ web/src/api"]
  - security:    [dotnet list package --vulnerable, npm audit, secret scan]
  - e2e:         [deploy to staging, "npx playwright test"]   # only on main, blocks release not merge
C#
// Determinism: tests never read the real clock or unseeded randomness.
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 9, 1, 9, 0, 0, TimeSpan.Zero));
var sut = new TaskService(store, clock);
clock.Advance(TimeSpan.FromDays(3));                          // move time forward on demand

// Readable test data: builders provide valid defaults and let each test state only what matters.
var task = new TaskBuilder().InState(TaskState.Review).AssignedTo(userId).Build();

A useful habit is to write the risk table before the tests. It makes the coverage argument explicit, shows gaps such as a rule that only has an end-to-end test, and gives reviewers something to check the tests against instead of a raw coverage percentage.

Fast unit tests for domain rules, integration tests through the real API and database, component tests for the React interface, a contract check, and a few end-to-end journeys, with security tests distributed across every layer.
Fast unit tests for domain rules, integration tests through the real API and database, component tests for the React interface, a contract check, and a few end-to-end journeys, with security tests distributed across every layer.

Real-World Examples

  • Mike Cohn introduced the test pyramid in his 2009 book Succeeding with Agile, and Martin Fowler's later article on the practical test pyramid popularized it. Google's testing blog followed in 2015 with Just Say No to More End-to-End Tests, describing how end-to-end suites became slow and flaky at scale and recommending that most confidence come from faster, narrower tests.
  • Guillermo Rauch's 2016 remark that you should write tests, not too many, mostly integration, was expanded by Kent C. Dodds into the testing trophy, and it reflects experience with modern frameworks where the majority of defects appear at the seams between components. Testing Library's guiding principle, that the more your tests resemble the way the software is used the more confidence they give, follows the same reasoning.
Key TakeawaysAssign each risk in a React and .NET system to the cheapest test layer that can detect it, instead of testing everything everywhere. Use unit tests for domain rules, integration tests for the real API pipeline and database, component tests for the interface, a contract check for client and server agreement, and a few end-to-end journeys. Build security tests into every layer, keep tests deterministic and fast, and treat flaky tests as bugs.

Review Questions & Answers

Most defects live in the wiring: routing, model binding, validation registration, authorization filters, serialization, and SQL translation. Unit tests that call handlers directly cannot see these, while a test through WebApplicationFactory with a real database exercises them together. They run fast enough to be part of every commit while catching a very different class of bug.

Ask where the failure would occur. Pure logic such as a state transition is best caught by a fast unit test. Anything that depends on framework behavior, the database, or authorization needs an integration test. Only journeys spanning the browser, the identity provider, and the deployed environment justify the cost of end-to-end. Choose the cheapest layer that can actually detect the defect.

A flaky test fails randomly, so people learn to rerun and ignore failures, and eventually real failures are dismissed too, destroying trust in the whole suite. Flakiness also wastes pipeline time. Fixing the cause, usually shared state, time, or timing assumptions, or deleting the test, restores the value of the signal.

At every layer: unit tests for validators and sanitizers with hostile input, integration tests for authorization, tenant isolation, headers and CORS, component tests for safe rendering, and pipeline scans for dependencies and secrets. Treating security as a layer of its own leaves gaps, while distributing it means each protection is verified where it is implemented.