The testing pyramid
Junior Always asked 7 min
On this page
The question
What is the difference between unit, integration and end-to-end tests?
30-second answer
They differ in how much real code runs. A unit test checks one unit of logic, usually a class, with no framework, database or network, in milliseconds. An integration test checks that real parts work together, such as a repository against a database. An end-to-end test drives the whole deployed system like a user. Keep many unit tests, fewer integration tests and a few end-to-end tests.
Understand it
Move tests between the layers
ExploreShape: pyramid. The suite takes about 2.7 min per run. Every layer catches its own kind of bug.
View as text
Three stacked bars, end-to-end on top, integration in the middle and unit at the bottom, each as wide as its number of tests and labelled with an illustrative time per test: 15 seconds, half a second and 10 milliseconds. Below them, three marks say whether logic, wiring and whole flows are checked, and the total run time.
Pyramid, 70 unit, 20 integration and 10 end-to-end tests: Shape: pyramid. The suite takes about 2.7 min per run. Every layer catches its own kind of bug.
Ice-cream cone, 10, 20 and 70: Shape: ice-cream cone. The suite takes about 17.7 min per run. Every layer catches its own kind of bug.
Unit tests only, 100: Shape: missing layers. The suite takes about 1 s per run. No end-to-end or integration tests, so some bugs go unchecked.
No unit tests, 60 integration and 20 end-to-end: Shape: ice-cream cone. The suite takes about 5.5 min per run. No unit tests, so some bugs go unchecked.
Three stacked bars, end-to-end on top, integration in the middle and unit at the bottom, each as wide as its number of tests and labelled with an illustrative time per test: 15 seconds, half a second and 10 milliseconds. Below them, three marks say whether logic, wiring and whole flows are checked, and the total run time.
Pyramid, 70 unit, 20 integration and 10 end-to-end tests: Shape: pyramid. The suite takes about 2.7 min per run. Every layer catches its own kind of bug.
Ice-cream cone, 10, 20 and 70: Shape: ice-cream cone. The suite takes about 17.7 min per run. Every layer catches its own kind of bug.
Unit tests only, 100: Shape: missing layers. The suite takes about 1 s per run. No end-to-end or integration tests, so some bugs go unchecked.
No unit tests, 60 integration and 20 end-to-end: Shape: ice-cream cone. The suite takes about 5.5 min per run. No unit tests, so some bugs go unchecked.
Takeaway: Many fast unit tests, fewer integration tests and a few end-to-end tests give quick feedback and still check how the parts fit together.
F.I.R.S.T.: what makes a good unit test
Tap the partsSelect a part to see what it does.
Tap a letter to see the property. Each row shows the rule and, crossed out, a line of test code that breaks it.
View as text
Five rows, one per letter of F.I.R.S.T. Each row has a button with the property, a short rule, and a crossed-out line of test code that breaks it.
Fast: Runs in milliseconds. It rules out Thread.sleep(2000). A unit test runs in milliseconds, so the whole suite can run on every save. Sleeps, real networks and real databases make tests slow, and slow tests stop being run.
Isolated: Shares no state. It rules out static List saved. Each test sets up what it needs and depends on no other test. Shared static state makes the result depend on which tests ran before, so a test passes alone and fails in the suite.
Repeatable: Same result anywhere. It rules out LocalDate.now(). The same code gives the same result on every machine and every run. Inject a Clock, fix the random seed and avoid the network, so a red test always means a real bug.
Self-validating: Asserts pass or fail. It rules out System.out.println. The test decides on its own whether it passed, with assertions. A test that prints a value for a person to read checks nothing when it runs in CI.
Timely: Written with the code. It rules out // TODO: add tests. Tests are written just before or with the code they check. Written much later, they tend to describe what the code happens to do, and the code is often hard to test by then.
Five rows, one per letter of F.I.R.S.T. Each row has a button with the property, a short rule, and a crossed-out line of test code that breaks it.
Fast: Runs in milliseconds. It rules out Thread.sleep(2000). A unit test runs in milliseconds, so the whole suite can run on every save. Sleeps, real networks and real databases make tests slow, and slow tests stop being run.
Isolated: Shares no state. It rules out static List saved. Each test sets up what it needs and depends on no other test. Shared static state makes the result depend on which tests ran before, so a test passes alone and fails in the suite.
Repeatable: Same result anywhere. It rules out LocalDate.now(). The same code gives the same result on every machine and every run. Inject a Clock, fix the random seed and avoid the network, so a red test always means a real bug.
Self-validating: Asserts pass or fail. It rules out System.out.println. The test decides on its own whether it passed, with assertions. A test that prints a value for a person to read checks nothing when it runs in CI.
Timely: Written with the code. It rules out // TODO: add tests. Tests are written just before or with the code they check. Written much later, they tend to describe what the code happens to do, and the code is often hard to test by then.
Takeaway: A good unit test is fast, isolated, repeatable, self-validating and timely. Each letter rules out a smell that makes a suite slow, flaky or useless.
In code
// Unit: one class, no Spring, no database. Runs in milliseconds.
class PricingTest {
@Test
void takesTenPercentOffAboveOneHundred() {
Pricing pricing = new Pricing();
assertEquals(180, pricing.total(200));
}
}
// Integration: the real repository and real SQL against a database.
@DataJpaTest
class OrderRepositoryTest {
@Autowired OrderRepository orders;
@Test
void findsOrdersByCustomer() {
orders.save(new Order("ana", 20));
assertEquals(1, orders.findByCustomer("ana").size());
}
}class Coupon {
private final Clock clock;
Coupon(Clock clock) { this.clock = clock; }
boolean expired(LocalDate lastDay) {
return LocalDate.now(clock).isAfter(lastDay);
}
}
@Test
void expiresTheDayAfterTheLastDay() {
Clock fixed = Clock.fixed(Instant.parse("2026-01-02T10:00:00Z"), ZoneOffset.UTC);
assertTrue(new Coupon(fixed).expired(LocalDate.parse("2026-01-01")));
}class DiscountPolicyTest {
private final DiscountPolicy policy = new DiscountPolicy(new InMemoryCoupons(Set.of("SAVE10")));
@Test
void knownCouponTakesTenPercent() {
assertEquals(Money.of(90), policy.apply(Money.of(100), "SAVE10")); // runs in about a millisecond
}
}Solve it
The CI suite takes 40 minutes and fails at random: rebalance it
A shop has 600 browser tests and 200 unit tests. CI takes 40 minutes, about one run in five fails for no code reason, and developers have stopped running tests locally. Propose a plan.
- Measure first. Count tests per layer, time per layer and the flaky tests by name. The shape is an inverted pyramid, an ice-cream cone.
- Ask what each browser test proves. Most check business rules, such as discount math or validation messages. A rule needs no browser: move it to unit tests.
- Keep integration tests for wiring. Repositories against a real database and HTTP clients against a stub server catch what units cannot.
- Keep a few journeys end to end. Login, checkout and payment stay as browser tests: the paths that must never break.
- Check. The rules are still covered (mutation score holds), CI time drops to minutes and flaky failures become rare.
// before: a browser test for each discount case, about 40 s each
Wrong @Test
Wrong void tenPercentCouponInBrowser() {
Wrong page.fill("#coupon", "SAVE10");
Wrong page.click("text=Pay");
Wrong assertThat(page.locator("#total")).hasText("90.00");
}
Right // after: the rule at the unit layer, every case in milliseconds
Right @ParameterizedTest
Right @CsvSource({"SAVE10, 100, 90", "SAVE20, 100, 80", "UNKNOWN, 100, 100"})
Right void couponDiscount(String coupon, int price, int expected) {
Right assertEquals(Money.of(expected), policy.apply(Money.of(price), coupon));
Right }
// one browser test remains: the checkout journey shows a discounted totalHow to answer
- Higher layers give more confidence per test but run slower and fail for more reasons.
- Unit tests pinpoint the broken line; an end-to-end failure only says that something broke.
- Integration tests catch what mocks hide, such as wrong SQL or JSON mapping.
- The pyramid is a guide to proportions, not a rule to count tests by.
Common mistakes
- Calling any test that uses JUnit a unit test; a test that starts Spring and a database is an integration test.
- Relying mostly on end-to-end tests, which are slow, flaky and hard to debug.
Follow-up questions
What makes a good unit test?
The F.I.R.S.T. properties. Fast, so the suite runs on every change. Isolated, so tests share no state and can run in any order. Repeatable, so the result never depends on the clock, the machine or the network. Self-validating, so assertions decide pass or fail. Timely, so it is written with the code. A good test also checks one behavior and reads like an example.
- One reason to fail per test, named after the behavior it checks.
- Inject time, randomness and I/O so a test can control them.
- Test behavior through the public API, not private methods.
See it in the infographic: F.I.R.S.T.: what makes a good unit test
Why should most of your tests be unit tests?
Because they give the fastest and most precise feedback. A thousand unit tests run in seconds, so developers run them on every change, and a failure names the class and the case. Each step up the pyramid costs more time, setup and flakiness per test. Higher layers are still needed, but only for what lower layers cannot see.
- Cheap tests can cover every edge case; expensive ones should cover the main paths.
- Fast feedback keeps the suite in use before every commit.
- A failure low in the pyramid is cheaper to find and fix.
A team has hundreds of end-to-end tests and few unit tests. What problems do you expect?
This is the ice-cream cone anti-pattern. The suite takes many minutes or hours, so it runs rarely and feedback comes late. Tests fail for reasons unrelated to the change, such as timeouts or test data, so people learn to rerun them. A red build says little about where the bug is. The fix is to push each check down to the lowest layer that can catch it.
- Slow suites move testing to the end of the day or to CI (continuous integration) only.
- Flaky tests teach the team to ignore red builds.
- Edge cases are expensive at the top, so they go untested.
A test passes on your machine but fails in CI now and then. What do you look for?
Something the test does not control. Common causes are shared state between tests, so order matters; the current time or time zone; random data without a fixed seed; real network calls; and waiting with a fixed sleep instead of waiting for a condition. Each one breaks the Isolated or Repeatable property. Reproduce it by running the test in a loop or in a different order, then remove that dependency.
- Run the suite in random order to expose hidden ordering.
- Replace sleeps with polling on a condition, for example with Awaitility.
- Quarantine is a short-term measure; fix the cause.
See it in the infographic: F.I.R.S.T.: what makes a good unit test
Is there code you would not cover with unit tests?
Yes. Code with no logic of its own, such as getters, plain mappings or framework configuration, gains little from a unit test. Code whose whole job is to talk to something external, such as a repository query or an HTTP client, needs an integration test to prove anything, since mocking the database tests only the mock. Put unit tests where the decisions are.
- A mocked repository cannot show that the SQL is right.
- Trivial code gets covered by the tests of the code that uses it.
- Test generated or framework code only where you configured it.
Is a unit always a single class?
Not necessarily. A solitary unit test replaces every collaborator with a test double. A sociable one lets a few real, fast collaborators run, such as value objects or a pricing helper. Both are unit tests while they stay fast and avoid I/O. Mocking every class tends to couple tests to the implementation.
What is the testing trophy?
A shape proposed by Kent C. Dodds for front-end code that puts most tests at the integration layer, with static analysis as its base. It reflects that integration tests became cheap there. For a Java service the same idea shows up as many slice and Testcontainers tests. The shared point is to buy confidence where it is cheap.
Where do contract tests fit in the pyramid?
Between integration and end-to-end tests. A contract test checks that two services agree on an API without deploying both, so it replaces many slow end-to-end tests between microservices with fast checks run in each service's own build.
Check yourself
Show answers
- The end-to-end tests: Correct. Each one drives the whole system, so even a few of them take far longer than hundreds of unit tests.
- The unit tests: Incorrect. There are the most of them, but each runs in milliseconds.
- The integration tests: Incorrect. They are slower than unit tests, but much faster than end-to-end ones.
Show answers
- A query with a wrong column name: Correct. The mocked repository never runs the SQL, so only an integration test would see it.
- A wrong discount calculation in one class: Incorrect. A unit test of the pricing class catches this.
- A missing null check in a service method: Incorrect. Unit tests are good at exactly this kind of logic case.
Show answers
- Repeatable: Correct. The result depends on when the test runs, not on the code.
- Fast: Incorrect. Reading the clock costs nothing; speed is not the problem.
- Self-validating: Incorrect. It does assert a result; the result just changes with the date.