Master the most popular testing framework for Java, through the Learn JUnit course:
Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely โ and automatically โ with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatโs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions โ one for newcomers and one for experienced users. Youโll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
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:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>6.0.13</version>
<scope>test</scope>
</dependency>
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:
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { ApplicationConfig.class })
@WebAppConfiguration
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:
@ContextConfiguration(locations={""})
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:
@Autowired
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;
@BeforeEach
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:
@Test
public void givenWac_whenServletContext_thenItProvidesGreetController() {
ServletContext servletContext = webApplicationContext.getServletContext();
assertNotNull(servletContext);
assertTrue(servletContext instanceof MockServletContext);
assertNotNull(webApplicationContext.getBean("greetController"));
}
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, 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:
http://localhost:8080/spring-mvc-test/
or
http://localhost:8080/spring-mvc-test/homePage
First, letโs see the test code:
@Test
public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() {
this.mockMvc.perform(get("/homePage")).andDo(print())
.andExpect(view().name("index"));
}
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:
http://localhost:8080/spring-mvc-test/greet
The expected output will be:
{
"id": 1,
"message": "Hello World!!!"
}
Letโs see the test code:
@Test
public void givenGreetURI_whenMockMVC_thenVerifyResponse() {
MvcResult mvcResult = this.mockMvc.perform(get("/greet"))
.andDo(print()).andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Hello World!!!"))
.andReturn();
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:
http://localhost:8080/spring-mvc-test/greetWithPathVariable/John
The expected output will be:
{
"id": 1,
"message": "Hello World John!!!"
}
Letโs see the test code:
@Test
public void givenGreetURIWithPathVariable_whenMockMVC_thenResponseOK() {
this.mockMvc
.perform(get("/greetWithPathVariable/{name}", "John"))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.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:
http://localhost:8080/spring-mvc-test/greetWithQueryVariable?name=John%20Doe
In this case, the expected output will be:
{
"id": 1,
"message": "Hello World John Doe!!!"
}
Now, letโs see the test code:
@Test
public void givenGreetURIWithQueryParameter_whenMockMVC_thenResponseOK() {
this.mockMvc.perform(get("/greetWithQueryVariable")
.param("name", "John Doe")).andDo(print()).andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.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:
this.mockMvc.perform(
get("/greetWithQueryVariable?name={name}", "John Doe"));
4.5. Send POST Request
Weโll invoke the /greetWithPost endpoint from our test as:
http://localhost:8080/spring-mvc-test/greetWithPost
We should obtain the output:
{
"id": 1,
"message": "Hello World!!!"
}
And our test code is:
@Test
public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() {
this.mockMvc.perform(post("/greetWithPost")).andDo(print())
.andExpect(status().isOk()).andExpect(content()
.contentType("application/json;charset=UTF-8"))
.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:
http://localhost:8080/spring-mvc-test/greetWithPostAndFormData
Then the data will be:
id=1;name=John%20Doe
So we should get:
{
"id": 1,
"message": "Hello World John Doe!!!"
}
Letโs see our test:
@Test
public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception {
MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/greet"))
.andDo(print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!"))
.andReturn();
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 {
@Before
public void setUp() {
RestAssured.port = DEFAULT_PORT;
}
@Test
public void givenGreetURI_whenSendingReq_thenVerifyResponse() {
given().get("/greet")
.then()
.statusCode(200);
}
}
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.
