jsonPath表达式期望值,但返回值列表

时间:2019-05-22 09:22:14

标签: regex spring unit-testing jsonpath

我要检查响应的“ class_type”值是否为“ REGION”。

我使用mockMvc测试springboot API。 MockHttpServletResponse就是这样。

sbrk()

这是整个响应对象。 让我们仔细看看,尤其是物品。

Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = 
{"result":true,
"code":200,
"desc":"OK",
"data":{"total_count":15567,
        "items": ... 
}}

我尝试使用jsonPath。

 "items": [
      {
        "id": ...,
        "class_type": "REGION",
        "region_type": "MULTI_CITY",
        "class": "com.model.Region",
        "code": "AE-65GQ6",
        ...

      },
      {
        "id": "...",
        "class_type": "REGION",
        "region_type": "CITY",
        "class": "com.model.Region",
        "code": "AE-AAN",
        ...

      },

但是

@When("User wants to get list of regions, query is {string} page is {int} pageSize is {int}")
    public void userWantsToGetListOfRegionsQueryIsPageIsPageSizeIs(String query, int page, int pageSize) throws Exception {
        mockMvc().perform(get("/api/v1/regions" ))
                .andExpect(status().is2xxSuccessful())
                .andDo(print())
                .andExpect(jsonPath("$.data", is(notNullValue())))
                .andExpect(jsonPath("$.data.total_count").isNumber())
                .andExpect(jsonPath("$.data.items").isArray())
                .andExpect(jsonPath("$.data.items[*].class_type").value("REGION"));

        log.info("지역 목록");
    }

返回

jsonPath("$.data.items[*].class_type").value("REGION")

我只想检查“ $ .data.items [*]。class_type”是否具有“ REGION”。

我该如何更改?

1 个答案:

答案 0 :(得分:1)

一种选择是检查数组中的元素是否具有等于'REGION' class_type

public static final String REGION = "REGION";

mockMvc().perform(get("/api/v1/regions"))
.andExpect(jsonPath("$.data.items[?(@.class_type == '" + REGION + "')]").exists());