What you'll learn: By the end of this lesson you will be able to name the three levels of a backend test suite (unit, web slice, integration), say what each can and cannot see, decide which level should own a given rule, and read the Spring lab's captured output to see three planted defects caught by different levels.
Think of a car factory. A worker checks each part at the bench: quick and cheap, but a bench check cannot tell you the door fits the frame. A test drive on the track tells you everything, but it takes an hour and every failed drive sends you hunting through the whole car. A good factory does both, in proportion: many cheap bench checks, fewer fit checks, a handful of drives.
A backend test suite works the same way. This lesson is the map of the levels and the rule for choosing among them. The database-specific setup and its limits are the subject of the next lesson, integration testing with Testcontainers; contract testing, load testing and testing asynchronous flows are separate lessons later in this module.
Verified with Spring Boot 4.1.2, Java 25, H2 2.4.240 and the Spring reference documentation, on 2026-12-01.
The core idea
A test is a trade between what it can see and what it costs. A unit test sees one rule and runs in milliseconds; a slice test sees one layer wired to Spring; an integration test sees several layers and the real SQL, and costs a context start-up and a database. Put each check at the cheapest level that can still see the thing it checks, and keep few tests at the expensive levels.
Three illustrations run through the lesson:
- Minimal example: a discount rule,
CouponPricing, tested as plain Java with no Spring. - Realistic example: ShopStream's
POST /v1/orders, tested at all three levels in the lab. - Failure example: a stock update whose guard clause was dropped from the SQL. The fast suites stay green; only a test that runs the real SQL fails.
What a level means
A level is not a size label. It is a statement about which parts of the system are real in the test and which are replaced.
Figure 1. The same stack, entered at three different heights. How to read this: each test enters the stack at a different box. The unit test calls the service with a fake store; the slice test sends HTTP to the controller with a stub service; the integration test sends HTTP and lets every box behind the controller run for real.
Level 1: the unit test
The Spring Framework reference says the POJOs that make up an application "should be testable in JUnit or TestNG tests, with objects instantiated by using the new operator, without Spring or any other container", and that true unit tests "typically run extremely quickly, as there is no runtime infrastructure to set up". It also suggests testing service-layer objects by stubbing or mocking repository interfaces.
The lab's price rule is a pure function. The discount is applied once to the whole line and rounded half up:
@Component
public class CouponPricing implements Pricing {
@Override
public long totalCents(int unitPriceCents, int quantity, int couponPercent) {
long subtotal = (long) unitPriceCents * quantity;
return (subtotal * (100 - couponPercent) + 50) / 100;
}
}
Two units at 105 cents with a 10% coupon come to 189 cents. A unit test needs only new CouponPricing(). The OrderService in the lab is tested the same way, with a hand-written fake in place of the database:
final class InMemoryStockStore implements StockStore {
private final Map<String, Integer> stock;
InMemoryStockStore(Map<String, Integer> initial) {
this.stock = new HashMap<>(initial);
}
@Override
public boolean reserve(String sku, int quantity) {
int onHand = onHand(sku);
if (onHand < quantity) {
return false;
}
stock.put(sku, onHand - quantity);
return true;
}
@Override
public int onHand(String sku) {
return stock.getOrDefault(sku, -1);
}
}
A fake is a lightweight working implementation of the same interface. It lets the service run without a database, and it shares a weakness the failure example exposes: it tests your understanding of the dependency, not the dependency.
Level 2: the web slice test
The slice question is "does the HTTP layer behave?": the URL maps to the method, the body is validated, an exception becomes the right status, the JSON has the right shape. None of that needs a real service. Spring Boot's @WebMvcTest "auto-configures the Spring MVC infrastructure and limits scanned beans" to controllers, controller advice, filters and similar web components; regular @Component beans are not scanned. Each slice "restricts component scan to appropriate components and loads a very restricted set of auto-configuration classes".
In the lab the service behind the controller is a Mockito mock, defined with @MockitoBean, the Spring Framework annotation that defines a Mockito mock for a bean in the context:
@WebMvcTest(OrdersController.class)
class OrdersWebSliceTest {
@Autowired
MockMvc mvc;
@MockitoBean
OrderPlacing orders;
A lighter MockMvc exists too. The Spring Framework reference describes a standalone setup where you "point directly to the controllers you want to test and programmatically configure Spring MVC infrastructure". It calls this "a little closer to a unit test" and says it "does imply the need for additional integration tests to verify your Spring MVC configuration". The lab's defect matrix uses it so that it can swap in controller variants.
Level 3: the integration test
The integration test lets the real components run together. By default @SpringBootTest "will not start a server": its MOCK web environment loads a web ApplicationContext with a mock servlet environment, and @AutoConfigureMockMvc adds a MockMvc for it. The Spring Framework reference lists the goals of this kind of test: context caching, dependency injection of fixtures, and transaction management, and notes that such tests are "slower to run than unit tests but much faster than the equivalent Selenium tests or remote tests that rely on deployment to an application server".
@SpringBootTest
@AutoConfigureMockMvc
class OrdersIntegrationTest {
@Autowired
MockMvc mvc;
@Autowired
JdbcClient jdbc;
The expensive part is the context. The Spring test framework caches application contexts, so tests that share a configuration load it once per suite; the cache holds 32 contexts by default and evicts the least recently used. Every distinct combination of profiles, properties or mock beans is a separate key, so a suite that scatters different @MockitoBean declarations pays for many context starts.
The database in the lab is H2 in memory, named as such wherever it matters. Spring Boot's JDBC and Data JDBC slices configure an in-memory embedded database by default, and @AutoConfigureTestDatabase(replace = Replace.NONE) switches a slice to a real one. What an in-memory stand-in can and cannot prove is the next lesson's subject.
The shape: many cheap, few expensive
Martin Fowler's practical test pyramid article credits Mike Cohn with the original pyramid of unit, service and UI tests, and says the layer names matter less than the shape: lots of fast unit tests, some coarser tests, very few end-to-end tests. Its rules of thumb are worth keeping in the form it states them: "Push your tests as far down the test pyramid as you can", and if a higher-level test finds a bug that no lower-level test caught, "write a lower-level test". It warns against the inverted shape, the "test ice-cream cone", in which the slow top layers outweigh the base.
Figure 2. Choose the lowest level that can still see the rule. How to read this: start at the top and take the first "yes". The last branch is the expensive one and the rarest.
The front-end version of this argument has a different shape; see The Testing Pyramid and Trophy. On the back end the pyramid holds because the cheap levels are very cheap and the SQL, the one thing they cannot see, is a small surface.
Build it: three defects, three levels
This is the realistic example you can run. The lab is a small ShopStream order endpoint (POST /v1/orders) with a pricing rule, a stock table and a controller. It runs the same three levels of checks against correct code and against three planted defects, and prints which level notices which.
Goal. See that a defect is visible only to levels that exercise the part of the system where it lives.
Setup. From the repository's examples/spring-labs folder:
./gradlew :labs:testing-pyramid:test
The task runs the three real suites (UnitLevelTest, OrdersWebSliceTest, OrdersIntegrationTest), a test that pins the matrix and a golden-file comparison. The code is in examples/spring-labs/labs/testing-pyramid/. The database is H2, in memory; no Docker is involved.
The defects are planted in test code, never in the application code:
- D1: the discount is truncated per unit instead of rounded once on the line.
- D2: a copy of the controller with
@Validand the201status removed. - D3: the stock update without its
and quantity >= ?guard:
@Override
public boolean reserve(String sku, int quantity) {
int rows = jdbc.sql("update stock set quantity = quantity - ? where sku = ? and quantity >= ?")
.params(quantity, sku, quantity)
.update();
return rows == 1;
}
Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, 2026-12-01):
The same three levels of checks, run against correct code and three planted defects.
pass = every check at that level passed; FAIL = a check caught the defect.
version unit slice integration
correct code pass pass pass
D1 discount truncated per unit FAIL pass FAIL
D2 controller: no @Valid, 200 not 201 pass FAIL FAIL
D3 SQL: stock guard missing pass pass FAIL
First failing check, per defect and level:
D1 discount truncated per unit | unit | 2 x 105 cents, 10% coupon, total: expected 189 but was 188
D1 discount truncated per unit | integration | 2 milk with a 10% coupon, body: expected {"sku":"milk-1l","quantity":2,"totalCents":189} but was {"sku":"milk-1l","quantity":2,"totalCents":188}
D2 controller: no @Valid, 200 not 201 | slice | a valid order, status: expected 201 but was 200
D2 controller: no @Valid, 200 not 201 | integration | 2 milk with a 10% coupon, status: expected 201 but was 200
D3 SQL: stock guard missing | integration | 9 units with 3 on hand, status: expected 409 but was 201
| Defect | Unit | Slice | Integration | Why |
|---|---|---|---|---|
| D1 rounding | caught | missed | caught | The slice stubs the service, so pricing never runs there. |
| D2 controller | missed | caught | caught | The unit test never touches HTTP. |
| D3 SQL guard | missed | missed | caught | The unit and slice levels use a fake or a stub; only the integration level runs the SQL. |
Break it. The matrix already does this with the planted copy UnguardedJdbcStockStore. To feel it in the real class, delete and quantity >= ? and its third parameter from JdbcStockStore, run the three suites and see which ones object, then restore the line and re-run the tests.
Stretch. Add a defect at the service layer, such as reserving stock after computing the total, and decide which level should catch it.
What the lab leaves out. Timing (not asserted, because it varies by machine), the real PostgreSQL, security and asynchronous flows.
The failure example: when a fake agrees with you
D3 is the lesson's real point. The in-memory fake in the unit suite has the guard, because the person who wrote it believed the SQL has it. The slice stubs everything below the controller. Both suites check the code against the author's belief about the repository. Only the level that runs the SQL checks the belief itself.
Figure 3. The unit test and production take different paths. How to read this: the top half is what the test exercised; the bottom half is what production runs. They share the service and nothing below it.
The cure is not to delete the unit tests. It is a small number of integration tests, one for each query whose correctness depends on its text: guards, constraints, uniqueness, transaction boundaries. The related lesson on Spring @Transactional shows another case where only a run against a database reveals the behaviour.
Trade-offs
| Level | What it can see | Cost | Blind spot | Wrong when |
|---|---|---|---|---|
| Unit | One rule or class | Milliseconds, no infrastructure | Wiring, HTTP, SQL | The rule is mostly about how components connect |
| Web slice | Mapping, validation, status codes, JSON shape | A restricted Spring context | Business rules behind the stub, SQL | You stub so much that nothing real is left |
| Integration | Layers together and the real SQL | A full context and a database; the context cache helps | Anything the stand-in database does differently from production | You use it to test pure logic that a unit test could check |
| End to end or contract | Several services | The slowest and most fragile | Cause of a failure is hard to locate | A lower level could see the same fault |
In practice: ShopStream's order service
This is the realistic example on the course's running example ShopStream; nothing in it describes a real company. The numbers below are illustrative.
This is a realistic scenario, not a case history.
The situation
The team's suite for the order service is mostly end-to-end tests that drive a deployed environment. A full run takes about 25 minutes (illustrative), a fifth of the runs fail for reasons unrelated to the change, and developers have started merging on a green re-run. Fowler's "ice-cream cone" is the shape of the problem.
Starting architecture
Figure 4. A pipeline ordered from cheap to expensive. How to read this: each stage runs only if the one before passed, so most failures are caught by the cheapest stage that can see them.
Options considered
| Option | Feedback speed | Where defects are found | Main risk |
|---|---|---|---|
| A. Keep the end-to-end suite | Slow | Late, far from the change | Flaky, merged on re-run |
| B. Rebuild as a pyramid | Fast for most changes | Close to the change | The SQL-dependent rules need a real-ish database |
| C. Only integration tests | Medium | At one level | Every rule pays for a context and a database |
The decision
Option B. Each end-to-end test is replaced by the lowest level that can see what it checked: pricing and stock rules become unit tests; status codes and validation become slice tests; one integration test per query whose text matters runs against a database; a handful of journeys stay end to end. When a higher-level test finds a bug, the team adds the lower-level test that should have found it first.
Rollout and verification
Move one area at a time, starting with the order endpoint. For each moved test, check that it still fails when the defect it was written for is planted, which is what the lab's matrix does in miniature. Track the share of failed runs that are not caused by the change, and the time from push to first failure.
The 2 a.m. failure
The page reads: stock is negative for several products after a deploy. A repository refactor dropped the quantity guard from one update, and the unit suite, which uses a fake store, stayed green (D3). Checks: compare stock rows below zero with the release time, and read the SQL of the changed repository. Mitigation: repair the stock and orders by hand and roll the release back. The lasting fix is the integration test that places an order for more units than are on hand and asserts a 409 and an unchanged stock row.
Architect's notes
- Test the rule at the cheapest level that can see it. Ask what the check needs to be real.
- A fake is a belief. Back each important fake with at least one test against the real dependency.
- Count contexts. Every new combination of mocks and properties creates a context cache entry; keep integration tests on a shared configuration.
- Keep end-to-end tests to journeys. A handful of "can a shopper buy" paths, not every rule.
- Turn bugs into low-level tests. When production finds a defect, write the smallest test that would have caught it.
Common mistakes
- Mocking everything and calling it an integration test. If every collaborator is a mock, nothing was integrated.
- Testing SQL with a fake. The guard clause is the logic; a map cannot test it.
- An inverted pyramid. Many slow tests and few fast ones leads to slow, flaky feedback.
- Checking one rule at every level. It costs three times and tells you nothing more.
- A different mock set per test class. Each combination starts a new context.
Key takeaways
- A test level is a choice of what is real: unit (nothing), slice (one layer), integration (several layers and the SQL).
- Put each check at the lowest level that can still see the thing it checks.
- A fake or stub verifies your belief about a dependency, not the dependency.
- Spring caches test contexts, so keep configurations shared.
- The lab shows three defects caught by three different levels: rounding by unit and integration, the controller by slice and integration, the SQL guard by integration only.
- Contract, load and asynchronous tests are separate tools for separate risks.
Practice exercises
Exercise 1 (20 min). From the captured matrix, explain why D1 is missed by the slice level and why D2 is missed by the unit level.
Exercise 2 (45 min). Add a defect D4 in which OrderService reserves stock after pricing and forgets to reserve at all. Predict which levels catch it, then run it.
Exercise 3 (1 hour). Take ShopStream's cart-total rule and write the same check at the unit and integration levels; compare the code you had to write and the run time.
Exercise 4 (2 hours). Draw your own service as a stack like Figure 1, mark which parts each of your current tests makes real, and list the boxes that no test ever runs for real.
Related reading
- The Testing Pyramid and Trophy: the front-end side of the same argument.
- Spring
@Transactional: a lab that only a database run can verify. - Problem Details error model: the error responses a web slice test should assert.
- Databases Basics: relational databases and what SQL tests depend on.
Later lessons in this module: integration testing with Testcontainers, contract testing with Pact and Spring Cloud Contract, and load, stress and soak testing.
Official documentation
- Spring Boot reference: Testing Spring Boot Applications.
- Spring Framework reference: Unit Testing.
- Spring Framework reference: Integration Testing.
- Spring Framework reference: MockMvc setup options.
- Spring Framework reference: Context caching.
- Martin Fowler: The Practical Test Pyramid.