开发过程中,有时需要对接口进行小步迭代测试。这时候可以使用junit mockmvc来对controller进行测试,这样即使接口在后期需要修改时,可以快速进行测试。
首先上一个例子:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class IndexControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void xiaowanzi() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/xwz")).andExpect(MockMvcResultMatchers.status().isOk());
}
}
mockmvc 为一个虚拟的servlet
方法:
public ResultActions perform(RequestBuilder requestBuilder) throws java.lang.Exception
**perform(RequestBuilder requestBuilder)
Perform a request and return a type that allows chaining further actions, such as asserting expectations, on the result.**
ResultActions 有三个方法:
andDo(ResultHandler handler)
ResultActions andExpect(ResultMatcher matcher)
MvcResult andReturn()
举个栗子:使用andReturn() 获取返回responsebody的值
@RequestMapping(value = "mockTest")
@ResponseBody
public RestResponseBo mockTest(){
System.out.println("this is mock test ");
return RestResponseBo.fail(ErrorCode.BAD_REQUEST);
}
//方法对应test:
@Test
public void xiaowanzi() throws Exception {
MockHttpServletResponse response = mockMvc.perform(MockMvcRequestBuilders.get("/mockTest")).andReturn().getResponse();
System.out.println(response.getContentAsString());
}