MockMvcTester exercises Spring Web MVC endpoints through a mock web stack, without starting an external web server. It can test responses that return HTML or JSON. The mock stack avoids starting Tomcat for tests that do not need server behavior. section 4.1 section 2.8
In a full-application test, combine @SpringBootTest with @AutoConfigureMockMvc and inject MockMvcTester using @Autowired. @SpringBootTest starts a test application from the @SpringBootApplication class; @AutoConfigureMockMvc makes the tester available. Requests specify a method and path rather than a host and port. Calling exchange() executes the request, and AssertJ assertions inspect the response. section 2.3
Listing 4.1 Basic MockMvcTester-based test
@SpringBootTest
@AutoConfigureMockMvc #1
class ApiTests {
@Autowired MockMvcTester mvc; #1
@Test
void indexPageHasSelectedCity() {
selectCity("Paris");
var response = mvc.get() #2
.uri("/") #3
.exchange(); #4
assertThat(response)
.hasStatus(HttpStatus.OK) #5
.bodyText().contains("Paris (France)"); #6
}
}
A focused test selects a city, sends GET /, then checks the status and rendered HTML with fluent assertions. section 4.1
Use the same request-and-assertion pattern for other endpoint behavior:
- For JSON, assert the status, compare a response with expected JSON, extract a value by JSON path, or convert JSON into Java objects for field-level assertions. section 4.1
- For a POST, set the URI, content type and request body before calling exchange(); then check the status and body. section 4.1
- For reusable request customization, pass a RequestPostProcessor with with(...), for example to add headers and cookies. section 4.1
MockMvcTester wraps MockMvc. MockMvc remains supported, but uses static request builders and matchers rather than MockMvcTester’s fluent, AssertJ-integrated API; existing tests need not be migrated. For server-specific behavior such as error dispatch or session handling, use a random-port @SpringBootTest with RestTestClient or WebTestClient instead. For testing HTML or JavaScript as a browser would, consider HtmlUnit or Selenium. WebFlux applications need a different testing tool. section 4.2.1 section 4.6 section 4.2
