Skip to content
javahacks.dev
Testing

A Practical Java Testing Strategy for Spring Boot Services

Decide what to unit test, what to run against real infrastructure and what to mock, with a layered plan that keeps a Spring Boot suite fast.

16 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the OpenJDK, Spring Boot, JUnit5, Selenium and GitHub Actions logos.

Teams rarely have too few tests. They have the wrong ones: hundreds of mock-heavy unit tests that pass when the code is broken, and three full-context tests that take four minutes and fail on a port conflict. A strategy is a decision about where each kind of risk gets caught. This guide lays out one for a Spring Boot 4 service on JDK 25 that talks to PostgreSQL, and explains where it breaks. The framework details live in the JUnit 5 handbook, and the Spring side is documented in the Spring Boot testing reference.

Match the test to the risk

RiskCheapest test that catches it
A pricing rule is wrongUnit test on the domain class
A request is bound or validated wrongly@WebMvcTest slice
A query returns the wrong rowsRepository test against a real PostgreSQL
A message is serialized wronglyIntegration test against a real broker
Two services disagree on a contractContract test
A journey breaks across the whole systemEnd-to-end test

The table is the strategy. Everything else is how to implement each row cheaply.

Test logic without Spring

Business rules belong in plain classes that take their collaborators in a constructor. Then the test is an ordinary object:

java
class DiscountPolicyTest {

    private final DiscountPolicy policy = new DiscountPolicy(Clock.fixed(
            Instant.parse("2026-03-14T10:00:00Z"), ZoneOffset.UTC));

    @Test
    void appliesWeekendRateOnSaturday() {
        assertEquals(10, policy.percentFor(new Customer("ana", Tier.GOLD)));
    }
}

No context starts, so this runs in milliseconds, and you can have thousands. A fixed Clock passed in turns time into an input. Code that calls Instant.now() internally cannot be tested like this, which is a good reason to inject the clock.

Test the wiring with slices

A slice loads a part of the context. @WebMvcTest loads controllers, advice, converters and filters; @DataJpaTest loads repositories and an EntityManager. They check what unit tests cannot: that a path variable binds, that validation returns 400, that a derived query method parses. If the context fails to build, Failed to load ApplicationContext lists the causes in the order to check them.

Use the real database

An in-memory H2 database accepts SQL that PostgreSQL rejects and ignores locking behavior entirely. Run the real engine, using Testcontainers:

java
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class OrderRepositoryTest {

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

    @Autowired OrderRepository orders;

    @Test
    void findsOpenOrdersForCustomer() {
        // save fixtures, query, assert
    }
}

@ServiceConnection wires the container's URL into the Spring datasource without property plumbing. The first run pulls the image, and later runs reuse it. If Docker is not reachable, the test fails at startup with Could not find a valid Docker environment. Share one container across classes with a static singleton or the reuse option so you pay the startup once.

Mock the edges, not the middle

Mock what you do not own or cannot run cheaply: an HTTP client to a payment provider, a clock, a random source. Do not mock your own value objects or domain services, because a mock encodes your assumption about their behavior, and the assumption is what you are trying to test. The detailed rules are in what to mock and what to leave real, and the vocabulary is in test doubles explained. Strict stubbing in Mockito flags stubs that are never used, which is how [UnnecessaryStubbingException](/library/unnecessarystubbingexception-fix-mockito-junit-5) catches a test that stopped testing what it claims to.

Keep end-to-end tests few

Each end-to-end test starts the whole system, so it is slow and fails for reasons unrelated to your change: a port, a clock, a downstream. Keep three to ten covering the journeys that earn money, and run them in a separate stage. Everything else you were tempted to cover end to end can be covered one layer down at a fraction of the cost.

The pyramid, and where it bends

The usual picture is a wide base of unit tests, fewer integration tests and a narrow top. The test pyramid for Java services explains where that shape stops matching a service that is mostly glue between a database and a queue. In those services, integration tests against real infrastructure carry the weight, and the unit layer shrinks. Let the risk table above, not the picture, decide.

Suite time is a requirement

Set a budget: unit tests under 30 seconds, the full local suite under five minutes. When the suite exceeds what a developer will run before pushing, the tests stop being run. Fix that by moving cases down a layer, sharing containers and enabling parallel execution only once tests are independent.

A sample service and what each layer covers

Abstract advice is easy to nod at. So take one concrete service, an order API with a database, a payment client and a message producer, and assign its risks to layers. The class names are illustrative:

