Spring Top

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:


1. Overview

Integration testing plays an important role in the application development cycle by verifying the end-to-end behavior of a system.

In this article, we'll see how we can leverage the Spring MVC test framework in order to write and run integration tests that test controllers without explicitly starting a Servlet container.

2. Preparation

Several Maven dependencies are required for running the integration tests we'll use in this article. First and foremost, we'll need the latest junit-jupiter-engine, junit-jupiter-api, and Spring test dependencies:


For effective asserting of results, we're going to also use Hamcrest and JSON path:


3. Spring MVC Test Configuration

Let's now introduce how to configure and run the Spring enabled tests.

3.1. Enable Spring in Tests with JUnit 5

JUnit 5 defines an extension interface through which classes can integrate with the JUnit test.

We can enable this extension by adding the @ExtendWith annotation to our test classes and specifying the extension class to load. To run the Spring test, we use SpringExtension.class.

We also need the @ContextConfiguration annotation to load the context configuration and bootstrap the context that our test will use.

Let's have a look:

@ContextConfiguration(classes = { ApplicationConfig.class })
public class GreetControllerIntegrationTest {

Notice how, in @ContextConfiguration, we provide the ApplicationConfig.class config class, which loads the configuration we need for this particular test.

We use a Java configuration class here to specify the context configuration. Similarly, we can use the XML-based configuration:


Finally, we also annotate the test with @WebAppConfiguration, which will load the web application context.

By default, it looks for the root web application at path src/main/webapp. We can override this location by simply passing the value attribute:

@WebAppConfiguration(value = "")

3.2. The WebApplicationContext Object

WebApplicationContext provides a web application configuration. It loads all the application beans and controllers into the context.

We'll now be able to wire the web application context right into the test:

private WebApplicationContext webApplicationContext;

3.3. Mocking Web Context Beans

MockMvc provides support for Spring MVC testing. It encapsulates all web application beans and makes them available for testing.

Let's see how to use it:

private MockMvc mockMvc;
public void setup() throws Exception {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();

We initialize the mockMvc object in the @BeforeEach annotated method so that we don't have to initialize it inside every test.

3.4. Verify Test Configuration

Let's verify that we're loading the WebApplicationContext object (webApplicationContext) properly. We'll also check that the right servletContext is being attached:

public void givenWac_whenServletContext_thenItProvidesGreetController() {
    ServletContext servletContext = webApplicationContext.getServletContext();
    Assert.assertTrue(servletContext instanceof MockServletContext);

Notice that we're also checking that a GreetController.java bean exists in the web context. This ensures that Spring beans are loaded properly. At this point, the setup of the integration test is done. Now, let's see how we can test resource methods using the MockMvc object.

4. Writing Integration Tests

In this section, we'll go over the basic operations available through the test framework.

We'll show how to send requests with path variables and parameters. Also, we'll follow with a few examples that show how to assert that the proper view name is resolved, or that the response body is as expected.

The snippets that are shown below use static imports from MockMvcRequestBuilders or MockMvcResultMatchers classes.

4.1. Verify View Name

We can invoke the /homePage endpoint from our test as:




First, let's see the test code:

public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() {

Let's break it down:

  • perform() method will call a GET request method, which returns the ResultActions. Using this result, we can have assertion expectations about the response, like its content, HTTP status, or header
  • andDo(print()) will print the request and response. This is helpful to get a detailed view in case of an error
  • andExpect() will expect the provided argument. In our case, we're expecting “index” to be returned via MockMvcResultMatchers.view()

4.2. Verify Response Body

We'll invoke the /greet endpoint from our test as:


The expected output will be:

    "id": 1,
    "message": "Hello World!!!"

Let's see the test code:

public void givenGreetURI_whenMockMVC_thenVerifyResponse() {
    MvcResult mvcResult = this.mockMvc.perform(get("/greet"))
      .andExpect(jsonPath("$.message").value("Hello World!!!"))

Let's see exactly what's going on:

  • andExpect(MockMvcResultMatchers.status().isOk()) will verify that response HTTP status is Ok (200). This ensures that the request was successfully executed
  • andExpect(MockMvcResultMatchers.jsonPath(“$.message”).value(“Hello World!!!”)) will verify that response content matches with the argument “Hello World!!!“. Here, we used jsonPath, which extracts response content and provides the requested value
  • andReturn() will return the MvcResult object, which is used when we have to verify something that isn't directly achievable by the library. In this case, we've added assertEquals to match the content type of the response that is extracted from the MvcResult object

4.3. Send GET Request With Path Variable

We'll invoke the /greetWithPathVariable/{name} endpoint from our test as:


The expected output will be:

    "id": 1,
    "message": "Hello World John!!!"

Let's see the test code:

public void givenGreetURIWithPathVariable_whenMockMVC_thenResponseOK() {
      .perform(get("/greetWithPathVariable/{name}", "John"))
      .andExpect(jsonPath("$.message").value("Hello World John!!!"));

MockMvcRequestBuilders.get(“/greetWithPathVariable/{name}”, “John”) will send a request as “/greetWithPathVariable/John“.

This becomes easier with respect to readability and knowing what parameters are dynamically set in the URL. Note that we can pass as many path parameters as needed.

4.4. Send GET Request With Query Parameters

We'll invoke the /greetWithQueryVariable?name={name} endpoint from our test as:


In this case, the expected output will be:

    "id": 1,
    "message": "Hello World John Doe!!!"

Now, let's see the test code:

public void givenGreetURIWithQueryParameter_whenMockMVC_thenResponseOK() {
      .param("name", "John Doe")).andDo(print()).andExpect(status().isOk())
      .andExpect(jsonPath("$.message").value("Hello World John Doe!!!"));

param(“name”, “John Doe”) will append the query parameter in the GET request. This is similar to “/greetWithQueryVariable?name=John%20Doe“.

The query parameter can also be implemented using the URI template style:

  get("/greetWithQueryVariable?name={name}", "John Doe"));

4.5. Send POST Request

We'll invoke the /greetWithPost endpoint from our test as:


We should obtain as output:

    "id": 1,
    "message": "Hello World!!!"

And our test code is:

public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() {
      .andExpect(jsonPath("$.message").value("Hello World!!!"));

MockMvcRequestBuilders.post(“/greetWithPost”) will send the POST request. We can set path variables and query parameters in a similar way as before, whereas form data can be set only via the param() method, similar to query parameters as:


Then, the data will be:


So, we should get:

    "id": 1,
    "message": "Hello World John Doe!!!"

Let's see our test:

public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception {
    MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/greet"))
      .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!"))
   assertEquals("application/json;charset=UTF-8", mvcResult.getResponse().getContentType());

In the above code snippet, we've added two parameters: id as “1” and name as “John Doe”.

5. MockMvc Limitations

MockMvc provides an elegant and easy-to-use API to call web endpoints and to inspect and assert their response at the same time. Despite all its benefits, it has a few limitations.

First of all, it does use a subclass of the DispatcherServlet to handle test requests. To be more specific, the TestDispatcherServlet is responsible for calling controllers and performing all of the familiar Spring magic.

The MockMvc class wraps this TestDispatcherServlet internally. So, every time we send a request using the perform() method, MockMvc will use the underlying TestDispatcherServlet directly. Therefore, there are no real network connections made, and consequently, we won't test the whole network stack while using MockMvc.

Also, because Spring prepares a fake web application context to mock the HTTP requests and responses, it may not support all features of a full-blown Spring application.

For example, this mock setup does not support HTTP redirections. This may not seem that significant at first. However, Spring Boot handles some errors by redirecting the current request to the /error endpoint. So, if we're using the MockMvc, we may not be able to test some API failures.

As an alternative to MockMvc, we can set up a more real application context and then use RestTemplate or even REST-assured to test our application.

For instance, this is easy using Spring Boot:

@SpringBootTest(webEnvironment = DEFINED_PORT)
public class GreetControllerRealIntegrationTest {

    public void setUp() {
        RestAssured.port = DEFAULT_PORT;

    public void givenGreetURI_whenSendingReq_thenVerifyResponse() {

Here, we don't even need to add the @ExtendWith(SpringExtension.class).

This way, every test will make a real HTTP request to the application that listens on a random TCP port.

6. Conclusion

In this tutorial, we implemented a few simple Spring-enabled integration tests.

We also looked at the WebApplicationContext and MockMvc object creation, which played an important role in calling the endpoints of the application.

Looking further, we covered how we can send GET and POST requests with variations of parameter passing and how to verify the HTTP response status, header, and content.

As a closing remark, we did also evaluate some limitations of MockMvc. Knowing those limitations can guide us to make an informed decision about how we're going to implement our tests.

Finally, the implementation of all these examples and code snippets is available over on GitHub.

Spring bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Comments are closed on this article!