MockMvc編寫單測
阿新 • • 發佈:2020-08-23
目錄
MockMvc
注意點
1、通過spring上下文獲取mockmvc物件
@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
2、json處理
通過MockMvc傳送和接受請求都是json。
所以傳送請求的時候,需要將javabean轉json
.content(new ObjectMapper().writeValueAsString(person)).contentType(MediaType.APPLICATION_JSON))
在接受得到result後,也需用json串轉javabean。
Person person = new ObjectMapper().readValue(result.getResponse().getContentAsString(), Person.class);
code
待測試的controller
package com.lexiaoyao.mocktest.controller; import com.lexiaoyao.mocktest.model.Person; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("test") @Slf4j public class TestController { //通過正則限時id只能為數字 @GetMapping("/person/{id:\\d+}") public ResponseEntity getPerson(@PathVariable("id") Integer id) { return ResponseEntity.ok(new Person(id, "tom", 22)); } @PostMapping("/person") public ResponseEntity postPerson(@RequestBody Person person) { return ResponseEntity.ok(person); } }
測試類
@SpringBootTest @Slf4j class MocktestApplicationTests { private MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; //在junit5內用BeforeEach代替Before @BeforeEach public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void testGet() throws Exception { MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test/person/1") //設定以json方式傳輸 .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn(); //將MvcResult中的response轉為物件 Person person = new ObjectMapper().readValue(result.getResponse().getContentAsString(), Person.class); Assert.assertNotNull(person); Assert.assertEquals(person.getId(), Integer.valueOf(1)); } @Test public void testPost() throws Exception { Person person = new Person(10, "name", 2); MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/test/person") .content(new ObjectMapper().writeValueAsString(person)).contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn(); Person resultPerson = new ObjectMapper().readValue(result.getResponse().getContentAsString(), Person.class); Assert.assertNotNull(person); Assert.assertEquals(person.getId(), resultPerson.getId()); } }