简体   繁体   English

如何使用带有JSON响应的Rest Assured声明基于正文项?

[英]How to assert based on body item with Rest Assured with JSON response?

How can I assert my properties inside the "description" array using the rest assured .body() method. 如何使用放心的.body()方法在“描述”数组中声明我的属性。

Example: 例:

 .body ("[0] .userType", equalTo (1)); // error 

Here is my current JSON data which I want to assert with: 这是我要使用的当前JSON数据:

{
"validSession": true,
"value": "xxx",
"description": [
    {
        "userType": 1,
        "userTypeDescription": "xxx",
        "uname": "xx",
        "distributorId": 1
    }
]}

I dit it: 我把它弄干净了:

.body("validSession",is(true))
.body("description[0].userType", equalTo(1))
.body("description[0].userTypeDescription", containsString("xxx"))
.body("description[0].uname", containsString("xx"))
.body("description[0].distributorId", equalTo(1));

I tested and it worked. 我进行了测试,并且有效。 but I did not understand why it only worked by putting all elements of the array with index zero. 但是我不明白为什么它只能通过将索引为零的数组的所有元素置为有效。

Can you explain? 你可以解释吗?

Try using the following code snippet : 尝试使用以下代码片段:

.body("description[0]", hasItem(1))

Let me know if it was helpful. 让我知道是否有帮助。

Can you explain? 你可以解释吗?

The reason you needed to reference description[0] in your test is that the element "description" in your JSON data is an array. 您需要在测试中引用description[0]的原因是,JSON数据中的元素“ description”是一个数组。 You're using array syntax to declare your intent to read the first element of the array named "description". 您正在使用数组语法声明要读取名为“ description”的数组的第一个元素的意图。

You can also use Hamcrest: 您还可以使用Hamcrest:

Response data = httpClientRequest.getApiCall(url);
data.then().assertThat().body("description.userTypeDescription[0]", Is.is("xxx"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM