在 JAVA 中循环遍历 SerenityRest 响应

Looping through SerenityRest Response in JAVA

我正在尝试从汽车对象中获取所有模型的数量,这是 SerenityRest 响应的一部分。

Response response = SerenityRest.rest()
        .contentType("application/json")
        .when()
        .get("/api/");
if (response.statusCode() == 200) {
   int numUniqueModels = response.body().path("cars.size()");  // 3
}

回复:

   "cars": {
       "Acura": [
           "ILX",
           "MDX",
           "TLX"
       ],
       "Audi": [
           "A3",
           "A4",
           "A6",
           "A7"
       ],
       "BMW": [
           "x",
           "y"
       ]
   }

例如,

response.body().path("cars.size()") = 3,

但我需要 cars.Acura.size() + cars.Audi.size() + cars.BMW.size() 的总和才能获得所有模型。但是,我不知道响应中是否会出现 Acura、Audi 或 BMW 的确切名称,因为车辆可能会动态变化。为了解决这个问题,我需要做一些循环,其中:

sum = 0; 
for (int i = 0; i < response.body().path("cars.size()"); i++) {
   sum += response.body().path("cars.[i].size()");
}

总和应得出汽车型号总数 = 9。 问题是这个语法:path("cars.[i].size()") 不正确。正确的叫法是什么?

如果您想使用 rest-assured 发出复杂的请求,您必须遵循此处描述的语法 groovy gpath as mentionned here rest-assured doc:

Note that the JsonPath implementation uses Groovy's GPath syntax and is not to be confused with Jayway's JsonPath implementation.

所以你必须玩一些 groovy synthax:

int total = JsonPath.from("{  "
              + " \"cars\": {\n"
              + "       \"Acura\": [\n"
              + "           \"ILX\",\n"
              + "           \"MDX\",\n"
              + "           \"TLX\"\n"
              + "       ],\n"
              + "       \"Audi\": [\n"
              + "           \"A3\",\n"
              + "           \"A4\",\n"
              + "           \"A6\",\n"
              + "           \"A7\"\n"
              + "       ],\n"
              + "       \"BMW\": [\n"
              + "           \"x\",\n"
              + "           \"y\"\n"
              + "       ]\n"
              + "   }"
              + "}")
        .getInt("cars.collect { it.value.size() }.sum()")

所以这个表达式应该成为工作cars.collect { it.value.size() }.sum()collect 方法就像函数式编程中的 map 方法。因此,您将集合 cars HashMap 映射到其值的 size() 并收集 sum()!

编辑

所以你只需要做:

Response response = SerenityRest.rest()
        .contentType("application/json")
        .when()
        .get("/api/");
if (response.statusCode() == 200) {
   int numUniqueModels = response.body().path("cars.collect { it.value.size() }.sum()");  // 9
}