@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层的代码。
原文:https://www.cnblogs.com/qingmuchuanqi48/p/12735060.html