Package org.springframework.test.web.servlet.assertj

# 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 instances to include:

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

Simple, single-statement assertions can be done wrapping the request builder in `assertThat()` provides access to assertions. For instance:

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

For more complex scenarios the result of the exchange can be assigned in a variable to run multiple assertions:

     // perform a POST on /save and assert the response body is empty
     MvcTestResult result = mvc.post().uri("/save").exchange();
     assertThat(result).hasStatus(HttpStatus.CREATED);
     assertThat(result).body().isEmpty();

If the request is processing asynchronously, `exchange` waits for its completion, either using the default timeout or a given one. If you prefer to get the result of an asynchronous request immediately, use `asyncExchange`:

     // perform a POST on /save and assert an asynchronous request has started
     assertThat(mvc.post().uri("/save").asyncExchange()).request().hasAsyncStarted();

You can also perform requests using the static builders approach that `MockMvc` uses. For instance:

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

Use this approach if you have a custom `RequestBuilder` implementation that you'd like to integrate here. This approach is also invoking `MockMvc` without any additional processing of asynchronous requests.

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. Both resolved and unresolved exceptions are considered a failure that can be asserted as follows:

     // perform a GET on /boom and assert the message for the exception
     assertThat(mvc.get().uri("/boom")).hasFailed()
             .failure().hasMessage("Test exception");

Any attempt to access the result with an unresolved exception will throw an `AssertionError`:

     // throw an AssertionError with an unresolved exception
     assertThat(mvc.get().uri("/boom")).hasStatus5xxServerError();

