Ujian Integrasi pada Musim Bunga

1. Gambaran keseluruhan

Ujian integrasi memainkan peranan penting dalam kitaran pengembangan aplikasi dengan mengesahkan tingkah laku sistem hujung ke hujung.

Dalam artikel ini, kita akan melihat bagaimana kita dapat memanfaatkan kerangka ujian Spring MVC untuk menulis dan menjalankan ujian integrasi yang menguji pengawal tanpa memulakan wadah Servlet secara eksplisit.

2. Persiapan

Pergantungan Maven berikut diperlukan untuk menjalankan ujian integrasi seperti yang dijelaskan dalam artikel ini. Keutamaan ujian JUnit dan Spring terbaru dan terpenting:

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

Untuk penegasan hasil yang berkesan, kami juga akan menggunakan jalan Hamcrest dan JSON:

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

3. Konfigurasi Ujian MVC Spring

Sekarang mari kita memperkenalkan cara mengkonfigurasi dan menjalankan ujian yang membolehkan Spring.

3.1. Dayakan Spring dalam Ujian

Pertama, sebarang ujian yang diaktifkan oleh Spring akan dijalankan dengan bantuan @RunWith (SpringJUnit4ClassRunner.class) ; pelari pada dasarnya adalah titik permulaan untuk mula menggunakan rangka Spring Test.

Kami juga memerlukan anotasi @ContextConfiguration untuk memuat konfigurasi konteks dan bootstrap konteks yang akan digunakan ujian .

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 ujian ini.

Kami menggunakan kelas konfigurasi Java di sini untuk menentukan konfigurasi konteks; sama, kita boleh menggunakan konfigurasi berasaskan XML:

@ContextConfiguration(locations={""})

Akhirnya - ujian ini juga diberi penjelasan dengan @ WebAppConfiguration - yang akan memuatkan konteks aplikasi web.

Secara lalai, ia mencari aplikasi web root pada lalai lalai src / main / webapp ; lokasi boleh diganti dengan meneruskan atribut nilai sebagai:

@WebAppConfiguration(value = "")

3.2. The WebApplicationContext Objek

WebApplicationContext ( WAC ) menyediakan konfigurasi aplikasi web. Ia memuat semua kacang aplikasi dan pengawal ke dalam konteks.

Kami sekarang dapat memasukkan konteks aplikasi web ke dalam ujian:

@Autowired private WebApplicationContext wac;

3.3. Kacau Kontek Web Mengejek

MockMvc memberikan sokongan untuk ujian Spring MVC. Ini merangkumi semua kacang aplikasi web dan menjadikannya tersedia untuk diuji.

Mari lihat cara menggunakannya:

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

Kita perlu menginisialisasi objek mockMvc dalam kaedah @Sebelum dianotasi, sehingga kita tidak perlu menginisialisasi di dalam setiap ujian.

3.4. Sahkan Konfigurasi Ujian

Untuk tutorial kami di sini, mari kita benar-benar mengesahkan bahawa kita memuat objek WebApplicationContext ( wac ) dengan betul. Kami juga akan mengesahkan bahawa servletContext yang betul 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 bahawa kami juga memeriksa bahawa kami kacang GreetController.java ada dalam konteks web - yang memastikan kacang kacang dimuat dengan betul.

Pada ketika ini, persediaan ujian integrasi selesai. Mari lihat bagaimana kita dapat menguji kaedah sumber menggunakan objek MockMvc .

4. Menulis Ujian Integrasi

Di bahagian ini, kita akan membahas operasi asas yang tersedia melalui kerangka ujian.

Kami akan menunjukkan cara menghantar permintaan dengan pemboleh ubah dan parameter jalur. Juga, kita akan ikuti dengan beberapa contoh yang menunjukkan bagaimana menegaskan bahawa nama pandangan yang betul diselesaikan, atau bahawa badan tindak balas seperti yang diharapkan.

Coretan berikut menggunakan import statik dari kelas M ockMvcRequestBuilders atau MockMvcResultMatchers .

4.1. Sahkan Nama Paparan

Mari kita gunakan titik akhir / homePage dari ujian kami sebagai :

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

atau

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

Coretan Kod:

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

Mari kita memecahkannya:

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

Akhirnya, pelaksanaan semua contoh dan coretan kod ini terdapat di GitHub .