虚拟请求匹配响应体(JSON)

如果我们Controller返回的响应体是JSON数据,该怎么用测试匹配响应体呢。

 @GetMapping
    public Book getById(){
        System.out.println("getById is running...");
        Book book=new Book();
        book.setId(1);
        book.setType("编程");
        book.setDescription("springboot");
        return book;

    }

测试

    @Test
    void testJson(@Autowired MockMvc mockMvc) throws Exception {

        MockHttpServletRequestBuilder builder=MockMvcRequestBuilders.get("/books");
        ResultActions actions = mockMvc.perform(builder);

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

        actions.andExpect(result);


    }

首先还是设置预期值用ContentResultMatchers的Json()方法设置预期值,然后用实际值和它相匹配。没有报错则匹配成功,报错则匹配失败。

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