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

Explore

Shape: pyramid. The suite takes about 2.7 min per run. Every layer catches its own kind of bug.

70
20
10
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 parts

Select 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.

Which layer should test itAsk what could break. Logic inside one class gets a unit test. Wiring, SQL or JSON mapping gets an integration test. A user flow across the whole system gets one of a few end-to-end tests.What couldbreak?Logic in one class:unit testWiring, SQL, JSON:integration testA whole user flow:end-to-end test
Which layer should test itAsk what could break. Logic inside one class gets a unit test. Wiring, SQL or JSON mapping gets an integration test. A user flow across the whole system gets one of a few end-to-end tests.What couldbreak?Logic in one class:unit testWiring, SQL, JSON:integration testA whole user flow:end-to-end test
Which layer should test it

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());
    }
}
One feature, tested at two layers
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")));
}
Repeatable: inject the clock instead of calling now()
Placing an order, tested at three layersMany unit tests check the pricing rules in one class. Fewer integration tests check the repository against a real database. One end-to-end test sends POST orders to the deployed service and checks the whole flow.Many unit tests:Pricing rulesFewer integrationtests:repository anddatabaseOne end-to-end test:POST /orders,deployed
Placing an order, tested at three layersMany unit tests check the pricing rules in one class. Fewer integration tests check the repository against a real database. One end-to-end test sends POST orders to the deployed service and checks the whole flow.Many unit tests:Pricing rulesFewer integrationtests:repository anddatabaseOne end-to-end test:POST /orders,deployed
Placing an order, tested at three layers
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
    }
}
Isolated and fast: a plain unit test, no Spring and no I/O

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.

  1. 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.
  2. 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.
  3. Keep integration tests for wiring. Repositories against a real database and HTTP clients against a stub server catch what units cannot.
  4. Keep a few journeys end to end. Login, checkout and payment stay as browser tests: the paths that must never break.
  5. 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 total
One browser test per case becomes one parameterized unit test

How 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.

See it in the infographic: Move tests between the layers

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.

See it in the infographic: Move tests between the layers

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.

See it in the infographic: Move tests between the layers

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

1. A suite has 700 unit, 200 integration and 100 end-to-end tests. Which layer takes most of the run time?
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.
2. A service has only unit tests, with every repository mocked. Which bug can still reach production?
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.
3. A test calls LocalDate.now() and fails only on the last day of the month. Which F.I.R.S.T. property does it break?
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.