Class MockMvcTester

java.lang.Object
org.springframework.test.web.servlet.assertj.MockMvcTester

public final class MockMvcTester extends Object
MockMvcTester provides support for testing Spring MVC applications with MockMvc for server request handling using AssertJ.

A tester instance can be created from a WebApplicationContext:


 // Create an instance with default settings
 MockMvcTester mvc = MockMvcTester.from(applicationContext);

 // Create an instance with a custom Filter
 MockMvcTester mvc = MockMvcTester.from(applicationContext,
         builder -> builder.addFilters(filter).build());
 

A tester can be created in standalone mode by providing the controller(s) to include:


 // Create an instance for PersonController
 MockMvcTester mvc = MockMvcTester.of(new PersonController());
 

Once a tester instance is available, you can perform requests in a similar fashion as with MockMvc, and wrapping the result in assertThat() provides access to assertions. For instance:


 // perform a GET on /hi and assert the response body is equal to Hello
 assertThat(mvc.perform(get("/hi")))
         .hasStatusOk().hasBodyTextEqualTo("Hello");
 

One main difference between MockMvc and MockMvcTester is that an unresolved exception is not thrown directly when using MockMvcTester. Rather an MvcTestResult is available with an unresolved exception which allows you to assert that a request failed unexpectedly:


 // perform a GET on /boom and assert the message for the the unresolved exception
 assertThat(mvc.perform(get("/boom")))
         .hasUnresolvedException())
         .withMessage("Test exception");
 

MockMvcTester can be configured with a list of message converters to allow the response body to be deserialized, rather than asserting on the raw values.

Since:
6.2
Author:
Stephane Nicoll, Brian Clozel