Kiểm thử (Mockito) trong Spring MVC
NỘI DUNG BÀI VIẾT
Thư viện
Kiểm thử tích hợp trong Spring MVC cũng yêu cầu một framework kiểm thử đơn vị, chẳng hạn JUnit, ngoài ra còn có thư viện Spring Tests để tích hợp unit test framework dễ dàng hơn.testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.2.0' testCompile group: 'org.junit.platform', name: 'junit-platform-commons', version: '1.2.0' testCompile group: 'org.junit.platform', name: 'junit-platform-launcher', version: '1.2.0' testCompile group: 'org.springframework', name: 'spring-test', version: '4.3.24.RELEASE' testCompile group: 'com.github.sbrannen', name: 'spring-test-junit5', version: '1.2.0'Khi kiểm thử tích hợp, để đảm bảo các thành phần của hệ thống được kiểm thử một cách cô lập, việc giả lập các thành phần phụ thuộc là cần thiết. Chẳng hạn, để test service thì giả lập repository, để test controller thì giả lập service. Việc này được thực hiện nhờ thư viện mock (giả tạo).
testCompile group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
Kích hoạt Spring Test
Khi sử dụng junit flatform, JUnit Framework đã có khả năng cấu hình compile, build và thực thi kiểm thử mà không cần chỉ định gì đặc thù.@WebAppConfiguration @SpringJUnitJupiterConfig(CustomerControllerTestConfig.class) public class CustomerControllerTest {Khi kiểm thử những thành phần tiếp xúc với http, sử dụng @WebApplicationConfiguration để nạp các đối tượng phụ thuộc cần thiết cho web. Sử dụng @SpringJUnitJupiterConfig để nạp các đối tượng phụ thuộc khác, tự định nghĩa, chẳng hạn:
@Configuration @ComponentScan("cg.wbd.grandemonstration") @EnableSpringDataWebSupport public class CustomerControllerTestConfig { @Bean public CustomerService customerService() { return Mockito.mock(CustomerServiceImplWithSpringData.class); } @Bean public ProvinceService provinceService() { return Mockito.mock(ProvinceServiceImplWithSpringData.class); } @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .setName("cms") .build(); } }
Giả tạo các đối tượng phụ thuộc của webapp
Thư viện MockMvc sẽ hỗ trợ cho kiểm thử Spring MVC. Nó bao gói các đối tượng phụ thuộc cần thiết của webapp.private MockMvc mockMvc; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders .standaloneSetup(customerController) .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver()) .build(); }
Viết kiểm thử tích hợp
Kiểm thử tên view
@Test public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() { this.mockMvc .perform(get("/homePage")) .andDo(print()) .andExpect(view().name("index")); }perform get sẽ giả lập gửi một request tới url chỉ định andDo print giúp in request và response tới luồng out, phục vụ debug expect view name xác nhận xem có đúng là view chỉ định được sử dụng không
Kiểm thử response body
@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()); }expect status isOk xác nhận rằng HTTP code của response là 200 expect json path xác nhận cấu trúc của body and return giúp trả về đối tượng mvcResult (để assert tiếp) câu lệnh assert equal đã được dùng để xác nhận header của response
Kiểm thử request get với param
Path param:@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!!!")); }Query param:
@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!!!")); }
Kiểm thử request post
@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!!!")); }
Leave a Reply