@AutoConfigureMockMvc adds Mock MVC testing support to a Spring Boot test context and makes a MockMvcTester bean available for issuing HTTP requests against the test application. section 2.3 section 5.7.1
Use the annotation according to the context being tested:
- Pair it with @SpringBootTest when testing requests against a test application started from the main @SpringBootApplication configuration. section 2.3
- Use it in web-focused test slices with @AutoConfigureWebMvc so the context loads web infrastructure without unrelated autoconfiguration. section 5.7.1
- Send requests through MockMvcTester without specifying the application host or port, then assert the response using its fluent API. section 2.3
Testing the index page
@SpringBootTest @AutoConfigureMockMvc class ExampleTests { @Autowired MockMvcTester mvc; @Test void indexPageLoads() { var response = mvc.get().uri("/").exchange(); assertThat(response) .hasStatus(HttpStatus.OK) .bodyText() .contains("<h1>Weather App</h1>"); } } section 2.3
Listing 2.2 Verifying that the application responds to HTTP queries.
@SpringBootTest #1
@AutoConfigureMockMvc #2
class ExampleTests {
@Autowired #2
private MockMvcTester mvc; #2
@Test
void indexPageLoads() {
// 1. Arrange
// We do not need to set up anything in particular
// 2. Act
var response = mvc.get() #3
.uri("/")
.exchange();
// 3. Assert
assertThat(response) #4
.hasStatus(HttpStatus.OK)
.bodyText()
.contains("<h1>Weather App</h1>");
}
}
Inspect the complete annotated test listing, including Arrange/Act/Assert comments and the MockMvcTester request. section 2.3
