使用mocMvc书写测试用例
2021-03-20 19:26
标签:length mat 方法 code name exce return getc run 使用这种方法也可以书写测试用例,用来测试controller层的代码。 使用mocMvc书写测试用例 标签:length mat 方法 code name exce return getc run 原文地址:https://www.cnblogs.com/qingmuchuanqi48/p/12735060.html@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);
}
}