Sub topic 1
What to test and at which level
Prerequisites
This chapter assumes you can:
- Write and run a JUnit-style unit test in Java.
- Build a small Spring Boot application with REST controllers and Spring Data JPA.
- Explain what a Spring bean is and how dependency injection wires beans together.
- Add a dependency in Maven or Gradle.
You do not need to know any Spring test annotations yet. Later chapters introduce them one at a time. This chapter gives you the decision framework those chapters rely on.
Why the level of a test matters
A Spring Boot application has code that is plain Java, such as a service that applies a discount. It also has code that only makes sense inside the framework, such as a controller that maps a URL to a method, or a repository whose queries run against a database.
You can test either kind in several ways. The choice of way is the test's level. The level decides three things:
- Speed. How long the test takes to run.
- Realism. How closely the test matches production behavior.
- Diagnosis. How easily a failure points to the broken line.
These pull against each other. A test that runs in milliseconds usually fakes most of the system. A test that uses the real system is slower and fails for more reasons. The goal is to pick the cheapest level that still gives reliable feedback for the code in front of you.
The three levels used in this tutorial
Unit tests
A unit test creates a class with new (or with Mockito), replaces its collaborators with mocks, and calls a method. No Spring context starts. The test runs in milliseconds.
Use unit tests for logic that does not depend on the framework: calculations, validation rules, branching, mapping between objects, and how a service reacts when a collaborator returns an empty result or throws.
A unit test cannot tell you whether annotations are correct. It will not notice a missing @RequestBody, a typo in a query method name, or a bean that Spring cannot wire.
Slice tests
A slice test starts a Spring application context, but only the part that one layer needs. @WebMvcTest loads controllers, JSON conversion, validation, and exception handlers. @DataJpaTest loads entities, repositories, and the JPA configuration. Everything else is left out.
Use slice tests to check behavior that exists only because of the framework: URL mapping, status codes, JSON shape, request validation, derived queries, and entity mappings.
A slice test starts in a second or two, which is slower than a unit test and much faster than loading everything. It does not prove that the layers work together. A controller slice test mocks the service, and a repository slice test never touches a controller.
Full-context tests
A full-context test uses @SpringBootTest to load the whole application. With a running server on a random port, you can send real HTTP requests through every layer to a real database.
Use these for a small number of end-to-end paths: a request that creates a record and reads it back, security configuration that spans several beans, or startup problems such as a missing property.
Full-context tests are the slowest and the most realistic. When one fails, the cause could be in any layer, so diagnosis takes longer.
Comparing the levels
| Level | Typical annotations | Spring context | Typical speed | Best for | Misses |
|---|---|---|---|---|---|
| Unit | `@ExtendWith(MockitoExtension.class)` | None | Milliseconds | Business logic, edge cases | Wiring, mappings, queries |
| Slice | `@WebMvcTest`, `@DataJpaTest` | Part of the application | Around a second | Layer behavior driven by annotations | Interaction between layers |
| Full context | `@SpringBootTest` | Entire application | Several seconds | Main end-to-end paths, configuration | Nothing by design, but hard to diagnose |
The speeds are rough. They depend on your machine and on how many beans your application has. What stays stable is the ordering: unit tests are cheapest, and full-context tests are the most expensive.
The test pyramid
The usual guidance is to write many cheap tests and few expensive ones. Drawn as a shape, this is a pyramid with unit tests as the wide base.
Two reasons support this shape.
- Cost accumulates. If a suite has 500 tests and each loads the full context, you wait for the slow level 500 times. If 400 of them are unit tests, the suite stays quick enough to run before every commit.
- Failures stay readable. A failing unit test names a method. A failing full-context test names a request that went wrong somewhere.
Some teams argue for a "honeycomb" or "trophy" shape, with more weight on integration tests, because microservices often have little logic and mostly glue code. That view has merit. Your service's actual shape should drive the decision. A service that mostly forwards data between a controller and a database has little for a unit test to check, so slice tests give more value.
Choosing a level for a piece of code
Ask what could be wrong with the code, then pick the cheapest test that can detect it.
- Does the risk lie in logic you wrote? Choose a unit test. Example: a method that decides whether a customer gets free shipping.
- Does the risk lie in how the framework interprets your annotations? Choose a slice test. Example: a
@GetMapping("/greetings/{name}")method returns the right status and body. - Does the risk lie in how two or more layers or real infrastructure interact? Choose a slice test with real infrastructure, or a full-context test. Example: a transaction rolls back across a service and a repository.
- Does the risk lie in how the whole application starts or is configured? Choose a full-context test. Example: the security filter chain protects the right paths.
The following diagram expresses the same decision.
A worked example
Suppose the application has a GreetingController, a GreetingService, and a GreetingRepository. Here is a reasonable split of tests.
| Code | Risk | Test |
|---|---|---|
| `GreetingService.greetingFor` | Returns the wrong text, or mishandles a missing greeting | Unit test with a mock repository |
| `GreetingController` | Wrong path, wrong status code, wrong body | `@WebMvcTest` with a mock service |
| `GreetingRepository.findByName` | Query method does not match the column | `@DataJpaTest` against a real database |
| Whole application | Beans do not wire, or a property is missing | One `@SpringBootTest` that calls an endpoint |
Notice that each test targets one risk. The service test does not check HTTP status codes, and the controller test does not check SQL. When something fails, the test name tells you where to look.
What not to test
More tests do not always mean better coverage of risk. Skip or reduce tests in these cases.
- Framework behavior. Spring already tests that
@GetMappingroutes requests. Test that your method returns the right result, not that Spring dispatches. - Trivial code. Getters, setters, and constructors that only assign fields rarely break.
- Mocks of mocks. If a test stubs every collaborator and then verifies the stubs were called, it checks the test's own setup. Assert on results where you can, and use
verifyonly for side effects that matter, such as sending an email. - Private methods. Test them through the public method that uses them. If a private method is complex enough to need its own test, consider moving it to its own class.
Common mistakes
- Using
@SpringBootTestby default. It works for everything, which is why it spreads. A suite built entirely from it is slow, and each failure is hard to diagnose. - Using only unit tests. A suite can pass while the application fails to start, because no test ever loaded a context.
- Testing the same thing at three levels. If a unit test, a slice test, and a full-context test all check the same discount rule, a rule change forces three edits. Check each rule at the lowest level that can see it.
- Sharing state between tests. Tests that depend on the order of execution or on leftover database rows fail unpredictably. Each test should set up its own data.
- Ignoring flaky tests. A test that fails sometimes teaches the team to ignore failures. Find the cause, or remove the test.
How this chapter fits the rest of the tutorial
The chapters that follow move up the pyramid and then back across it:
- Unit tests with JUnit 5, Mockito, and AssertJ come first, after a look at what
spring-boot-starter-testprovides. @SpringBootTestintroduces the full context, along with profiles, properties, and mock beans.- Slice tests,
@WebMvcTest, and@DataJpaTestshow how to load only one layer. Testcontainers gives the repository tests a real database. - Full-stack HTTP tests, secured endpoints, JSON and client slices, context caching, and suite practices close the tutorial.
Each chapter returns to the same question from this one: what is the cheapest test that gives reliable feedback here?
Exercise
A PriceCalculator service applies a 10 percent discount to orders over 100 and calls a TaxRepository to look up a tax rate. You want to check the discount boundary at exactly 100 and at 100.01. Which test level do you choose, and why? Then name which level you would use to check that TaxRepository.findByRegion returns the right row.
Show answer
Use a unit test for the discount boundary. The risk is in logic you wrote, it needs no framework, and a mock TaxRepository removes the database. The test runs in milliseconds and can cover many boundary values cheaply. For findByRegion, use a @DataJpaTest slice test, ideally against a real database through Testcontainers. The risk there is whether the query method and entity mapping match the database, and only a test that runs the query can show that.
Exercise
Your team has 300 tests, and every one uses @SpringBootTest. The suite takes twelve minutes, and developers have stopped running it locally. Describe two changes that would help, and explain what risk each change reduces.
Show answer
First, move logic-only tests, such as service rules, to unit tests with Mockito and no Spring context. This removes most of the startup cost because those tests run in milliseconds. Second, replace @SpringBootTest in controller and repository tests with @WebMvcTest and @DataJpaTest, which load only one layer. Keep a small number of @SpringBootTest tests for main end-to-end paths and configuration. Together these changes cut run time while keeping a check that the application wires and starts correctly.