在 java 使用放心执行操作时无法获取断言的响应主体数据

Not able to take response body data for assertions while performing operations using rest-assured with java

响应正文如下:

{
    "Updated_Fields": [
        "a",
        "b",
        "c",
        "d"
    ],
    "Invalid_Fields": [
        "cd",
        "ab"
    ]
}

我想检查响应正文是否有

  1. invalid_field 块中的两个字段
  2. 'cd' 和 'ab' 应该在 invalid_field 块
JSONArray JSONResponseBody = new JSONArray(response.body().asString());

Assert.assertEquals(JSONResponseBody.getJSONObject(0).getString("Invalid_Fields"), "cd");

response.jsonPath().param("Invalid_Fields", "cd");

assertThat( response.asString(), hasJsonPath("Invalid_Fields.ab"));

遇到错误

一种方法可以使用像 gson 这样的库将 String 转换为 Java 对象,然后应用标准 Java 逻辑(下面的示例)

Gson Maven Dependency

private static final List INVALID_DATA = Arrays.asList("cd", "ab");

public static void main(String[] args)
{
    String input = "{ \"Updated_Fields\": [ \"a\", \"b\", \"c\", \"d\" ], \"Invalid_Fields\": [ \"cd\", \"ab\" ] }";
    Gson gson = new Gson();
    FieldData data = gson.fromJson(input, FieldData.class);
    System.out.println(isInvalidFields(data.Invalid_Fields));
}

private static boolean isInvalidFields(List<String> Invalid_Fields) {
    if(CollectionUtils.isEmpty(Invalid_Fields) || Invalid_Fields.size() != 2) {
     return false;   
    }
    return Invalid_Fields.containsAll(INVALID_DATA);
}

class 映射到此数据的定义:

public class FieldData
{

    public List<String> Updated_Fields;

    public List<String> Invalid_Fields;

}