Integration Testing in Spring Baeldung
Integration Testing in Spring | Baeldung
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:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.3</version>
<scope>test</scope>
</dependency>
For effective asserting of results, we're going to also use Hamcrest and JSON path:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.5.0</version>
<scope>test</scope>
</dependency>
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:
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { ApplicationConfig.class })
@WebAppConfiguration
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:
@ContextConfiguration(locations={""})
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:
@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 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();
Assert.assertNotNull(servletContext);
Assert.assertTrue(servletContext instanceof MockServletContext);
Assert.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, 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:
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();
Assert.assertEquals("application/json;charset=UTF-8",
mvcResult.getResponse().getContentType());
}
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:
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 as 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 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 contextand 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 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.