放心 - 使用 GPath 从多条记录列表中提取单个值

Rest Assured - Extract a single value from a list of multiple records with GPath

我有一个记录列表:

{
  "StatusCode": 200,
  "Result": [
    {
      "Id": 15015600,
      "Amount": 97.41,
      "CreatedDate": "10/17/2018",
    },
    {
      "Id": 15015602,
      "Amount": 682.11,
      "CreatedDate": "10/17/2018",
    },
   and so on...

当我知道 Amount 和 CreatedDate 时,我正在尝试为 return "Id" 值编写一个声明。

int Id = given()
            .when()
                .get(/EndPoint))
            .then()
                .body("Result.findAll { it.Amount==97.41 }.CreatedDate", hasItems("10/17/2018"));

这可能吗?

如果您将记录列表作为列表而不是 json 字符串,您可以调用

def id = YourResponse.Result.find{it.Amount==97.41 && it.CreatedDate=="10/17/2018"}

它将return您第一个找到符合您的搜索条件的结果。如果您使用相同的闭包调用 findAll 而不是 find,您将获得所有匹配项的列表。

很难判断您是否已经解析了 JSON,因此我也包含了执行此操作的代码。这很简单 Groovy,不是 Rest Assured 特定的。

import groovy.json.JsonSlurper

def text = '''
{
  "StatusCode": 200,
  "Result": [
    {
      "Id": 15015600,
      "Amount": 97.41,
      "CreatedDate": "10/17/2018",
    },
    {
      "Id": 15015602,
      "Amount": 682.11,
      "CreatedDate": "10/17/2018",
    }
   ]
}'''
def json = new JsonSlurper().parseText(text)
assert json.Result.find{ it.Amount == 97.41 && it.CreatedDate == '10/17/2018' }.Id == 15015600

解决方法:

int i = response.path("Result.find{it.Amount.toDouble()==293.51 && it.CreatedDate=='10/26/2018'}.Id");

我需要将 "toDouble()" 添加到我的查询中。 it.Amount.toDouble()==293.51,不是 it.Amount==293.51。添加 toDouble() 后,查询按预期工作。