ClassWhat can go wrongLayer
DiscountPolicy, Money, OrderWrong arithmetic, invalid state transitionsUnit
OrderControllerBinding, validation, status codes, security rules@WebMvcTest
OrderRepositoryDerived queries, JPQL, mapping, migrations@DataJpaTest with a real database
PaymentClientRequest shape, timeouts, error mappingTest against a stubbed HTTP server
OrderEventsPublisherSerialization, topic, keyTest against a real broker
POST /orders through the whole stackWiring across all of the aboveA few integration tests
Checkout in a browserThe journey as a customer sees itOne or two end-to-end tests

Count the classes in each row of your own service and the numbers write the plan: most of the volume is in the first row, most of the risk that the first row cannot see is in the middle rows, and the last two rows exist to prove that the pieces are connected.

Unit tests that survive refactoring

A unit test fails for a good reason when the behavior changes, and for a bad one when the structure does. Bad failures come from asserting how the code works instead of what it produces. Compare two tests of the same discount rule:

java
// brittle: knows the implementation
@Test
void callsRepositoryAndAppliesRate() {
    when(rates.rateFor(GOLD)).thenReturn(new BigDecimal("0.10"));
    policy.priceFor(order);
    verify(rates).rateFor(GOLD);
    verifyNoMoreInteractions(rates);
}

// resilient: knows the rule
@Test
void goldCustomersPayTenPercentLess() {
    Order order = anOrder().forCustomer(gold()).withLine("sku-1", 2, "50.00").build();

    Money price = policy.priceFor(order);

    assertThat(price).isEqualTo(Money.of("90.00"));
}

The second test survives the day someone replaces the repository with a lookup table, and the first one does not. Use a builder, as above, so that each test states only the facts it cares about:

java
final class OrderBuilder {

    private CustomerId customer = new CustomerId("c-default");
    private final List<OrderLine> lines = new ArrayList<>();

    static OrderBuilder anOrder() { return new OrderBuilder(); }

    OrderBuilder forCustomer(Customer c) { this.customer = c.id(); return this; }

    OrderBuilder withLine(String sku, int quantity, String unitPrice) {
        lines.add(new OrderLine(new Sku(sku), quantity, Money.of(unitPrice)));
        return this;
    }

    Order build() { return new Order(OrderId.next(), customer, lines); }
}

A test with a ten-line setup of constructor arguments hides the one value that matters, and the builder keeps it in view. Parameterized tests are the other tool that keeps a rule's table readable:

java
@ParameterizedTest(name = "{0} items for {1} customer costs {2}")
@CsvSource({
    "1,  STANDARD, 50.00",
    "10, STANDARD, 450.00",
    "10, GOLD,     405.00",
    "0,  GOLD,     0.00"
})
void volumeAndTierDiscounts(int quantity, Tier tier, String expected) {
    Order order = anOrder().forCustomer(customerOf(tier)).withLine("sku-1", quantity, "50.00").build();
    assertThat(policy.priceFor(order)).isEqualTo(Money.of(expected));
}

For rules with a large input space, a property-based test states an invariant and lets a library generate the cases. With jqwik, "a discount never makes the price negative or higher than the original" is three lines, and it finds the zero or the overflow that nobody thought to write down.

Web slices that catch what unit tests cannot

A controller unit test with mocks passes when the request never binds. A @WebMvcTest runs the real MVC machinery against a mocked service, so binding, validation, serialization and security rules are exercised:

java
@WebMvcTest(OrderController.class)
class OrderControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean OrderService orders;

    @Test
    @WithMockUser(roles = "CUSTOMER")
    void createReturns201WithLocation() throws Exception {
        when(orders.create(any())).thenReturn(new OrderView(42L, "PLACED", new BigDecimal("99.00")));

        mvc.perform(post("/orders")
                .with(csrf())
                .contentType(MediaType.APPLICATION_JSON)
                .content("""
                    {"customerId":"c-1","lines":[{"sku":"sku-1","quantity":2}]}"""))
           .andExpect(status().isCreated())
           .andExpect(header().string("Location", endsWith("/orders/42")))
           .andExpect(jsonPath("$.status").value("PLACED"));
    }

    @Test
    @WithMockUser(roles = "CUSTOMER")
    void rejectsAnEmptyOrderWithProblemDetails() throws Exception {
        mvc.perform(post("/orders")
                .with(csrf())
                .contentType(MediaType.APPLICATION_JSON)
                .content("""
                    {"customerId":"c-1","lines":[]}"""))
           .andExpect(status().isBadRequest())
           .andExpect(content().contentTypeCompatibleWith("application/problem+json"));
    }

    @Test
    void anonymousCallersAreRejected() throws Exception {
        mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content("{}"))
           .andExpect(status().isUnauthorized());
    }
}

