虚拟请求匹配响应头

还是那个Controller

测试

    @Test
    void testHeader(@Autowired MockMvc mockMvc) throws Exception {
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
        ResultActions actions = mockMvc.perform(builder);

        HeaderResultMatchers header = MockMvcResultMatchers.header();

        ResultMatcher result = header.string("Content-Type", "application/json");

        actions.andExpect(result);


    }

还是设置预期值和真实值进行匹配,成功则通过,失败则报错。
我们的controller现在的响应体不是json的,所以现在运行会报错,因为你的期望值是json类型的。

如果响应体是json形式则通过


你也可以都测试一遍,测试状态码,响应头和响应体,一个一个进行匹配,匹配的越多越精准。

@Test
    void testAll(@Autowired MockMvc mockMvc) throws Exception {
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
        ResultActions actions = mockMvc.perform(builder);

        //1.定义本次调用的预期值
        StatusResultMatchers status = MockMvcResultMatchers.status();
        //2.isOk表示的是如果请求成功返回的状态码是200
        ResultMatcher ok = status.isOk();//状态码200
        //3.添加预计值到本次调用过程中进行匹配
        actions.andExpect(ok);



        HeaderResultMatchers header = MockMvcResultMatchers.header();

        ResultMatcher result = header.string("Content-Type", "application/json");

        actions.andExpect(result);

        ContentResultMatchers content = MockMvcResultMatchers.content();
        ResultMatcher result2 = content.json("{\"id\":1,\"type\":\"编程\",\"description\":\"springboot\"}");

        actions.andExpect(result2);





    }
posted @ 2022-05-16 09:27  长情c  阅读(40)  评论(0)    收藏  举报