All posts / Spring Boot

Building a Test Suite That Actually Holds Up: A Spring Boot Field Guide

NordLearn · · 9 min read

On this page

Building a Test Suite That Actually Holds Up: A Spring Boot Field Guide

Building a Test Suite That Actually Holds Up: A Spring Boot Field Guide

Why this post exists

Almost every Spring Boot codebase I’ve worked on has tests. Very few have a test suite — a deliberate, layered strategy where each type of test has a clear job, runs at the right speed, and doesn’t duplicate what another layer already covers. Instead, what usually happens is: someone writes a @SpringBootTest for everything because it "just works," the suite gets slower every sprint, nobody trusts a red build anymore because it's "probably flaky," and eventually people stop writing tests at all.

This post walks through the four layers — unit, slice, integration, and regression — explaining not just the tools but why each layer exists and what happens when you skip it or misuse it. The goal isn’t “100% coverage.” It’s a suite that catches real bugs, runs fast enough that people actually run it, and stays maintainable as the codebase grows.

1. Unit tests — the foundation, and the one people get wrong most

What it is: Testing a single class or method in complete isolation. No Spring context. No database. No network. Every dependency is mocked or faked.

@ExtendWith(MockitoExtension.class)
class OrderPricingServiceTest {

    @Mock
    private DiscountRepository discountRepository;

    @InjectMocks
    private OrderPricingService pricingService;

    @Test
    void appliesPercentageDiscountCorrectly() {
        when(discountRepository.findActiveDiscount("SUMMER10"))
            .thenReturn(new Discount("SUMMER10", 10));

        BigDecimal result = pricingService.calculatePrice(
            new BigDecimal("100.00"), "SUMMER10");

        assertThat(result).isEqualByComparingTo("90.00");
    }
}

Why it matters: Speed and precision. A well-written unit test suite runs in seconds, not minutes, and when one fails, it tells you exactly which piece of logic broke — no digging through a stack trace that spans five layers of Spring plumbing. This is the layer that should catch the majority of your logic bugs, because it’s cheap to write a lot of them and cheap to run them constantly.

Where people get it wrong:

If a test mocks every single dependency and just checks that “method X was called,” it’s not really testing that the code does the right thing — just that it made a call. It’s better to assert on the actual output or state change instead.

// Wrong: only checks that a method was called, not that the result is correct
verify(discountRepository).findActiveDiscount("SUMMER10");

// Right: checks the actual outcome
assertThat(result).isEqualByComparingTo("90.00");

Another common one: reaching for @MockBean or any Spring annotation inside what's supposed to be a plain unit test. If that's happening, it's usually a sign the class under test is doing too much, or that what's really needed is a slice test instead.

// Wrong: pulling in Spring just to test plain logic
@SpringBootTest
class OrderPricingServiceTest { ... }

// Right: plain Mockito, no Spring involved
@ExtendWith(MockitoExtension.class)
class OrderPricingServiceTest { ... }

And it’s worth skipping tests for getters, setters, and other framework-generated code — that’s testing Lombok or Spring, not your logic.

// Wrong: only tests that Lombok generated a working setter/getter
order.setStatus("PENDING");
assertThat(order.getStatus()).isEqualTo("PENDING");

// Right: test behavior that involves actual logic
assertThat(order.canBeCancelled()).isTrue(); // depends on status + a business rule

Maintainability tip: Use a consistent naming convention across the team — methodName_condition_expectedResult() or shouldDoX_whenY(), doesn't matter which, just pick one. Six months from now, someone scanning a failed test list should understand what broke without opening the file.

2. Slice tests — Spring’s middle ground, and the most underused layer

What it is: Spring Boot loads only part of the application context — just the layer you’re testing — instead of the whole thing. This is the layer most teams skip entirely, jumping straight from unit tests to full @SpringBootTest, which is where a lot of suite slowness comes from.

**@WebMvcTest** — the web layer:

@WebMvcTest(OrderController.class)
class OrderControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private OrderService orderService;

    @Test
    void returns404WhenOrderNotFound() throws Exception {
        when(orderService.findById(99L)).thenThrow(new OrderNotFoundException(99L));

        mockMvc.perform(get("/orders/99"))
            .andExpect(status().isNotFound());
    }
}

This loads controllers, filters, JSON serialization (Jackson), and exception handlers — but mocks the service layer. It’s the right place to test request validation, HTTP status codes, and JSON shape, without paying for a full context or a database.

