使用MockMvcResultMatchers对返回值为List的接口进行断言

在使用MockMvc进行单元测试的时候,我们经常使用andExpect(MockMvcResultMatchers.jsonPath(jsonKeyName).isNotEmpty())
Controller返回的结果进行断言,用以验证返回结果的正确性。

但假如,后端返回的是无Key的Json时,如返回值为List<T>,此时返回的Json字符串格式为

[{
    "id":"100",
    "name":"Jack",
    "age":"18"
},
{
    "id":"101",
    "name":"Tom",
    "age":"21"
}]

jsonKeyName的选择让我犯了难,于是乎搜索一番,得到了答案,遂小记一番,避免遗忘:
此时我们可以使用如下表达式进行断言,假如我需要断言列表的第二个对象的id是否为101
andExpect(MockMvcResultMatchers.jsonPath($[1]).Value("101"))

完整的测试方法如下:

@Test
    public void testGetAll() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/person") //此处为Controller的请求路径
                .param("type", "student")  //添加一个值为student的请求参数type
                .andExpect(MockMvcResultMatchers.status().isOk()) //判断状态码是否为200
                .andDo(MockMvcResultHandlers.print()) //打印返回结果,便于信息校对
                .andExpect(MockMvcResultMatchers.jsonPath($[1]).Value("101")) //断言返回值的第二个对象的`id`是否为`101`
                .andReturn(); // 返回相应的MvcResult
    }
posted @ 2022-08-15 14:40  古宇  阅读(954)  评论(0编辑  收藏  举报

欢迎来刀