A web server accepts network requests and returns HTTP responses, serving static resources or application-generated content. In Spring Boot tests, a full embedded server is distinct from the lightweight mock web stack. section 4.3 section 4.6
The server supplies behavior that mocks do not reproduce, including servlet-container exception handling, error-page rendering, session handling, and server-specific components such as custom Tomcat valves. section 4.3
Configure the test environment according to the behavior under test:
- Use MOCK for the default mock server, NONE for non-web applications, RANDOM_PORT for an embedded server on an available port, or DEFINED_PORT for a configured port. section 4.3
- Prefer RANDOM_PORT with RestTestClient or WebTestClient when testing server behavior; retain MockMvcTester for most API tests. section 4.6
- Use HtmlUnit or Selenium when HTML or JavaScript behavior requires browser-oriented testing rather than only HTTP exchange testing. section 4.6
Testing a custom 404 page
A mock request to /does-not-exist can verify the 404 status but returns no rendered error-page body. Starting the embedded server with @SpringBootTest(webEnvironment = RANDOM_PORT) and issuing the request through RestTestClient verifies the custom HTML response. section 4.3
Listing 4.15 Full web server tests
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient #1
class FullServerTests {
@Autowired
RestTestClient testClient; #2
@Test
void displaysCustom404Page() {
var responseSpec = testClient.get()
.uri("/does-not-exist") #3
.accept(MediaType.TEXT_HTML)
.exchange();
var response = RestTestClientResponse.from(responseSpec);
assertThat(response).hasStatus(HttpStatus.NOT_FOUND)
.bodyText()
.containsIgnoringCase("404 NOT FOUND")
.containsIgnoringCase("This is not the page you are looking for");
}
}
Shows the complete RANDOM_PORT test setup, RestTestClient request, and assertions against the rendered 404 page. section 4.3