**@DataJpaTest** — the persistence layer:

@DataJpaTest
@Testcontainers
class OrderRepositoryTest {

    @Container
    static PostgreSQLContainer<?> postgres =
        new PostgreSQLContainer<>("postgres:16-alpine");

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
    }

    @Autowired
    private OrderRepository orderRepository;

    @Test
    void findsOrdersWithoutTriggeringNPlusOne() {
        // real Postgres, real query behavior — not H2's approximation of it
    }
}

Why this layer matters specifically for you: this is where you’d actually catch the N+1 query and OSIV issues from the JPA post. An in-memory H2 database often won’t reproduce the same query-generation or locking behavior as real Postgres — pairing @DataJpaTest with Testcontainers (rather than the default embedded DB) is what makes this layer trustworthy instead of a false sense of security.

Maintainability tip: slice tests are cheap enough to write generously, but resist the urge to slice-test every controller method exhaustively — one or two tests per meaningful behavior (happy path, one validation failure, one not-found case) is usually enough; the exhaustive combinatorics belong at the unit level, testing the underlying service logic directly.

3. Integration tests — the whole app, wired together for real

What it is: The full Spring context boots, with real (or realistically simulated) infrastructure — actual database, actual message broker if you use one, real HTTP calls in and out of the app.

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

    @Container
    static PostgreSQLContainer<?> postgres =
        new PostgreSQLContainer<>("postgres:16-alpine");

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void createOrderEndToEnd() {
        OrderRequest request = new OrderRequest("SKU-123", 2);

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

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        assertThat(response.getBody().status()).isEqualTo("PENDING");
    }
}

Why this layer matters: it’s the only layer that catches wiring problems — a missing bean, a misconfigured @Transactional boundary, a security filter blocking a request it shouldn't, serialization breaking between two real components. Unit and slice tests can all pass individually while the app is still broken when everything runs together; this is the layer that catches that.

Testcontainers is the piece that makes this trustworthy. Before Testcontainers became standard, most teams either used embedded/in-memory substitutes (which drift from production behavior) or shared a real test database (which causes flaky, order-dependent tests when multiple test runs collide). Testcontainers gives every test run its own disposable, real instance of Postgres/Kafka/Redis/whatever you depend on — closer to prod, and isolated per run.

Where people get it wrong:

The biggest one is using @SpringBootTest for everything, including things a plain unit test should cover. This is the single biggest source of slow, unmaintainable suites — a full context startup is genuinely expensive (JVM class loading, bean initialization, DB connection setup), and multiplying that cost across hundreds of tests turns a 30-second suite into a 20-minute one. If a test doesn't need the full context, it shouldn't have to pay for it.

Shared, mutable test data is another trap. If test A creates an order and test B assumes an empty database, the suite becomes order-dependent and starts failing randomly the moment someone reorders or parallelizes the tests. Each integration test should set up — and ideally clean up — its own data, or lean on @Transactional with rollback if that fits your database setup.

And it’s worth being honest about what “integration” actually means on your team. Some people call anything with @SpringBootTest an integration test, even when half the dependencies are mocked. If the database is mocked, it's not really testing integration with the database.

Maintainability tip: keep a test data builder pattern (or a library like instancio / hand-rolled builders) rather than constructing entities field-by-field in every test. When your Order entity gains a new required field six months from now, you want to update one builder, not forty test methods.

4. Contract tests — when your integration test’s mock lies to you

What it is: A layer that catches something none of the previous three do — the case where the other side of an API call changes shape without you knowing.

This came up as a comment on this post, and it’s worth calling out on its own rather than folding it into integration or regression, because it’s protecting against a genuinely different failure mode.

Your Testcontainers-backed integration tests protect you against your own infrastructure drifting from what you assume — a real Postgres, a real query plan, a real schema. But when your service calls another team’s API, your integration test almost always runs against a local mock or stub you wrote once. That mock doesn’t know when the real API changes. If the other team renames a field, adds a required one, or changes a status code next quarter, your mock stays exactly as it was — and your test keeps passing right up until the real call breaks in staging or production.

This cuts both ways, and it’s worth thinking about both directions separately:

You as the provider — protecting teams that depend on your API:

// Spring Cloud Contract - defines the contract once,
// generates both provider-side tests and consumer stubs
Contract.make {
    request {
        method GET()
        url '/orders/1'
    }
    response {
        status 200
        body(
            id: 1,
            status: "PENDING"
        )
    }
}

