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 JUnit 5 test. It also assumes you know what a Spring bean is and have read the earlier chapters on @SpringBootTest and test slices. Here you will start the whole application on a real HTTP port and call it like a client would.
Why run a real server
Slice tests such as @WebMvcTest call controllers through MockMvc. No servlet container starts, and no network socket opens. That is fast, but some behavior only exists in a running server:
- Servlet filters and their registration order.
- Serialization through the real
HttpMessageConverterchain, including content negotiation over actual headers. - Error pages and the
/errorhandling path. - Port binding, compression, and HTTP-level settings from
server.*properties. - Wiring between the web layer, services, and the database in a single request.
A full-stack test checks that these parts work together. It costs more than a slice test, so you write fewer of them and aim them at the paths that matter most.
Starting the server on a random port
@SpringBootTest has a webEnvironment attribute. It controls whether a server starts and on which port.
| Value | Server | Port | Typical use |
|---|---|---|---|
| `MOCK` (default) | Mock servlet environment, no real server | None | `MockMvc` tests with the full context |
| `RANDOM_PORT` | Real embedded server | A free port chosen at startup | HTTP tests, the usual choice |
| `DEFINED_PORT` | Real embedded server | `server.port` or 8080 | Rare, can collide with other processes |
| `NONE` | No web environment at all | None | Non-web beans, batch jobs |
Prefer RANDOM_PORT. A fixed port fails when another test run, a developer's local app, or a parallel CI job already holds it. A random port avoids that problem.
A first full-stack test
This test starts the application and calls the health endpoint over HTTP. It needs spring-boot-starter-actuator on the classpath, because /actuator/health comes from Actuator.
@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);
}
}When the test starts, Spring Boot launches the embedded server, such as Tomcat, on a free port. It then registers a TestRestTemplate bean that already knows that port. The relative URL /actuator/health is resolved against http://localhost:<port>, so you never write the port yourself.
The imports for this test come from org.springframework.boot.test.context.SpringBootTest, org.springframework.boot.resttestclient.TestRestTemplate (Spring Boot 4) or org.springframework.boot.test.web.client.TestRestTemplate (earlier versions), org.springframework.http, and org.assertj.core.api.Assertions. Check which package your Spring Boot version uses, because the class moved.
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 PortInfoTest {
@LocalServerPort
int port;
@Test
void portIsAssigned() {
assertThat(port).isGreaterThan(0);
}
}@LocalServerPort reads the local.server.port property, which the server sets after it binds. The value is only available once the context has started, so you cannot use it in a static initializer.
What TestRestTemplate does differently
TestRestTemplate wraps a RestTemplate and changes a few defaults to suit tests.
- It does not throw on 4xx and 5xx responses. You get the
ResponseEntityback and assert on the status code. A plainRestTemplatethrows an exception instead. - It resolves relative URLs against the running server's port.
- It can send HTTP basic credentials through
withBasicAuth(user, password). - It tolerates cookies and redirects in a way that makes assertions simpler.
The first point matters for negative tests. To check that a missing resource returns 404, you assert on the status, not on an exception:
@Test
void unknownGreetingReturnsNotFound() {
ResponseEntity<String> response =
restTemplate.getForEntity("/greetings/nobody", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}Sending requests with bodies
For POST requests, pass an object and let Jackson serialize it, then read the response into a type.
@Test
void createsGreeting() {
GreetingRequest request = new GreetingRequest("Grace", "Hello, Grace");
ResponseEntity<Greeting> response =
restTemplate.postForEntity("/greetings", request, Greeting.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().name()).isEqualTo("Grace");
}GreetingRequest and Greeting here stand for your own request and response types. Use the same classes the application uses, or small test-only records, as long as Jackson can read and write them.
How the pieces fit together
The test thread and the server run in separate threads. The test thread sends a real HTTP request, and a server thread handles it.
Because the server runs on another thread, a test-managed transaction does not cover it. This has a consequence covered next.
The transaction gotcha
In a MOCK environment, a @Transactional test method rolls back after the test, because the test and the request share a thread. With RANDOM_PORT, the request runs on a server thread. The test's transaction does not apply there, and the server commits its own changes.
This means:
- Data created by an HTTP call stays in the database after the test.
- Data you insert inside a
@Transactionaltest method may not be visible to the server, because it is not committed yet.
Put the database in a known state in a different way. Delete rows in @BeforeEach through a repository, or give each test unique data, such as a random name.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class GreetingCleanupTest {
@Autowired
TestRestTemplate restTemplate;
@Autowired
GreetingRepository repository;
@BeforeEach
void cleanDatabase() {
repository.deleteAll();
}
@Test
void returnsSavedGreeting() {
repository.save(new Greeting("Ada", "Hello, Ada"));
ResponseEntity<String> response =
restTemplate.getForEntity("/greetings/Ada", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}Here repository.save runs outside any test transaction, so it commits immediately and the server can see the row.
Combining with Testcontainers
A full-stack test is most trustworthy when it uses the same database engine as production. Combine RANDOM_PORT with a container and @ServiceConnection:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class GreetingApiContainerTest {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
@Autowired
TestRestTemplate restTemplate;
@Test
void healthEndpointIsUp() {
ResponseEntity<String> response = restTemplate.getForEntity("/actuator/health", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}The health response includes the database check when a DataSource exists, so a 200 here shows the application reached the container.
Common errors
NoSuchBeanDefinitionExceptionforTestRestTemplate. The test class lackswebEnvironment = RANDOM_PORT(orDEFINED_PORT), or, on Spring Boot 4, lacks@AutoConfigureTestRestTemplate. The bean is only registered when a real server runs.404for/actuator/health. Actuator is not on the classpath. Addspring-boot-starter-actuator.- A test passes alone and fails in the suite. Committed data from an earlier test is still in the database. Clean up in
@BeforeEach. Connection refusedon a fixed port. You usedDEFINED_PORTand something else holds the port. Switch toRANDOM_PORT.- Authentication returns
401. Spring Security is on the classpath and protects the endpoint. Send credentials withwithBasicAuth, or use the security test support covered in a later chapter.
Cost and placement in the suite
Each distinct combination of configuration starts its own application context, and a real server makes that heavier. Keep full-stack tests for end-to-end checks of important flows: create and read a resource, an error path, and a health check. Test field validation rules, JSON shapes, and edge-case branches in @WebMvcTest or unit tests, where a failure points to a smaller piece of code and runs faster.
Exercise
A @SpringBootTest(webEnvironment = RANDOM_PORT) test is annotated with @Transactional. It posts a new greeting through TestRestTemplate, and the next test finds that greeting still in the database. Why did the rollback not remove it, and how would you fix the suite?
Show answer
The HTTP request runs on a server thread, not on the test thread, so the transaction started by the test does not cover it. The server commits its own transaction. To fix it, remove the reliance on rollback: delete the rows in a @BeforeEach method with the repository (for example repository.deleteAll()), or give each test unique data so leftovers do not interfere.
Exercise
Your negative test calls restTemplate.getForEntity("/greetings/nobody", String.class) and you want to check for a 404. Do you need a try/catch or assertThrows? Explain.
Show answer
No. TestRestTemplate does not throw on 4xx or 5xx responses. It returns the ResponseEntity, so you assert that response.getStatusCode() equals HttpStatus.NOT_FOUND.