Three tests, three kinds of fault: a mapping that returns the wrong status, a validation rule that is missing, and a security rule that was never applied. Each failure would otherwise be found by a person with a browser. When a slice fails to start, read the first Caused by, which almost always names a bean the slice did not load, and import it with @Import, as described in test slices.

Persistence tests against the engine you ship

The repository test earlier shows the container. What goes inside it matters more. Test the queries you wrote, not the ones Spring Data derived for you, and test the migration, since a schema that differs from the mapping is a production incident:

java
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import(Containers.class)
class OrderRepositoryTest {

    @Autowired OrderRepository orders;
    @Autowired TestEntityManager em;

    @Test
    void findsOnlyOpenOrdersOfTheCustomerNewestFirst() {
        Customer ana = em.persist(aCustomer("ana"));
        Customer bob = em.persist(aCustomer("bob"));
        em.persist(anOrderFor(ana).status(OPEN).createdAt("2026-03-01T10:00:00Z").build());
        em.persist(anOrderFor(ana).status(OPEN).createdAt("2026-03-02T10:00:00Z").build());
        em.persist(anOrderFor(ana).status(SHIPPED).build());
        em.persist(anOrderFor(bob).status(OPEN).build());
        em.flush();
        em.clear();

        List<Order> found = orders.openFor(ana.getId());

        assertThat(found).extracting(o -> o.getCreatedAt().toString())
            .containsExactly("2026-03-02T10:00:00Z", "2026-03-01T10:00:00Z");
    }
}

The flush and clear pair is deliberate. Without it, the query returns the entities that are already in the first-level cache and never reaches the database, and a wrong query still passes. Run Flyway migrations in the same test configuration, and set spring.jpa.hibernate.ddl-auto=validate, so the test fails when the mapping and the schema disagree. Add the statement-counting assertion for any query that feeds a list, as shown in detecting N plus 1 queries in tests.

One container configuration, shared

Containers are the expensive part of integration tests, so start each once per run and share it. Put them in one configuration class that every test imports:

java
@TestConfiguration(proxyBeanMethods = false)
public class Containers {

    @Bean
    @ServiceConnection
    PostgreSQLContainer<?> postgres() {
        return new PostgreSQLContainer<>("postgres:17").withReuse(true);
    }

    @Bean
    @ServiceConnection
    KafkaContainer kafka() {
        return new KafkaContainer(DockerImageName.parse("apache/kafka:3.9.0"));
    }
}

Every test that imports Containers with the same other annotations shares a Spring context and the containers behind it, as covered in caching the Spring test context. withReuse(true) lets a developer's local run keep the container between runs when the user has enabled reuse in their Testcontainers configuration, which turns a ten-second startup into an instant one.

The HTTP boundary: stub the server, not the client

A mocked PaymentClient proves that the service calls the mock. A stubbed HTTP server proves that the real client builds the right request and understands the real response, including the bad ones:

java
@SpringBootTest
@Import(Containers.class)
@WireMockTest(httpPort = 8089)
class PaymentClientIT {

    @Autowired PaymentClient payments;

    @DynamicPropertySource
    static void urls(DynamicPropertyRegistry registry) {
        registry.add("payments.base-url", () -> "http://localhost:8089");
    }

    @Test
    void sendsTheChargeAndReadsTheReceipt() {
        stubFor(post("/charges")
            .withHeader("Idempotency-Key", matching(".+"))
            .withRequestBody(matchingJsonPath("$.amount", equalTo("99.00")))
            .willReturn(okJson("""
                {"id":"ch_1","status":"succeeded"}""")));

        Receipt receipt = payments.charge(new Charge("order-1", Money.of("99.00")));

        assertThat(receipt.status()).isEqualTo("succeeded");
    }

    @Test
    void mapsAGatewayTimeoutToAPaymentUnavailableError() {
        stubFor(post("/charges").willReturn(aResponse().withFixedDelay(3000).withStatus(200)));

        assertThrows(PaymentUnavailable.class,
            () -> payments.charge(new Charge("order-2", Money.of("5.00"))));
    }
}

The second test is the one nobody writes and the one that matters: what the service does when the dependency is slow. Add a case for a 500, a malformed body and a connection reset. These are the failures production will deliver, and a test double that always succeeds hides them all.

