Sub topic 11
Full-stack tests with a random port and TestRestTemplate
This chapter assumes you can write a Spring Boot REST controller and a basic @SpringBootTest. It also assumes you know how slice tests such as @WebMvcTest work. A full-stack test sits at the top of the test pyramid. It starts the whole application, including the embedded web server, and calls it over real HTTP.
When a full-stack test is worth it
Slice tests check one layer at a time. They cannot catch problems in how the layers fit together. Examples are a missing bean, a filter that rewrites requests, a serialization setting that applies only in the running app, or a security rule that blocks a route. A full-stack test finds these problems because the application runs the way it does in production.
The cost is speed. Each distinct context takes seconds to start. Keep full-stack tests to a few important paths, such as startup, one happy path per feature, and security boundaries. Leave edge cases to unit and slice tests.
Starting a server on a random port
By default, @SpringBootTest uses a mock web environment with no real server. Set webEnvironment to RANDOM_PORT to start the embedded server on a free port. A fixed port can clash with another test run or a process already on the machine. A random port avoids that.
@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 test assumes spring-boot-starter-actuator is on the classpath, because /actuator/health comes from Actuator.
TestRestTemplate is a test-friendly HTTP client. When the test uses a web environment with a real server, Spring Boot registers it as a bean. It resolves relative URLs such as /actuator/health against the random port, so you never need to look up the port yourself.
Behaviour that differs from MockMvc
TestRestTemplate is built for assertions, not for production code. It differs from a normal RestTemplate in these ways:
- It does not throw an exception on 4xx and 5xx responses. You read the status code from the
ResponseEntityand assert on it. - It can send basic authentication credentials with
withBasicAuth(user, password). - It makes a real network call, so the test runs on a different thread from the server. A
@Transactionaltest method does not wrap the server's work in its transaction, and the test cannot roll back what the server committed.
The last point catches many people. Data created through the HTTP call stays in the database after the test. Clean it up explicitly, or use an isolated database per test class.
Reading the port directly
Sometimes you need the port itself, for example to build a URL for a different HTTP client. Inject it with @LocalServerPort:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class PortAwareTest {
@LocalServerPort
int port;
@Test
void portIsAssigned() {
assertThat(port).isGreaterThan(0);
}
}Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NoSuchBeanDefinitionException` for `TestRestTemplate` | The web environment is `MOCK` or `NONE` | Set `webEnvironment = RANDOM_PORT` |
| `/actuator/health` returns 404 | Actuator is not on the classpath | Add `spring-boot-starter-actuator` |
| Tests pass alone but fail together | Committed data from earlier tests | Clean up in `@AfterEach` |
| Request returns 401 | Spring Security protects the route | Use `withBasicAuth` or test with Security test support |
Exercise
A test class uses @SpringBootTest with its default settings and injects TestRestTemplate. The context fails to load with a missing bean error. What change fixes it, and why does it work?
Show answer
Set webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT. The default is a mock web environment with no real server, so no TestRestTemplate bean is registered. With a random port, the embedded server starts and the bean is available. It resolves relative URLs against the server's port.
Exercise
A full-stack test creates a greeting through a POST request. The test class is annotated @Transactional, but the greeting is still in the database when the next test starts. Why?
Show answer
The POST is handled on a server thread, which has its own transaction that commits. The test's transaction does not cover it, so the rollback does not remove the data. Delete the data in an @AfterEach method or use unique data per test.