liveBook · Manning

@AutoConfigureMockMvc

As explained in Testing Spring Boot Applications

@AutoConfigureMockMvc is a Spring Boot test annotation that configures MockMvc-based testing support in an application test context.

@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

How Testing Spring Boot Applications covers it

How deep it goes
Adds Mock MVC support and exposes MockMvcTester, while leaving request actions and response assertions to the test.
Examples
Demonstrates GET /, HTTP 200 verification, and checking rendered HTML for a Weather App heading.
What it assumes
Assumes a Spring Boot test application context configured from an @SpringBootApplication class.
What you can do after
Apply it via MockMvcTester to exercise application routes and verify HTTP responses without managing host or port details.
How it connects
Connects @SpringBootTest, MockMvcTester, @AutoConfigureWebMvc, @WebMvcTest, and @ImportAutoConfiguration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Testing Spring Boot Applications. The section links point to the parts of the book it draws on.