Testing Layers and Production Readiness

Testing Layers and Production Readiness in Spring Boot: Before an airliner leaves the gate the crew does not fire up every engine and see what happens.

The Analogy: An Aircraft's Staged Pre-Flight Checks

Before an airliner leaves the gate the crew does not fire up every engine and see what happens. They work through a checklist that is deliberately staged from cheapest to most expensive. First come cockpit checks a pilot can do alone in seconds: flip a switch, confirm a single indicator responds. These cost nothing, need no ground crew, and catch the most common faults. Only if those pass does the crew move on to the costlier stages.

The next stage bench-tests one system at a time. Ground engineers power up just the hydraulics rig, or just the avionics bus, in isolation, with the surrounding systems simulated rather than really running. Testing one subsystem on its own is far cheaper than a full power-up and it pins any fault to that exact box. A hydraulics fault found on the hydraulics bench is unambiguous; the same fault found only during a full engine run costs an hour of everyone's time to trace back.

The most expensive stage is the full power-up: every engine running, every system live, the whole aircraft behaving as it will in the air. This is the only test that proves the systems work together, but it burns fuel and ties up a runway slot, so the crew reserves it for a small number of end-to-end checks rather than repeating it for things a bench test already proved. The discipline is to prove each thing at the cheapest stage that can prove it, and escalate only when a cheaper stage genuinely cannot.

Alongside the checklist sits the cockpit warning panel: a bank of lights that report the live state of each system once flying. A sensible panel separates two very different questions. One light asks is this airframe fundamentally flyable -- if it goes red the answer is land and shut down. Another asks is this system ready to be used right now -- if it goes red you simply avoid that system until it clears. The panel fails the crew when those two questions are wired to the same light: a merely-not-ready system trips the shut-down alarm, the crew shuts down an aircraft that was perfectly flyable, and the fault never actually gets a chance to clear.

Syntax or Core Structure

Spring Boot gives you a graded set of test slices, each loading only part of the application. The rule mirrors the pre-flight checklist: pick the cheapest slice that can actually prove the behaviour you care about. A plain unit test loads no Spring context at all; @WebMvcTest loads only the web layer; @DataJpaTest loads only persistence; @SpringBootTest loads everything.

// Cheapest: no container, just the class under test
class PriceCalculatorTest {
    @Test
    void appliesPercentageDiscount() {
        var result = new PriceCalculator().apply(new BigDecimal("100"), 10);
        assertThat(result).isEqualByComparingTo("90");
    }
}

// Web layer only -- controller, validation, JSON mapper; service is mocked
@WebMvcTest(ProductController.class)
class ProductControllerTest {
    @Autowired MockMvc mockMvc;
    @MockBean ProductService service;

    @Test
    void rejectsBlankName() throws Exception {
        mockMvc.perform(post("/api/products")
                .contentType(APPLICATION_JSON)
                .content(blankNamePayload()))
            .andExpect(status().isBadRequest());
    }
}

The behaviour under test -- a blank name yields HTTP 400 -- lives entirely in the web layer, so the cheapest slice that can prove it is @WebMvcTest. Rank every approach by how many layers it loads against whether it can prove that 400, and the choice becomes mechanical:

Output:

approach          layers   ctx   proves web 400?
----------------------------------------------
plain unit test   0        no    no
@WebMvcTest       1        yes   yes
@DataJpaTest      1        yes   no
@SpringBootTest   3        yes   yes
----------------------------------------------
cheapest that proves it: @WebMvcTest
layers it loads     : 1

Technical Depth: What Each Slice Wires, and How Health Aggregates

The slice map

Each annotation is a contract about which beans exist in the context. This is the reference you reach for when a test fails with "no qualifying bean" or, worse, quietly talks to a real database:

SliceWeb layerService beansRepository or DataSourceContext
plain unitnonenonenonenot started
@WebMvcTestloadedyou mockabsentstarted
@DataJpaTestabsentnoneloaded in-memorystarted
@SpringBootTestloadedloadedloadedstarted

@WebMvcTest bean presence

A @WebMvcTest loads the controller, the validation engine, and the JSON mapper, mocks the service you name, and leaves the repository and datasource out of the context entirely:

