使用Rest Assured检查JSON数组的值时出现问题



我正试图在我的应用程序中添加一些带有Rest Assured的测试,但我不知道如何断言一些嵌套值。错误消息为:

预期:(包含"json"的集合(实际:[[json,spring,gullow,path等]]

这是代码:

when().
get("/api/personsByID/{id}/{count}", 262, 2).
then().
statusCode(200).
body("personDependencies.name", hasItems("json"));

这是rest控制器返回的JSON文件:

[
{
"id": 346,
"verified": true,
"displayName": "eda656a2c3cb59ae840e40a28ba4ab50bfb9de0185abcb901c6af6dc59d6668f",
"emails": [
{
"email": "16a23f2e5477df0bbcad718c3abc235b2cb8a1b6648d14f58d42a7be13df2b6e"
}
],
"personDependencies": [
{
"name": "json"
},
{
"name": "spring"
},
{
"name": "gulp"
},
{
"name": "path"
},
{
"name": "junit"
},
{
"name": "activemq"
},
{
"name": "hibernate"
},
{
"name": "jstl"
},
{
"name": "phantomjs"
},
{
"name": "activiti"
},
{
"name": "commons"
},
{
"name": "h2"
},
{
"name": "joda"
},
{
"name": "log4j"
},
{
"name": "exec"
},
{
"name": "admin"
},
{
"name": "coveralls"
},
{
"name": "cxf"
},
{
"name": "cglib"
},
{
"name": "camel"
},
{
"name": "sugaronrest"
},
{
"name": "tslint"
},
{
"name": "httpclient"
},
{
"name": "guava"
},
{
"name": "inventory"
},
{
"name": "jackson"
},
{
"name": "gson"
},
{
"name": "event"
},
{
"name": "OTRS"
},
{
"name": "maven"
},
{
"name": "karma"
},
{
"name": "slf4j"
},
{
"name": "postgresql"
},
{
"name": "typescript"
},
{
"name": "jasmine"
},
{
"name": "spa"
},
{
"name": "javax.servlet"
}
],
"countries": [],
"member_of": [],
"projects": [],
"employee_type": [],
"languages": [
{
"language": "reStructuredText",
"sum": 575
},
{
"language": "JSON",
"sum": 21
},
{
"language": "JavaScript",
"sum": 4467
},
{
"language": "Java",
"sum": 7958
},
{
"language": "Python",
"sum": 2
},
{
"language": "XML",
"sum": 477
},
{
"language": "Plain Text",
"sum": 41
}
],
"distance": 0.6028837702084446
}
]

我不知道如何做出正确的断言,任何帮助都会很好。谢谢

如果我读对了你的问题,你需要检查为特定ID 返回的列表中是否存在特定值

以下内容应该适用于

given().when().get().then().body("find {it.id == 346}.personDependencies.name", hasItems("json", "jackson"));

第一个问题是,你不需要用hasItems检查项目的存在,你应该使用hasItem

when().
get("/api/personsByID/{id}/{count}", 262, 2).
then().
statusCode(200).
body("personDependencies.name", hasItem("json"));

然后,如果您需要在测试失败时向断言添加更多消息,您可以这样做:

when().
get("/api/personsByID/{id}/{count}", 262, 2).
then().
statusCode(200).
body("personDependencies.name",  describedAs("Array not containing the provided item",hasItem("json")));

在您的情况下,您可以通过以下方式进行验证:

when().
get("/api/personsByID/{id}/{count}", 262, 2).
then().
statusCode(200).
body("personDependencies[*].name", hasItem("json"));

Wilfred Clement的回答很棒。我只想再添加一个例子,以便更好地理解概念和语法。如果您必须在某个不在JSON的"根"级别的数组中进行类似的搜索,请使用下一个语法:

.body("problems.find {it.property == 'boardUrl'}.details", is("size must be between 1 and 256"))

此路径是为以下JSON结构创建的:

{
"title": "Bad Request",
"status": 400,
"problems": [
{
"property": "tag",
"value": "too-big-tag-value",
"details": "size must be between 1 and 10"
},
{
"property": "name",
"value": "Very big name for testing purposes",
"details": "size must be between 1 and 20"
}
]
}

相关内容

  • 没有找到相关文章

最新更新