The test pyramid
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite has 70 slow full-app tests and only 3 unit tests, so every change means a long wait. How many tests of each kind should a healthy suite have?
The pyramid: many unit tests, few end-to-end tests
The test pyramid is a picture of a healthy test suite: a wide base of many fast unit tests, a smaller middle of integration tests and a narrow top of very few end-to-end tests.
Most tests are fast unit tests, fewer are integration tests and only a handful are end-to-end tests. The right side of the picture shows the upside-down shape to avoid.
The numbers are not a fixed rule. A common shape for a service like ShopLite is several hundred unit tests, a few dozen integration tests and five to ten end-to-end tests.
What matters is the direction: the higher a test sits, the slower it is, so the fewer of them you keep.
Why this shape: speed, precision and upkeep
Feedback speed is how long you wait to learn whether your change broke something. Unit tests answer in seconds, so you run them after every small change; a slow suite is run less often.
This program estimates how long two suites take to run. Both have a mix of tests, with a different shape. The times per test are a simple model, not a measurement.
Example 1 · Feedback time: a pyramid versus an ice-cream cone
public class FeedbackTimeDemo { // Typical times per test, in milliseconds (a simple model, not a measurement) static final int UNIT_MS = 5; static final int INTEGRATION_MS = 400; static final int E2E_MS = 3000;
static void report(String name, int unit, int integration, int e2e) { int total = unit + integration + e2e; long ms = (long) unit * UNIT_MS + (long) integration * INTEGRATION_MS + (long) e2e * E2E_MS; System.out.printf("%-15s %4d tests %3d unit %3d integration %3d e2e -> %5.1f min%n", name, total, unit, integration, e2e, ms / 60000.0); }
public static void main(String[] args) { report("Pyramid", 400, 40, 8); report("Ice-cream cone", 30, 60, 160); }}Pyramid 448 tests 400 unit 40 integration 8 e2e -> 0.7 min Ice-cream cone 250 tests 30 unit 60 integration 160 e2e -> 8.4 min
What this code does
- The pyramid has almost twice as many tests and still finishes in about 42 seconds, because 400 unit tests together take only 2 seconds.
- The cone has fewer tests but waits more than 8 minutes, so developers stop running it after each change. Those per-test times are a rough model; real numbers vary, but the gap is always this wide.
Two more reasons point the same way:
- Failure precision: a failing unit test names the class and line; a failing end-to-end test only says a request returned 500.
- Maintenance cost: an end-to-end test touches URLs, JSON, security and data, so many unrelated changes break it. A unit test changes only when its own rule changes.
- Set-up: unit tests need nothing; integration tests need a test database; end-to-end tests need the whole app running.
Predict the output
How long does the suite take?
Use the model: a unit test takes 5 ms and an end-to-end test takes 3000 ms.
Round 1 of 2
200 unit tests and 10 end-to-end tests. What is printed?
The ice-cream cone anti-pattern
The ice-cream cone is an upside-down test suite: many slow manual and end-to-end checks on top, a few integration tests and almost no unit tests at the bottom. It is a common anti-pattern, a habit that causes trouble.
These are ShopLite's real test counts, drawn as bars. The widest bar is at the top, so the shape is the wrong way up.
Example 2 · What shape is this suite? ShopLite's tests today
import java.util.LinkedHashMap;import java.util.Map;
public class SuiteShapeDemo { public static void main(String[] args) { // Test counts from the shoplite-api build at the end of the Spring Security section Map<String, Integer> levels = new LinkedHashMap<>(); levels.put("Full app (IT)", 70); levels.put("Controller", 17); levels.put("Unit", 3);
for (Map.Entry<String, Integer> level : levels.entrySet()) { System.out.printf("%-14s %3d %s%n", level.getKey(), level.getValue(), "#".repeat(level.getValue() / 2)); }
int top = levels.get("Full app (IT)"); int bottom = levels.get("Unit"); System.out.println(top > bottom ? "Shape: top-heavy - add unit tests underneath" : "Shape: pyramid"); }}Full app (IT) 70 ################################### Controller 17 ######## Unit 3 # Shape: top-heavy - add unit tests underneath
What this code does
- These are ShopLite's real counts: 70 tests start the whole Spring app, 17 test controllers, and only 3 test a plain class. Drawn as bars (one
#per two tests), the widest bar is at the top. - The full-app tests are valuable, but every pricing or status rule checked there costs seconds. The projects in this section add unit tests for line totals, the cart and coupons, which turns the shape the right way up.
Teams fall into the cone because end-to-end tests feel like "real" testing, and because rules mixed into controllers are hard to unit test. The result is a suite that takes ages, fails at random and is skipped before deadlines.
The cure is to move rules into small classes and test them at the bottom.
Order of execution
Turn the cone around
Put the steps for moving one rule from slow tests down to unit tests in order.
A pyramid for ShopLite
Before writing tests for a feature, list how many you will write at each level. This plan does it for three ShopLite features and checks the shape.
Example 3 · Sketching the pyramid for three ShopLite features
import java.util.List;
record FeaturePlan(String feature, int unit, int integration, int e2e) { int total() { return unit + integration + e2e; }}
public class ShopLitePyramidPlan { public static void main(String[] args) { List<FeaturePlan> plan = List.of( new FeaturePlan("Products", 12, 4, 1), new FeaturePlan("Orders", 18, 6, 1), new FeaturePlan("Security", 10, 8, 1));
int unit = 0, integration = 0, e2e = 0; System.out.println("Feature unit integration e2e"); for (FeaturePlan p : plan) { System.out.printf("%-9s %5d %12d %4d%n", p.feature(), p.unit(), p.integration(), p.e2e()); unit += p.unit(); integration += p.integration(); e2e += p.e2e(); } System.out.printf("%-9s %5d %12d %4d%n", "Total", unit, integration, e2e); System.out.println(unit > integration && integration > e2e ? "Pyramid: yes" : "Pyramid: no"); }}Feature unit integration e2e Products 12 4 1 Orders 18 6 1 Security 10 8 1 Total 40 18 3 Pyramid: yes
What this code does
- Each feature gets most of its tests as unit tests for its rules, a few integration tests for database and access rules, and one end-to-end journey.
- Security has relatively more integration tests, because "who may call which URL" only exists once Spring Security is running. The total still has the pyramid shape.
Start with the rules (unit), then the database and JSON work (integration), then one or two journeys through HTTP (end-to-end). For ShopLite's main areas the plan looks like this:
- Products: unit tests for SKU and price rules; integration tests for search queries and paging; one E2E read of a product.
- Orders: unit tests for line totals, order total and which statuses may be cancelled; integration tests for placing an order with stock and rollback; one E2E place-and-read journey.
- Security: unit tests for password and token rules; integration tests for the access table (who may call what); one E2E login-then-call journey.
Find the bug
Fix the test plan
Each plan has one level that does not fit the pyramid. Tap that line, then read the fix.
Plan for: an order may be cancelled only while it is PLACED.
Round 1 of 3Where contract and smoke tests fit
A contract test checks that what you publish still matches what clients were promised: URLs, fields and status codes. It protects the clients from breaking changes.
ShopLite's published API docs are part of its contract with clients. This test checks that placing an order documents exactly the promised status codes.
Example 4 · A contract test: ShopLite's API docs match the contract
Runs in: the shoplite-api Spring Boot project
package com.shoplite;
/** Keeps the published API docs true to the API contract (API-DESIGN.md). */@SpringBootTest@AutoConfigureMockMvc@ActiveProfiles("test")class ApiDocsIT {
@Autowired private MockMvcTester mvc;
@Test void placeOrderDocumentsEveryStatusOfTheContract() { assertThat(mvc.get().uri("/v3/api-docs")) .bodyJson() .extractingPath("$.paths['/api/v1/orders'].post.responses").asMap() .containsOnlyKeys("201", "400", "409", "422", "401", "403"); }}[INFO] Running com.shoplite.ApiDocsIT [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.975 s -- in com.shoplite.ApiDocsIT
What this code does
- The test reads the generated OpenAPI document and checks that placing an order lists exactly the status codes the contract promises. If someone adds or removes a status, clients would be surprised, and this test fails first.
- It needs the Spring context, so it sits in the integration layer, and there are only a few such tests. The smoke test from the previous lesson,
ShopliteApiSmokeIT, sits at the very top with just three requests.
A smoke test is a tiny end-to-end check that the app starts and answers at all, named after switching on a machine and checking that no smoke comes out. Smoke tests run first, or right after a deployment, so a broken start-up is reported in seconds.
Both kinds sit near the top and stay few. Contract tests run with the integration tests and protect clients, such as ShopLite's browser client.
Next step
Check your understanding
11 quick questions