@WebMvcTest(ProductController.class)
class ProductControllerTest {
    @Autowired MockMvc mockMvc;      // loaded
    @Autowired ObjectMapper mapper;  // loaded (JSON)
    @MockBean ProductService service; // mocked
    // ProductRepository, DataSource: NOT in this context
}

Output:

component           in @WebMvcTest
----------------------------------------
ProductController   loaded
Bean validation     loaded
JSON mapper         loaded
ProductService      mocked
ProductRepository   absent
DataSource          absent
----------------------------------------
loaded        : 3
mocked        : 1
absent        : 2
can hit db    : no

Because the repository and datasource are absent, a @WebMvcTest physically cannot reach a database. If your controller calls the repository directly, the test fails to load rather than silently hitting one -- the slice doing its job.

Health aggregation: the most severe indicator wins

Actuator's /actuator/health composes many indicators into one status. It does not average them -- it takes the most severe. Rank the statuses by severity (DOWN and OUT_OF_SERVICE are worse than UP, which is worse than UNKNOWN) and the aggregate is simply the worst one present. A single DOWN dependency drags the whole endpoint to DOWN and its HTTP code to 503:

// each indicator reports independently; the registry aggregates
Health db()        { return Health.up().build(); }
Health diskSpace() { return Health.up().build(); }
Health redis()     { return Health.down().build(); }
Health ping()      { return Health.up().build(); }

Output:

indicator     status        severity rank
----------------------------------------
db            UP            2
diskSpace     UP            2
redis         DOWN          0
ping          UP            2
----------------------------------------
aggregate status: DOWN
http status     : 503
rule            : most severe wins

The lower the rank, the more severe the status, so aggregation is a minimum over ranks. This is why a healthy application can report DOWN the instant one non-critical cache goes offline -- and why marking a genuinely optional dependency as a full health indicator can make your whole service look dead over something it could run without.

Real World Example: A Restart Loop Born From One Misgrouped Probe

A team runs a Spring Boot order service on Kubernetes. It depends on Postgres, which is critical, and Redis, which is only a cache -- nice to have, not essential. They enable probes and, wanting Redis problems to be visible, add Redis to the liveness group. The configuration wires the two Actuator probes that Kubernetes will call:

@Configuration
class ProbeConfig {
    // Config A (shipped): redis is in the LIVENESS group
    @Bean
    HealthGroup liveness(RedisHealth redis, ProcessHealth process) {
        return groupOf("liveness", process, redis); // <-- the mistake
    }
    @Bean
    HealthGroup readiness(ProcessHealth process) {
        return groupOf("readiness", process);
    }
}
# kubernetes wiring: a failed liveness probe RESTARTS the pod;
# a failed readiness probe only STOPS ROUTING to it
livenessProbe:  { httpGet: { path: /actuator/health/liveness } }
readinessProbe: { httpGet: { path: /actuator/health/readiness } }

One afternoon Redis goes down for maintenance. Redis reports DOWN; because it sits in the liveness group, /actuator/health/liveness aggregates to DOWN. Kubernetes reads a failed liveness probe as "this process is broken" and does the one thing it knows: it restarts the pod. The restart cannot bring Redis back -- Redis is a separate service -- so the fresh pod's liveness is DOWN again within seconds and Kubernetes restarts it again. Compare that to the correct grouping, where Redis sits in readiness instead:

Output:

config                liveness  readiness  k8s action
--------------------------------------------------------
A: redis in liveness  DOWN      UP         restart (loops)
B: redis in readiness UP        DOWN       stop routing
--------------------------------------------------------
redis status          : DOWN
configs restart-looping: 1
safe grouping         : B

Under Config B the pod stays alive; Kubernetes merely pulls it out of the load-balancer rotation until Redis returns, then routes to it again -- self-healing with no human intervention. Under the shipped Config A the service enters CrashLoopBackOff and pages the on-call engineer, over a cache that was never required to serve a single request.