Asynchronous behavior without sleeps

A message published to a broker arrives later. The wrong test sleeps for two seconds and hopes. The right one waits for a condition, with a timeout:

java
@Test
void placingAnOrderPublishesAnEvent() {
    ResponseEntity<Void> response = rest.postForEntity("/orders", newOrder(), Void.class);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);

    await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> {
        List<ConsumerRecord<String, String>> records = consumer.received("orders");
        assertThat(records).hasSize(1);
        assertThat(records.get(0).value()).contains("\"event\":\"OrderPlaced\"");
    });
}

Awaitility polls until the assertion passes or the timeout expires, so a fast system finishes quickly and a slow one gets a fair chance. Keep the timeout generous, because it only costs time on failure. A test that needs Thread.sleep to pass is a flaky test with a delay, and the first thing to look for in a flaky suite.

Contracts between services

When two services agree on a request and a response, each side's tests can drift while both stay green. A contract test pins the agreement in a file both sides run against. The lightest version needs no framework: a shared JSON example that the provider's test must produce and the consumer's test must parse:

java
// provider side: the response must match the agreed example
@Test
void orderResponseMatchesTheContract() throws Exception {
    String expected = Files.readString(Path.of("src/test/resources/contracts/order-response.json"));
    mvc.perform(get("/orders/42"))
       .andExpect(status().isOk())
       .andExpect(content().json(expected, JsonCompareMode.STRICT));
}

// consumer side: the same file must deserialize into the client's type
@Test
void clientUnderstandsTheContract() throws Exception {
    String json = Files.readString(Path.of("src/test/resources/contracts/order-response.json"));
    OrderView view = new ObjectMapper().findAndRegisterModules().readValue(json, OrderView.class);
    assertThat(view.id()).isEqualTo(42L);
}

Keep the file in a place both repositories read, such as a small shared artifact. For many consumers, Spring Cloud Contract or Pact automate the same idea and add a broker to track which version of which consumer expects what. Pick the tool when the manual file approach starts to hurt, not before.

Check the tests themselves

Coverage says which lines ran, and nothing about whether a test would notice if the line were wrong. Mutation testing changes the code in small ways, such as flipping a comparison or deleting a call, and reports the changes the suite failed to catch:

XML
<plugin>
  <groupId>org.pitest</groupId>
  <artifactId>pitest-maven</artifactId>
  <configuration>
    <targetClasses><param>dev.javahacks.shop.domain.*</param></targetClasses>
    <mutationThreshold>80</mutationThreshold>
  </configuration>
</plugin>
Shell
./mvnw org.pitest:pitest-maven:mutationCoverage

Run it on the domain package, where logic lives, and not on controllers and configuration, where it produces noise. Treat a surviving mutant as a question: either a test is missing, or the code has a behavior nobody cares about, and both are worth knowing. Do not put a score on a dashboard as a target, since a number someone is rewarded for becomes a number someone games.

Organizing the build around the strategy

The layers should map to build stages, so that feedback arrives in order of cost. Unit tests run in the compile phase of every build, and integration tests run after, under a separate plugin:

XML
<plugin>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <excludes><exclude>**/*IT.java</exclude></excludes>
  </configuration>
</plugin>
<plugin>
  <artifactId>maven-failsafe-plugin</artifactId>
  <executions>
    <execution>
      <goals><goal>integration-test</goal><goal>verify</goal></goals>
    </execution>
  </executions>
</plugin>

With this split, ./mvnw test runs in seconds and is what a developer runs on every change, ./mvnw verify runs everything and is what CI runs on every push, and a pipeline can fail fast on the unit stage before it pays for containers. Record the time of each stage in the build log and review it monthly. The numbers tell you when the suite is turning into the thing nobody runs. The details of the Maven side are in Surefire, Failsafe and JUnit.

Flaky tests are a defect with an owner

A test that fails one run in fifty teaches the team to rerun. Handle each one the day it appears. Quarantine it with a tag so that it stops blocking others, file it with the failure output attached, and fix the cause: shared state between tests, an unseeded random source, time, ordering, or a race in the code under test, which is the case where the test is the only thing telling the truth. Never add an automatic retry to the whole suite, because it converts a signal into noise and a real intermittent bug into a pass.

Rolling the strategy out on an existing suite

Nobody starts from zero, so the practical question is what to do on Monday. A sequence that has worked for teams with a slow, distrusted suite:

  1. Measure first. Record total time, time per layer, the number of tests and the failures per week for a month.
  2. Fix the flaky tests and delete the dead ones. A smaller trusted suite is better than a larger doubted one.
  3. Move the slowest full-context tests to slices where the risk allows, and share the containers.
  4. Add the missing middle: a real-database repository test for each hand-written query, and a stubbed-server test for each outbound client with the failure cases.
  5. Write down the layer table for the service, one page, and use it in code review: "which layer should catch this?"
  6. Set the time budget and watch it. When a new test pushes the suite over, the author finds the one to move down.

At the end of a quarter, the suite should be faster, the failures should point at real problems and a red build should mean something. That, and not the shape of a diagram, is the measure of the strategy.

Names and structure that make failures readable

When a test fails in CI, the report shows its name before anything else, so the name should state the behavior and the condition. test1 and shouldWork fail without telling anyone what broke. A test class named after the class under test, with method names that read as sentences, turns the build log into documentation:

java
class OrderTest {

    @Nested
    class WhenPlacing {

        @Test
        void anEmptyOrderIsRejected() { /* ... */ }

        @Test
        void aPlacedOrderCannotGainLines() { /* ... */ }

        @Test
        void aPlacedOrderPublishesOneEvent() { /* ... */ }
    }

    @Nested
    class WhenCancelling {

        @Test
        void aShippedOrderCannotBeCancelled() { /* ... */ }
    }
}

