Skip to content
javahacks.dev
Testing

The Test Pyramid for Java Services and Where It Breaks

What the test pyramid says, why it fits business logic and fits badly for services that mostly connect a database to a queue, and what to draw instead.

6 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the OpenJDK, Selenium, Jenkins and JUnit5 logos.

The test pyramid is a picture from 2009 and it is still the first thing anyone draws about testing. A wide base of unit tests, a middle layer of integration tests and a narrow tip of end-to-end tests. It is good advice with a precondition that people forget, and a Java service built mainly of glue code does not meet it. This post states the rule, then shows where it holds. The full plan it feeds is in a practical Java testing strategy.

What the shape encodes

Each layer up costs more:

LayerRuns inFails forFinds a fault
Unitmillisecondslogic errors onlyin the line
Integrationsecondswiring, SQL, serializationin the component
End to endtens of seconds to minutesanything, including the environmentsomewhere in the system

Speed, stability and precision all drop as you go up. The pyramid says to catch each defect at the lowest layer that can catch it. That is the whole idea; the triangle is a mnemonic.

When it fits

A service with rich domain logic fits: pricing rules, scheduling, an eligibility engine. Logic can be written as plain classes, tested by the thousand with no framework, and the integration layer only needs to prove the wiring. Here a unit-heavy suite finds defects early and costs little.

java
class EligibilityTest {

    @Test
    void under18IsNotEligible() {
        assertFalse(new Eligibility(LocalDate.of(2026, 3, 14))
                .check(new Applicant(LocalDate.of(2010, 6, 1))).eligible());
    }
}

Where it breaks

Consider a service whose controller validates a request, a repository saves it and a listener publishes an event. There is almost no logic. A unit test with the repository mocked asserts that save was called, which restates the code. The defects that actually occur are in the SQL, the transaction boundary, the JSON mapping and the message format, and none of them is visible to a unit test. For this service a stack of unit tests gives confidence about code that did not need it.

The better shape is a honeycomb or a trophy: few unit tests, many integration tests against real components (a PostgreSQL container, a real broker), and a handful of end-to-end checks. The cost of the integration layer is lower than it used to be, because containers start in seconds and can be reused across a run.

The inverted pyramid

The failure mode on the other side is a suite that is mostly end to end. It runs for twenty minutes, fails on a port conflict or a stale fixture, and nobody can say whether the failure means the code is broken. Teams stop trusting it, then stop running it. If you have this, move cases down: each end-to-end test that covers a rule can usually become a unit or integration test.

Choose the shape from the code

Your serviceLikely shape
Rich domain logic, few integrationsPyramid
Mostly CRUD over a databaseHoneycomb: integration-heavy
Mostly glue between queues and APIsContract tests plus integration
A libraryUnit tests plus a compatibility matrix

Measure your own suite to check the shape: count tests per layer and the total time and failure count of each. A layer that is 80 percent of the run time and finds 5 percent of the defects is the one to shrink. The differences between the layers are spelled out in unit vs integration vs end-to-end tests.

What an integration test for glue code looks like

The service described above, with a controller, a repository and an event, is best covered by one test that starts the real database and sends a real request. Testcontainers makes the database a few lines:

java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class OrderFlowTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17");

    @Autowired
    TestRestTemplate http;

    @Autowired
    OrderRepository orders;

    @Test
    void creatingAnOrderPersistsItAndReturnsItsLocation() {
        var request = new CreateOrder("sku-42", 3);

        ResponseEntity<Void> response = http.postForEntity("/orders", request, Void.class);

        assertEquals(HttpStatus.CREATED, response.getStatusCode());
        URI location = response.getHeaders().getLocation();
        assertNotNull(location);

        Order saved = orders.findById(idFrom(location)).orElseThrow();
        assertEquals("sku-42", saved.sku());
        assertEquals(3, saved.quantity());
    }

    private static long idFrom(URI location) {
        String path = location.getPath();
        return Long.parseLong(path.substring(path.lastIndexOf('/') + 1));
    }
}

One test exercises request mapping, validation, JSON binding, the transaction, the SQL and the generated key, against the database engine you run in production. A mocked-repository unit test of the same controller would pass while the INSERT failed on a column that was renamed in a migration. The cost is a few seconds for the container the first time and much less for each later class, since Spring caches the context, as described in caching the Spring test context.

Pushing the logic back down

The pyramid still applies to the part of the service that has logic. When a rule hides inside a service method that also talks to the database, extract it so it can be tested in milliseconds:

java
record Discount(BigDecimal percent) {

    static Discount forOrder(int quantity, boolean loyaltyMember) {
        BigDecimal base = quantity >= 10 ? new BigDecimal("0.10") : BigDecimal.ZERO;
        return new Discount(loyaltyMember ? base.add(new BigDecimal("0.05")) : base);
    }
}

class DiscountTest {

    @ParameterizedTest
    @CsvSource({
        "1,  false, 0.00",
        "10, false, 0.10",
        "10, true,  0.15",
        "1,  true,  0.05"
    })
    void combinesVolumeAndLoyalty(int quantity, boolean loyal, String expected) {
        assertEquals(new BigDecimal(expected),
            Discount.forOrder(quantity, loyal).percent().setScale(2));
    }
}

The test has no framework, no mock and no I/O. It runs with thousands of siblings in a second, and it documents the rule in a table a product owner can read. That is the base of the pyramid doing what it is good at.

A boundary check for the edges

Between the two layers sits the contract with other services. If the order service calls a pricing service over HTTP, a consumer-driven contract test is cheaper than an end-to-end environment. WireMock is enough to pin the shape you depend on:

java
@WireMockTest(httpPort = 8089)
class PricingClientTest {

    @Test
    void readsPriceFromPricingService() {
        stubFor(get("/prices/sku-42").willReturn(okJson("""
            {"sku":"sku-42","amount":"19.90","currency":"EUR"}""")));

        Price price = new PricingClient("http://localhost:8089").priceOf("sku-42");

        assertEquals(new BigDecimal("19.90"), price.amount());
        assertEquals("EUR", price.currency());
    }
}

The stub is a statement about what your service expects. Share it with the team that owns the pricing service as a contract, so that a change on their side that breaks your assumption fails their build rather than your production traffic.

Counting your own shape

You can measure the layers with the report your build already produces. Tag the tests by layer and count what each tag costs:

Shell
./mvnw -q test -Dgroups=unit        # note the duration
./mvnw -q verify -Dgroups=integration

Write the three numbers (tests, seconds, failures in the last 30 days) next to each layer in the team's wiki and look at them each quarter. The goal is not a pretty triangle. It is that a failing build points at a small area, and that the slowest layer is also the one that earns its time.

Where the pyramid is a poor guide

It says nothing about non-functional tests: performance, security and resilience have their own shapes. It also treats a "unit" as a class, which encourages mocking every collaborator. Treat a unit as a cluster of classes that behave as one, and mock only at the edges, as argued in what to mock and what to leave real. The original test pyramid article by Martin Fowler states the idea, and the Testcontainers documentation shows how cheap the integration layer has become.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.