Pengujian Integrasi di Spring

1. Ikhtisar

Pengujian integrasi memainkan peran penting dalam siklus pengembangan aplikasi dengan memverifikasi perilaku ujung ke ujung suatu sistem.

Pada artikel ini, kita akan melihat bagaimana kita dapat memanfaatkan kerangka kerja uji MVC Spring untuk menulis dan menjalankan uji integrasi yang menguji pengontrol tanpa secara eksplisit memulai penampung Servlet.

2. Persiapan

Dependensi Maven berikut ini diperlukan untuk menjalankan pengujian integrasi seperti yang dijelaskan di artikel ini. Pertama dan terpenting, dependensi pengujian JUnit dan Spring terbaru:

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

Untuk menegaskan hasil secara efektif, kami juga akan menggunakan jalur Hamcrest dan JSON:

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

3. Konfigurasi Uji MVC Musim Semi

Sekarang mari kita perkenalkan cara mengonfigurasi dan menjalankan pengujian yang diaktifkan Spring.

3.1. Aktifkan Spring in Tests

Pertama, semua pengujian yang mendukung Spring akan berjalan dengan bantuan @RunWith (SpringJUnit4ClassRunner.class) ; pelari pada dasarnya adalah titik masuk untuk mulai menggunakan framework Uji Musim Semi.

Kita juga membutuhkan anotasi @ContextConfiguration untuk memuat konfigurasi konteks dan mem-bootstrap konteks yang akan digunakan pengujian .

Mari kita lihat:

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

Perhatikan bagaimana, dalam @ContextConfiguration, kami menyediakan kelas konfigurasi ApplicationConfig.class yang memuat konfigurasi yang kami perlukan untuk pengujian khusus ini.

Kami menggunakan kelas konfigurasi Java di sini untuk menentukan konfigurasi konteks; Demikian pula, kita dapat menggunakan konfigurasi berbasis XML:

@ContextConfiguration(locations={""})

Terakhir - pengujian juga dianotasi dengan @ WebAppConfiguration - yang akan memuat konteks aplikasi web.

Secara default, ini mencari aplikasi web root di jalur default src / main / webapp ; lokasi dapat diganti dengan meneruskan atribut value sebagai:

@WebAppConfiguration(value = "")

3.2. The WebApplicationContext Obyek

WebApplicationContext ( wac ) menyediakan konfigurasi aplikasi web. Itu memuat semua kacang aplikasi dan pengontrol ke dalam konteks.

Kami sekarang akan dapat menghubungkan konteks aplikasi web langsung ke dalam pengujian:

@Autowired private WebApplicationContext wac;

3.3. Mengejek Kacang Konteks Web

MockMvc menyediakan dukungan untuk pengujian MVC Spring. Ini merangkum semua kacang aplikasi web dan membuatnya tersedia untuk pengujian.

Mari kita lihat bagaimana cara menggunakannya:

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

Kita perlu menginisialisasi objek mockMvc dalam metode anotasi @Before , sehingga kita tidak perlu menginisialisasi di dalam setiap pengujian.

3.4. Verifikasi Konfigurasi Uji

Untuk tutorial kita di sini, mari kita verifikasi bahwa kita memuat objek WebApplicationContext ( wac ) dengan benar. Kami juga akan memverifikasi bahwa servletContext yang tepat sedang dilampirkan:

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

Perhatikan bahwa kami juga memeriksa bahwa kami kacang GreetController.java ada dalam konteks web - yang memastikan bahwa kacang pegas dimuat dengan benar.

Pada titik ini, penyiapan uji integrasi selesai. Mari kita lihat bagaimana kita dapat menguji metode sumber daya menggunakan objek MockMvc .

4. Menulis Tes Integrasi

Di bagian ini, kita akan membahas operasi dasar yang tersedia melalui kerangka pengujian.

Kami akan menunjukkan cara mengirim permintaan dengan variabel dan parameter jalur. Selain itu, kami akan mengikuti dengan beberapa contoh yang menunjukkan cara menegaskan bahwa nama tampilan yang tepat telah diselesaikan, atau bahwa isi respons seperti yang diharapkan.

Cuplikan berikut menggunakan impor statis dari kelas M ockMvcRequestBuilders atau MockMvcResultMatchers .

4.1. Verifikasi Nama Tampilan

Mari panggil endpoint / homePage dari pengujian kita sebagai :

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

atau

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

Cuplikan Kode:

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

Mari kita hancurkan:

  • 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.

Terakhir, implementasi semua contoh dan cuplikan kode ini tersedia di GitHub .