Inside each test, keep the three parts visible, in order: set up the situation, perform one action, assert on the outcome. A test with two actions is two tests, and a test with a loop and an if has logic that nobody tests. Prefer AssertJ's fluent assertions for their failure messages, which show the expected and actual values in full, and give custom assertions to the types you assert on often.

Test the configuration, because it fails in production first

A service that compiles and passes its tests can still fail to start, since the failure lives in properties, profiles and bean wiring. One test that boots the real application with the production-like profile finds most of it:

java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Import(Containers.class)
@ActiveProfiles("prod-like")
class ApplicationStartsTest {

    @Autowired ApplicationContext context;
    @Autowired TestRestTemplate rest;

    @Test
    void contextLoadsAndHealthIsUp() {
        assertThat(context.getBeansOfType(OrderService.class)).hasSize(1);

        ResponseEntity<String> health = rest.getForEntity("/actuator/health", String.class);

        assertThat(health.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(health.getBody()).contains("\"status\":\"UP\"");
    }
}

It is slow compared with a unit test and cheap compared with a failed deployment. Pair it with a test that checks the properties your code requires are bound, by loading the @ConfigurationProperties class with a minimal context and asserting that validation rejects a missing value. A required setting that fails at startup, with a named property in the message, is a gift to whoever deploys it at night.

Architecture rules as tests

Some decisions are about structure, and a code review is a weak place to enforce them. ArchUnit expresses them as tests that run with everything else:

java
@AnalyzeClasses(packages = "dev.javahacks.shop", importOptions = ImportOption.DoNotIncludeTests.class)
class ArchitectureTest {

    @ArchTest
    static final ArchRule domainDoesNotDependOnSpring =
        noClasses().that().resideInAPackage("..domain..")
            .should().dependOnClassesThat().resideInAPackage("org.springframework..");

    @ArchTest
    static final ArchRule controllersDoNotTouchRepositories =
        noClasses().that().resideInAPackage("..web..")
            .should().dependOnClassesThat().resideInAPackage("..persistence..");
}

The first rule is what keeps the domain testable without a context, which is the foundation of the whole strategy: the day a domain class gains an @Autowired, the fast layer starts to decay, and this test says so. Keep the rule list short and tied to decisions the team made on purpose.

What not to test

Part of a strategy is the list of things you decline to test, and writing it down prevents a slow drift into writing tests for coverage. Do not test getters, setters and constructors that hold no logic. Do not test the framework: asserting that @Transactional rolls back, or that Spring Data can save an entity, repeats the framework's own suite. Do not test private methods directly; if one is complicated enough to want a test, it wants to be its own class. And do not copy the implementation into the test, as in a test that recomputes the expected discount with the same formula, since a bug in the formula appears on both sides and the test agrees with it. Use literal expected values worked out by hand or taken from the business rule.

Where this plan does not fit

This layout assumes a request-response service with a relational database. A data pipeline wants property-based and golden-file tests; a UI-heavy application needs browser tests that this strategy keeps minimal on purpose. A library should invest in unit tests and a compatibility matrix instead of containers. In each case, keep the risk table and change the rows.

Also inJUnit
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.