The design flaw is in the code shown: putting redis in the liveness group conflates "is this process fundamentally broken?" with "is a dependency currently reachable?". Liveness must depend only on state a restart can actually fix -- a deadlock, corrupt in-memory state -- never on external dependencies, because restarting can never repair something outside the process. A second, quieter flaw is that the cache is modelled as a hard health indicator at all: even in readiness a brief Redis blip needlessly removes the pod from rotation, when a resilient service would degrade to the database and still report UP. The fix is a single line -- move redis out of liveness -- but the failure it prevents is a production outage that looks, from every dashboard, exactly like the application itself crashing.

Common Mistakes

  1. Reaching for @SpringBootTest by default. It boots the entire context for every test, so a suite that should run in seconds takes minutes. Prove behaviour at the cheapest slice that can prove it and reserve the full boot for a few end-to-end paths.
  2. Testing against H2 while production runs Postgres. In-memory H2 accepts SQL Postgres rejects and differs on constraints, types, and locking, so green tests hide real failures. Run the actual engine with Testcontainers.
  3. Expecting the repository bean inside a @WebMvcTest. The slice deliberately leaves persistence out of the context; a controller that calls a repository directly makes the test fail to load. Mock the service the controller depends on with @MockBean.
  4. *Exposing all Actuator endpoints with include: "".** That publishes /actuator/env, /actuator/beans, and heap dumps to anyone who can reach the port. Expose only the endpoints you need -- typically health, info, and metrics.
  5. Leaving show-details ungated so health leaks internals. show-details: always returns connection strings and dependency detail to unauthenticated callers. Gate it behind when-authorized so the public probe stays a bare UP or DOWN.
  6. Wiring liveness and readiness to the same check. If both point at one aggregate, a not-ready condition trips the restart alarm and a broken process is never taken out of rotation. Keep them separate: liveness answers "restart me?", readiness answers "route to me?".
  7. Putting an external dependency in the liveness group. A restart can only fix state inside the process, so a DOWN database or cache in liveness produces an endless CrashLoopBackOff. External dependencies belong in readiness, if anywhere.
  8. Assuming one DOWN indicator will not matter. Health aggregation takes the most severe status, not a majority or an average, so a single DOWN drives the whole endpoint to DOWN and its HTTP code to 503. Only register indicators you are willing to fail the service on.
  9. Asserting on free-text error messages. A test that checks the exact wording of a message breaks the moment someone rephrases it, even though the behaviour is unchanged. Assert on the status code and a stable error code instead.

Best Practices

  • Default to plain unit tests with constructor injection; they need no container and run in milliseconds. Most of a healthy suite looks like this.
  • Match each test to the narrowest slice that proves it: @WebMvcTest for controllers and status codes, @DataJpaTest for queries, @SpringBootTest only for critical end-to-end flows.
  • Verify persistence against the real engine with Testcontainers and @ServiceConnection, so the datasource is wired automatically and no in-memory dialect hides a production failure.
  • Expose Actuator deliberately: include only health, info, and metrics, and keep show-details behind when-authorized so nothing sensitive reaches an anonymous caller.
  • Enable liveness and readiness probes and keep them answering different questions -- restartable process state versus ability to serve traffic.
  • Keep external dependencies out of the liveness group; a restart cannot repair a service running in another pod.
  • Model optional dependencies so a blip degrades gracefully rather than failing health, and register a hard indicator only for things that truly make the service unusable.
  • Assert on status codes and stable error codes rather than message text, and lean on @DataJpaTest rollback to keep cases independent.

Practice Exercises

  1. For each behaviour, name the cheapest test that proves it and say how many layers it loads: a discount formula, a blank-name-yields-400 response, a custom @Query, and a full checkout flow. Justify why a cheaper slice cannot prove the web-layer case.
  2. An /actuator/health endpoint aggregates four indicators reporting UP, UP, OUT_OF_SERVICE, and DOWN. Give the aggregate status and the HTTP code the endpoint returns, and explain the severity rule that produces them.
  3. A service is stuck in CrashLoopBackOff whenever its message broker is briefly unavailable. Given that the broker sits in the liveness group, describe the exact sequence Kubernetes follows and the one-line change that stops the loop.
  4. Write the management YAML for a production service that exposes only health, info, and metrics, hides health detail from anonymous callers, and enables liveness and readiness probes. State which dependency you would place in readiness and why none belongs in liveness.