Sub topic 4
Loading the context with @SpringBootTest
This chapter assumes you can write a Spring Boot application with REST controllers and Spring Data JPA, and that you know how beans and dependency injection work. It also assumes you have written JUnit 5 tests and have spring-boot-starter-test on the test classpath. The examples use Spring Boot 3.x and JUnit 5.
What @SpringBootTest does
A plain unit test creates objects with new or Mockito. @SpringBootTest instead starts a real Spring ApplicationContext for the test, using the same machinery as SpringApplication.run. That includes component scanning, auto-configuration, and application.properties loading. Beans from your application are then available through @Autowired.
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class GreetingWiringTest {
@Autowired
GreetingService service;
@Test
void serviceIsWiredByTheContainer() {
assertThat(service).isNotNull();
}
}This test is trivial, but it proves something a unit test cannot. Your configuration is valid, every required bean can be created, and the dependency graph resolves. A missing bean, a bad property binding, or a failing @PostConstruct method makes the context fail to start, and every test that uses it fails.
The annotation does the following when the test class is run:
- It locates a
@SpringBootConfigurationclass, usually the one annotated with@SpringBootApplication. - It builds a context from that class with
SpringApplication, applying properties, profiles, and any@TestConfigurationclasses. - It stores the context in a cache keyed by its configuration.
- It injects the context's beans into the test instance's fields.
The cache is covered in detail in a later chapter. For now, note that building a context is the expensive step, and the test framework avoids repeating it when it can.
How the configuration class is found
If you do not name a configuration class, Spring Boot searches for one. It starts in the test class's package and moves up through parent packages until it finds a class annotated with @SpringBootConfiguration. This is why test classes normally mirror the package structure of the main code.
If the search fails, you see Unable to find a @SpringBootConfiguration. There are two fixes. Move the test into the application's package tree, or name the class explicitly:
@SpringBootTest(classes = DemoApplication.class)
class ExplicitConfigurationTest {
// ...
}Naming classes also lets you load a smaller configuration than the full application. This is useful when you want a few beans rather than everything.
Choosing a web environment
The webEnvironment attribute controls whether a web server starts.
| Mode | Server started? | Typical use |
|---|---|---|
| `MOCK` (default) | No. A mock servlet environment is used. | Calling beans directly, or using `MockMvc` through `@AutoConfigureMockMvc` |
| `RANDOM_PORT` | Yes, on a free port | HTTP calls with `TestRestTemplate`, `WebTestClient`, or a real client |
| `DEFINED_PORT` | Yes, on `server.port` | Rare. Fails if another process holds the port. |
| `NONE` | No web environment at all | Batch jobs, messaging, or non-web applications |
RANDOM_PORT is the safe choice for tests that need a real server. Two test classes can run at the same time, or a developer can have the application open locally, without a port conflict. DEFINED_PORT is a common cause of tests that pass alone and fail in CI.
Full-stack tests over HTTP
With RANDOM_PORT, the embedded server starts and the test sends real HTTP requests. TestRestTemplate is registered as a bean, and it resolves relative URLs against the chosen port.
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@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);
}
}This example assumes spring-boot-starter-actuator is on the classpath. Without it, /actuator/health returns 404. In Spring Boot 4, TestRestTemplate moved to a separate module and needs an extra annotation, so check the migration notes if you upgrade.
If you need the port itself, for example to build a URL for a different client, inject it:
@LocalServerPort
int port;Unlike a unit test, this request travels through the whole stack: servlet filters, security, serialization, controller, service, repository, and database. A failure can come from any layer, so diagnosing it takes more effort. Keep these tests for a few end-to-end paths and use cheaper tests for detail.
Using MockMvc in a full context
If you want the full context but not a real server, keep the default MOCK mode and add @AutoConfigureMockMvc. The request goes through the DispatcherServlet and filter chain in the same thread, with no network.
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class GreetingEndpointTest {
@Autowired
MockMvc mockMvc;
@Test
void returnsGreetingFromRealBeans() throws Exception {
mockMvc.perform(get("/greetings/Ada"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Ada"));
}
}The test expects a greeting for "Ada" to exist in the database. All beans are real here, unlike in @WebMvcTest, where collaborators are mocked. This is slower, but it also catches wiring mistakes between layers.
Transactions and test threads
Putting @Transactional on a test class makes Spring Test start a transaction before each test method and roll it back afterward. This keeps the database clean without cleanup code. It works with MOCK mode because the test and the code under test run on the same thread, so they share the transaction.
With RANDOM_PORT or DEFINED_PORT, the server handles requests on its own threads. Your test's transaction does not cover them. Data created by the server is committed, and @Transactional on the test does not roll it back.
Passing properties to a single test class
You can override properties for one test class directly in the annotation:
@SpringBootTest(properties = {
"greeting.default-name=Test",
"spring.main.lazy-initialization=true"
})
class CustomPropertiesTest {
// ...
}These values take precedence over application.properties. Profiles, test property files, and @TestConfiguration are covered in the next chapter, so use inline properties only for small, local overrides.
Any change to properties, classes, active profiles, or similar settings produces a different context configuration. The cache then builds a separate context for that class.
Common errors
- The context fails to start. The root cause is at the bottom of a long stack trace, after "Caused by". Typical causes are a missing bean, a datasource that is not reachable, or a required property that is not set in the test environment.
- Every test that uses the failing context fails. Spring caches the failure, so a broken context shows up as many red tests. Fix the first one.
- A bean cannot be found. The configuration class may sit in a different package branch than the beans, or
classesnames a smaller configuration than you expected. @SpringBootTestis used for everything. Each distinct context costs seconds of startup. A service with simple logic needs a unit test, not a context.
Exercise
A test class is annotated with @SpringBootTest(webEnvironment = RANDOM_PORT) and @Transactional. It posts a new greeting through TestRestTemplate, and a second test later finds the greeting still in the database. Why did the rollback not happen, and what should you do?
Show answer
The server processes the request on its own thread, outside the transaction that Spring Test opened for the test method. The server's work was committed independently, so the test's rollback never covered it. Delete the data explicitly in an @AfterEach method, use unique data per test, or switch to the default MOCK web environment with @AutoConfigureMockMvc, where the test and the code under test share one thread and one transaction.
Exercise
Your test class is in the package com.example.tests, while the application class is in com.example.demo. The test fails with "Unable to find a @SpringBootConfiguration". Give two ways to fix it.
Show answer
Move the test class into com.example.demo or a subpackage of it, so the upward package search reaches the application class. Alternatively, name the configuration explicitly with @SpringBootTest(classes = DemoApplication.class).