使用mocMvc书写测试用例
@SpringBootTest @RunWith(SpringRunner.class) public class BookControllerTest { @Autowired private WebApplicationContext moc; private MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(moc).build(); } @Test public void whenQuerySuccess() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/book") .param("name", "tom and jerry") .accept(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3)); } @Test public void whenGetInfoSuccess() throws Exception { String res = mockMvc.perform(MockMvcRequestBuilders.get("/book/1") .accept( MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("战争与和平")) .andReturn().getResponse().getContentAsString(); System.out.println(res); } }
使用这种方法也可以书写测试用例,用来测试controller层的代码。
本文来自博客园,作者:King-DA,转载请注明原文链接:https://www.cnblogs.com/qingmuchuanqi48/p/12735060.html