`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

## Nested Class Summary

Nested Classes
Modifier and Type
Class
Description
`final class`
`MockMvcTester.MockMultipartMvcRequestBuilder`
A builder for `MockMultipartHttpServletRequest` that supports AssertJ.
`final class`
`MockMvcTester.MockMvcRequestBuilder`
A builder for `MockHttpServletRequest` that supports AssertJ.

## Method Summary

Modifier and Type
Method
Description
`static MockMvcTester`
`create(MockMvc mockMvc)`
Create an instance that delegates to the given `MockMvc` instance.
`MockMvcTester.MockMvcRequestBuilder`
`delete()`
Prepare an HTTP DELETE request.
`static MockMvcTester`
`from(org.springframework.web.context.WebApplicationContext applicationContext)`
Shortcut to create an instance using the given fully initialized (i.e., refreshed) `WebApplicationContext`.
`static MockMvcTester`
`from(org.springframework.web.context.WebApplicationContext applicationContext, Function<DefaultMockMvcBuilder,MockMvc> customizations)`
Create an instance using the given, fully initialized (i.e., refreshed) `WebApplicationContext`.
`MockMvcTester.MockMvcRequestBuilder`
`get()`
Prepare an HTTP GET request.
`MockMvcTester.MockMvcRequestBuilder`
`head()`
Prepare an HTTP HEAD request.
`MockMvcTester.MockMvcRequestBuilder`
`method(org.springframework.http.HttpMethod method)`
Prepare a request for the specified `HttpMethod`.
`static MockMvcTester`
`of(Object... controllers)`
Shortcut to create an instance by registering one or more `@Controller` instances.
`static MockMvcTester`
`of(Collection<?> controllers, Function<StandaloneMockMvcBuilder,MockMvc> customizations)`
Create an instance by registering one or more `@Controller` instances and configuring Spring MVC infrastructure programmatically.
`MockMvcTester.MockMvcRequestBuilder`
`options()`
Prepare an HTTP OPTIONS request.
`MockMvcTester.MockMvcRequestBuilder`
`patch()`
Prepare an HTTP PATCH request.
`MvcTestResult`
`perform(RequestBuilder requestBuilder)`
Perform a request using the given `RequestBuilder` and return a `result` that can be used with standard `AssertJ` assertions.
`MockMvcTester.MockMvcRequestBuilder`
`post()`
Prepare an HTTP POST request.
`MockMvcTester.MockMvcRequestBuilder`
`put()`
Prepare an HTTP PUT request.
`MockMvcTester`
`withHttpMessageConverters(Iterable<org.springframework.http.converter.HttpMessageConverter<?>> httpMessageConverters)`
Return a new instance using the specified message converters.

### Methods inherited from class java.lang.Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

## Method Details

### create

public static MockMvcTester create(MockMvc mockMvc)
Create an instance that delegates to the given `MockMvc` instance.

Parameters:
  `mockMvc` - the MockMvc instance to delegate calls to

### from

public static MockMvcTester from(org.springframework.web.context.WebApplicationContext applicationContext, Function<DefaultMockMvcBuilder,MockMvc> customizations)
Create an instance using the given, fully initialized (i.e., refreshed) `WebApplicationContext`. The given `customizations` are applied to the `DefaultMockMvcBuilder` that ultimately creates the underlying `MockMvc` instance.

If no further customization of the underlying `MockMvc` instance is required, use `from(WebApplicationContext)`.

Parameters:
  `applicationContext` - the application context to detect the Spring MVC infrastructure and application controllers from
  `customizations` - a function that creates a `MockMvc` instance based on a `DefaultMockMvcBuilder`
See Also:
  - `MockMvcBuilders.webAppContextSetup(WebApplicationContext)`

### from

public static MockMvcTester from(org.springframework.web.context.WebApplicationContext applicationContext)
Shortcut to create an instance using the given fully initialized (i.e., refreshed) `WebApplicationContext`.

Consider using `from(WebApplicationContext, Function)` if further customization of the underlying `MockMvc` instance is required.

Parameters:
  `applicationContext` - the application context to detect the Spring MVC infrastructure and application controllers from
See Also:
  - `MockMvcBuilders.webAppContextSetup(WebApplicationContext)`

### of

public static MockMvcTester of(Collection<?> controllers, Function<StandaloneMockMvcBuilder,MockMvc> customizations)
Create an instance by registering one or more `@Controller` instances and configuring Spring MVC infrastructure programmatically.

This allows full control over the instantiation and initialization of controllers and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.

Parameters:
  `controllers` - one or more `@Controller` instances or `@Controller` types to test; a type (`Class`) will be turned into an instance
  `customizations` - a function that creates a `MockMvc` instance based on a `StandaloneMockMvcBuilder`, typically to configure the Spring MVC infrastructure
See Also:
  - `MockMvcBuilders.standaloneSetup(Object...)`

### of

public static MockMvcTester of(Object... controllers)
Shortcut to create an instance by registering one or more `@Controller` instances.

The minimum infrastructure required by the `DispatcherServlet` to serve requests with annotated controllers is created. Consider using `of(Collection, Function)` if additional configuration of the MVC infrastructure is required.

Parameters:
  `controllers` - one or more `@Controller` instances or `@Controller` types to test; a type (`Class`) will be turned into an instance
See Also:
  - `MockMvcBuilders.standaloneSetup(Object...)`

### withHttpMessageConverters

public MockMvcTester withHttpMessageConverters(Iterable<org.springframework.http.converter.HttpMessageConverter<?>> httpMessageConverters)
Return a new instance using the specified message converters.

If none are specified, only basic assertions on the response body can be performed. Consider registering a suitable JSON converter for asserting against JSON data structures.

Parameters:
  `httpMessageConverters` - the message converters to use
Returns:
  a new instance using the specified converters

### get

public MockMvcTester.MockMvcRequestBuilder get()
Prepare an HTTP GET request.

The returned builder can be wrapped in `assertThat` to enable assertions on the result. For multi-statements assertions, use `exchange()` to assign the result. To control the time to wait for asynchronous request to complete on a per-request basis, use `exchange(Duration)`.

Returns:
  a request builder for specifying the target URI

### head

public MockMvcTester.MockMvcRequestBuilder head()
Prepare an HTTP HEAD request.

The returned builder can be wrapped in `assertThat` to enable assertions on the result. For multi-statements assertions, use `exchange()` to assign the result. To control the time to wait for asynchronous request to complete on a per-request basis, use `exchange(Duration)`.

Returns:
  a request builder for specifying the target URI

### post

public MockMvcTester.MockMvcRequestBuilder post()
Prepare an HTTP POST request.

The returned builder can be wrapped in `assertThat` to enable assertions on the result. For multi-statements assertions, use `exchange()` to assign the result. To control the time to wait for asynchronous request to complete on a per-request basis, use `exchange(Duration)`.

Returns:
  a request builder for specifying the target URI

### put

public MockMvcTester.MockMvcRequestBuilder put()
Prepare an HTTP PUT request.

The returned builder can be wrapped in `assertThat` to enable assertions on the result. For multi-statements assertions, use `exchange()` to assign the result. To control the time to wait for asynchronous request to complete on a per-request basis, use `exchange(Duration)`.

Returns:
  a request builder for specifying the target URI

### patch

public MockMvcTester.MockMvcRequestBuilder patch()
Prepare an HTTP PATCH request.

The returned builder can be wrapped in `assertThat` to enable assertions on the result. For multi-statements assertions, use `exchange()` to assign the result. To control the time to wait for asynchronous request to complete on a per-request basis, use `exchange(Duration)`.

Returns:
  a request builder for specifying the target URI

### delete

public MockMvcTester.MockMvcRequestBuilder delete()
Prepare an HTTP DELETE request.

The returned builder can be wrapped in `assertThat` to enable assertions on the result. For multi-statements assertions, use `exchange()` to assign the result. To control the time to wait for asynchronous request to complete on a per-request basis, use `exchange(Duration)`.

Returns:
  a request builder for specifying the target URI

### options

public MockMvcTester.MockMvcRequestBuilder options()
Prepare an HTTP OPTIONS request.

The returned builder can be wrapped in `assertThat` to enable assertions on the result. For multi-statements assertions, use `exchange()` to assign the result. To control the time to wait for asynchronous request to complete on a per-request basis, use `exchange(Duration)`.

Returns:
  a request builder for specifying the target URI

### method

public MockMvcTester.MockMvcRequestBuilder method(org.springframework.http.HttpMethod method)
Prepare a request for the specified `HttpMethod`.

The returned builder can be wrapped in `assertThat` to enable assertions on the result. For multi-statements assertions, use `exchange()` to assign the result. To control the time to wait for asynchronous request to complete on a per-request basis, use `exchange(Duration)`.

Returns:
  a request builder for specifying the target URI

### perform

public MvcTestResult perform(RequestBuilder requestBuilder)
Perform a request using the given `RequestBuilder` and return a `result` that can be used with standard `AssertJ` assertions.

Use only this method if you need to provide a custom `RequestBuilder`. For regular cases, users should initiate the configuration of the request using one of the methods available on this instance, for example, `get()` for HTTP GET.

Contrary to `MockMvc.perform(RequestBuilder)`, this does not throw an exception if the request fails with an unresolved exception. Rather, the result provides the exception, if any. Assuming that a `POST` request against `/boom` throws an `IllegalStateException`, the following asserts that the invocation has indeed failed with the expected error message:

    assertThat(mvc.post().uri("/boom")))
           .failure().isInstanceOf(IllegalStateException.class)
           .hasMessage("Expected");

Parameters:
  `requestBuilder` - used to prepare the request to execute
Returns:
  an `MvcTestResult` to be wrapped in `assertThat`
See Also:
  - `MockMvc.perform(RequestBuilder)`
  - `method(HttpMethod)`