Sub topic 4
Loading the context with @SpringBootTest
This chapter assumes you can write JUnit 5 tests, understand Spring beans and dependency injection, and have a Spring Boot application with a controller, a service, and a repository.
What @SpringBootTest does
@SpringBootTest starts a real Spring ApplicationContext for your test. It finds your @SpringBootApplication class, runs auto-configuration, creates every bean, and injects the beans into your test class. Use it when the thing you want to verify is the wiring: that beans are created, that configuration binds, and that the layers work together.
It is the most expensive kind of test in the suite. Starting a context takes seconds, not milliseconds. If a plain unit test can answer your question, prefer that.
@SpringBootTest
class ApplicationContextTest {
@Autowired
GreetingService service;
@Test
void contextLoadsAndServiceIsWired() {
assertThat(service).isNotNull();
}
}If any bean fails to start, for example because of a missing property or an unsatisfied dependency, every test that uses this context fails with the startup exception.
How the application class is found
Without arguments, Spring Boot searches upward from the test's package until it finds a class annotated with @SpringBootApplication. Keep your test packages mirroring your main packages so this works. If the search fails, you get an error like Unable to find a @SpringBootConfiguration. Fix it by moving the test into a matching package or by naming the class with @SpringBootTest(classes = MyApplication.class).
Choosing a web environment
The webEnvironment attribute controls whether a server starts.
| Value | What happens | Typical use |
|---|---|---|
| `MOCK` (default) | Loads a web context but starts no server. `MockMvc` can be injected with `@AutoConfigureMockMvc`. | Wiring tests and mock-based web tests |
| `RANDOM_PORT` | Starts an embedded server on a free port. | HTTP calls with `TestRestTemplate` |
| `DEFINED_PORT` | Starts a server on the configured port. | Rarely. It can collide with other processes. |
| `NONE` | Loads a context with no web environment. | Batch jobs and non-web code |
Prefer RANDOM_PORT over DEFINED_PORT. A fixed port fails when a second test run, or another service on the machine, already uses it.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class GreetingApiTest {
@Autowired
TestRestTemplate restTemplate;
@Test
void healthEndpointIsUp() {
ResponseEntity<String> response = restTemplate.getForEntity("/actuator/health", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}TestRestTemplate resolves relative URLs against the random port. This example assumes spring-boot-starter-actuator is on the classpath.
Common errors
- Unable to find a @SpringBootConfiguration. The test package does not sit under the application's package. See above.
- Injection fails for
TestRestTemplateorMockMvc.TestRestTemplateneeds a server, so useRANDOM_PORT.MockMvcneeds@AutoConfigureMockMvcin a@SpringBootTest. - Tests pass alone and fail together. Tests share one context, and so they share its state, such as database rows and singleton beans. Clean up what you change.
- A suite that takes minutes. Each distinct context configuration starts a new context. A later chapter explains the cache that avoids this.
Exercise
A test uses @SpringBootTest with the default settings and injects TestRestTemplate, but it fails because no bean of that type exists. What is the cause, and what is the fix?
Show answer
The default webEnvironment is MOCK, which starts no server, so TestRestTemplate is not registered. Set webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT.