Partner – Microsoft – NPI (cat= Spring)
announcement - icon

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

And, the Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

You can also ask questions and leave feedback on the Azure Spring Apps GitHub page.

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 tutorial, we’ll learn how to leverage the Spring MVC test framework to write and run integration tests that test controllers without explicitly starting a Servlet container.

2. Preparation

We’ll need several Maven dependencies to run 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:


3. Spring MVC Test Configuration

Now, let’s see 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’ll 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 that in @ContextConfiguration, we provided the ApplicationConfig.class config class, which loads the configuration we need for this particular test.

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


Finally, we’ll 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.

Now, we’ll 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’ll 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();
    assertTrue(servletContext instanceof MockServletContext);

Notice that we’re also checking that a 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, we’ll 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 look at how to send requests with path variables and parameters. We’ll also 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 the 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!!!"))
    assertEquals("application/json;charset=UTF-8", mvcResult.getResponse().getContentType());

Let’s see exactly what’s going on:

  • andExpect(MockMvcResultMatchers.status().isOk()) will verify that the response HTTP status is Ok (200). This ensures that the request is successfully executed.
  • andExpect(MockMvcResultMatchers.jsonPath(“$.message”).value(“Hello World!!!”)) will verify that the response content matches with the argument “Hello World!!!” Here, we used jsonPath, which extracts the 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 the output:

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

And our test code is:

public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() {
      .andExpect(jsonPath("$.message").value("Hello World!!!"));
}“/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 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, no real network connections are 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 the features of a full-blown Spring application.

For example, this mock setup doesn’t 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 article, we implemented a few simple Spring-enabled integration tests.

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

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

Then, we evaluated some limitations of MockMvc. Knowing these 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.

Course – LS (cat=Spring)

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

res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.