【问题标题】:Rest-Assured validate each item in a JSON array放心验证 JSON 数组中的每个项目
【发布时间】:2016-12-23 13:59:15
【问题描述】:

鉴于我有这个 JSON 数组:

{
    value: ["000", "111", "345", "987"]
}

我想使用 Rest-assured 来验证字段的格式,使用它的 given/when/then 结构。

given().
    queryParam("myparam", myparamvalue).
when().
    get(callRoot).
then().
    body("value", matchesPattern("[0-9][0-9][0-9]");

如何确保放心循环并针对 JSON 数组中的每个值应用测试?

我不知道 JSON 数组中有多少个值。它可能只有 1;可能是 100。

【问题讨论】:

    标签: rest-assured


    【解决方案1】:

    您可以使用JsonPath 并执行以下操作:

    given().
        queryParam("myparam", myparamvalue).
    when().
        get(callRoot).
    then().
      body("value.*", matchesPattern("[0-9][0-9][0-9]");
    

    更多详情请见https://github.com/rest-assured/rest-assured/wiki/usage#json-example

    或者您可以将响应提取为String,将其转换为JSONObject,在values 字段中提取JSONArray,然后将正则表达式应用于数组中的每个项目:

    Response response = given().queryParam("myparam", myparamvalue).when().get(callRoot).
    
    JSONObject responseJson = new JSONObject(response.getBody().asString());
    JSONArray values = responseJson.getJSONArray("values");
    
    for(int i = 0; i < values.length(); i++) {
      String value = values.getString(i);
       Assert.assertThat(values, matchesPattern("[0-9][0-9][0-9]"));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多