使用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层的代码。

posted @ 2020-04-19 23:31  King-DA  阅读(258)  评论(0编辑  收藏  举报