Pruebas de integración en Spring

1. Información general

Las pruebas de integración juegan un papel importante en el ciclo de desarrollo de aplicaciones al verificar el comportamiento de un sistema de un extremo a otro.

En este artículo, veremos cómo podemos aprovechar el marco de prueba Spring MVC para escribir y ejecutar pruebas de integración que prueben controladores sin iniciar explícitamente un contenedor Servlet.

2. Preparación

Las siguientes dependencias de Maven son necesarias para ejecutar pruebas de integración como se describe en este artículo. En primer lugar, las últimas dependencias de prueba de JUnit y Spring:

 junit junit 4.12 test   org.springframework spring-test 4.3.2.RELEASE test  

Para una afirmación efectiva de los resultados, también usaremos Hamcrest y la ruta JSON:

 org.hamcrest hamcrest-library 1.3 test   com.jayway.jsonpath json-path 2.2.0 test 

3. Configuración de la prueba Spring MVC

Vamos a presentar ahora cómo configurar y ejecutar las pruebas habilitadas para Spring.

3.1. Habilitar Spring en pruebas

Primero, cualquier prueba habilitada para Spring se ejecutará con la ayuda de @RunWith (SpringJUnit4ClassRunner.class) ; el corredor es esencialmente el punto de entrada para comenzar a usar el marco de Spring Test.

También necesitamos las anotaciones @ContextConfiguration para cargar la configuración de contexto y arrancar el contexto que usará la prueba .

Echemos un vistazo:

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

Observe cómo, en @ContextConfiguration, proporcionamos la clase de configuración ApplicationConfig.class que carga la configuración que necesitamos para esta prueba en particular.

Usamos una clase de configuración de Java aquí para especificar la configuración de contexto; de manera similar, podemos usar la configuración basada en XML:

@ContextConfiguration(locations={""})

Finalmente, la prueba también está anotada con @ WebAppConfiguration , que cargará el contexto de la aplicación web.

De forma predeterminada, busca la aplicación web raíz en la ruta predeterminada src / main / webapp ; la ubicación se puede anular pasando el atributo de valor como:

@WebAppConfiguration(value = "")

3.2. El objeto WebApplicationContext

WebApplicationContext ( wac ) proporciona una configuración de aplicación web. Carga todos los beans y controladores de la aplicación en el contexto.

Ahora podremos conectar el contexto de la aplicación web directamente en la prueba:

@Autowired private WebApplicationContext wac;

3.3. Burlarse de los beans de contexto web

MockMvc proporciona soporte para las pruebas Spring MVC. Encapsula todos los beans de aplicación web y los pone a disposición para realizar pruebas.

Veamos cómo usarlo:

private MockMvc mockMvc; @Before public void setup() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); }

Necesitamos inicializar el objeto mockMvc en el método anotado @Before , para que no necesitemos inicializarlo dentro de cada prueba.

3.4. Verificar la configuración de la prueba

Para nuestro tutorial aquí, verifiquemos que estamos cargando el objeto WebApplicationContext ( wac ) correctamente. También verificaremos que se adjunta el servletContext correcto :

@Test public void givenWac_whenServletContext_thenItProvidesGreetController() { ServletContext servletContext = wac.getServletContext(); Assert.assertNotNull(servletContext); Assert.assertTrue(servletContext instanceof MockServletContext); Assert.assertNotNull(wac.getBean("greetController")); }

Tenga en cuenta que también estamos comprobando que existe un bean GreetController.java en el contexto web, lo que garantiza que los beans de primavera se carguen correctamente.

At this point, the setup of the integration test is done. 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 the few examples that show how to assert that the proper view name is resolved, or that the response body is as expected.

The following snippets use static imports from MockMvcRequestBuilders or MockMvcResultMatchers classes.

4.1. Verify View Name

Let's invoke the /homePage endpoint from our test as:

//localhost:8080/spring-mvc-test/

or

//localhost:8080/spring-mvc-test/homePage

Code Snippet:

@Test public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() { this.mockMvc.perform(get("/homePage")).andDo(print()) .andExpect(view().name("index")); }

Let's break that down:

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

4.2. Verify Response Body

We will invoke /greet endpoint from our test as:

//localhost:8080/spring-mvc-test/greet

Expected Output:

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

Code Snippet:

@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 i.e. 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 provide the requested value
  • andReturn()will return the MvcResult object which is used when we have to verify something which is not achievable by the library. You can see we have added assertEquals to match the content type of response that is extracted from the MvcResult object

4.3. Send GET Request With Path Variable

We will invoke /greetWithPathVariable/{name} endpoint from our test as:

//localhost:8080/spring-mvc-test/greetWithPathVariable/John

Expected Output:

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

Code Snippet:

@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 request as “/greetWithPathVariable/John“.

This becomes easier with respect to readability and knowing what are the parameters which 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 /greetWithQueryVariable?name={name} endpoint from our test as:

//localhost:8080/spring-mvc-test /greetWithQueryVariable?name=John%20Doe

Expected Output:

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

Code Snippet:

@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. It 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 will invoke /greetWithPost endpoint from our test as:

//localhost:8080/spring-mvc-test/greetWithPost

Expected Output:

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

Code Snippet:

@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. Path variables and Query Parameters can be set in a similar way we looked earlier, whereas Form Data can be set via param() method only similar to Query Parameter as:

//localhost:8080/spring-mvc-test/greetWithPostAndFormData

Form Data:

id=1;name=John%20Doe

Expected Output:

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

Code Snippet:

@Test public void givenGreetURIWithPostAndFormData_whenMockMVC_thenResponseOK() { this.mockMvc.perform(post("/greetWithPostAndFormData").param("id", "1") .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!!!")) .andExpect(jsonPath("$.id").value(1)); }

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 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:

@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT) public class GreetControllerRealIntegrationTest { @LocalServerPort private int port; @Before public void setUp() { RestAssured.port = port; } @Test public void givenGreetURI_whenSendingReq_thenVerifyResponse() { given().get("/greet") .then() .statusCode(200); } }

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 the MockMvc. Knowing those limitations can guide us to make an informed decision about how we're going to implement our tests.

Finalmente, la implementación de todos estos ejemplos y fragmentos de código está disponible en GitHub .