This catches the case where your integration tests all pass because they only test your service in isolation, but a change to your response shape silently breaks a consumer team’s service the moment it ships.

5. Smoke tests — a different question entirely

What it is: Not “is the logic correct” — that’s already been verified before this point. Smoke tests ask “did the deployment actually succeed, and is the app minimally alive?” They run against a real, running environment — staging, or new pods before a full traffic cutover — not against an embedded test context.

@Tag("smoke")
class ProductionSmokeTest {

    private static final String BASE_URL =
        System.getProperty("baseUrl", "https://staging.yourservice.com");

    @Test
    void healthEndpointRespondsReady() {
        given()
            .baseUri(BASE_URL)
        .when()
            .get("/health/ready")
        .then()
            .statusCode(200);
    }

    @Test
    void criticalOrderEndpointIsReachable() {
        given()
            .baseUri(BASE_URL)
        .when()
            .get("/orders/health-check-order-id")
        .then()
            .statusCode(anyOf(is(200), is(404))); // reachable, not necessarily found
    }
}

Why this layer matters: it’s your last line of defense between “the pipeline said tests passed” and “a real user hits a broken deployment.” Config errors, missing environment variables, a database connection string pointing at the wrong environment — none of these show up in your integration test suite, because that suite runs against its own isolated, correctly-configured test infrastructure. Smoke tests are what catch “it works in every environment except the one that matters.”

Keep it small on purpose. Five to ten tests, running in under a minute: health endpoint, one or two critical business flows, auth working. This is not the place for thoroughness — that’s what integration tests are for. Smoke tests exist to fail fast and loud immediately after deploy, so you can roll back before real traffic is affected.

6. Regression tests — protecting what already works

What it is: Not a separate tool, but a separate purpose. Regression tests are the tests — often your integration tests, plus a few specific additions — that exist specifically to make sure a bug that was fixed once doesn’t come back, and that a change to one part of the system doesn’t silently break another.

The most valuable regression tests are the ones written after a real production bug. When you fix something like the multipart upload truncation bug from earlier in this series, the fix isn’t complete until there’s a test that would have caught it — reproducing the exact condition (partial stream availability, in that case) that caused the original failure. This is how a test suite gets smarter over time instead of just bigger.

Maintainability tip: tag regression-specific tests clearly (@Tag("regression")) and, where a test exists specifically because of a past incident, say so in the test name or a comment — void multipartUpload_doesNotTruncate_whenStreamPartiallyAvailable() tells the next engineer exactly what production incident this test is protecting against, so nobody "cleans it up" thinking it's a redundant edge case.

Keeping the whole suite maintainable as it grows

A few practices that matter more than any individual test.

It helps to enforce the pyramid shape rather than just hope it happens naturally. If unit tests get outnumbered by @SpringBootTest integration tests, the suite will get slow and brittle as the codebase grows, no matter how well each individual test is written. It's worth checking the ratio now and then — a healthy suite usually looks like a wide base of unit tests, a solid middle layer of slice tests, and a comparatively small number of integration tests covering the critical paths.

Tag everything, and let CI run the right subset at the right time — fast tests on every PR, integration tests on merge, smoke tests post-deploy, regression and contract tests nightly or before a release. A suite that takes 20 minutes on every single commit is a suite people quietly start skipping.

Tests that no longer earn their keep should probably be deleted. If something hasn’t failed in two years and doesn’t correspond to any real risk — not a past incident, not a genuinely tricky piece of logic — it’s just weight. That’s uncomfortable advice for a lot of teams, but a bloated, slow suite nobody trusts is worse than a smaller one people actually run and believe.

And flaky tests need to be fixed or deleted, never just tolerated. The moment a team starts saying “just rerun it, that one’s flaky,” the whole suite’s credibility starts eroding, because nobody can tell a real failure from a known flaky one anymore.

The honest takeaway

None of this is about chasing a coverage percentage. It’s about matching the right kind of test to the right kind of risk — fast, isolated tests for logic; slice tests for framework wiring at the edges; integration tests, backed by real infrastructure via Testcontainers, for the parts that only break when everything runs together; smoke tests for “did this actually deploy correctly”; and regression tests that specifically remember your past incidents so they don’t repeat. Get that shape right, and the suite stays fast and trusted as the codebase grows — which is the only kind of test suite that actually protects you.