使用REST Assured,如何检查响应的json对象类型数组中是否存在字段? [英] Using REST Assured, how can I check if a field is present or not in an array of json objects type of response?

查看:201
本文介绍了使用REST Assured,如何检查响应的json对象类型数组中是否存在字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证以下响应是否包含某些字段.我对字段值不感兴趣-只是键存在. 例如,我想检查这种响应类型中是否存在键"id".我该怎么办?

[  
   {  
      "id":"1",
      "title":"Title",
      "details":"details",
      "benefit":"Welcome",
      "expirationTimestamp":1549995900,
      "notice":"some text",     
   }
]

如果我这样做

given()
  .spec(reqSpec).
when()
  .get().
then()
  .body("$", hasKey("id"));

我收到这样的错误:

java.lang.AssertionError: 1 expectation failed.
JSON path $ doesn't match.
Expected: map containing ["id"->ANYTHING]
  Actual: [{blabla=something, id=1, details=details, etc=etc}]

请,有人可以向我解释这应该如何工作吗?

解决方案

尝试一下:

given()
  .spec(reqSpec).
when()
  .get().
then()
  .body("[0]", hasKey("id"));

Groovy GPath在确保放心"中使用.您可以在此处

上查看他们的指南.

这里

I need to validate that a response like the one below contains some fields. I am not interested in the fields value - just that the keys exist. For example I want to check that the key "id" is present in this type of response. How would I accomplish that?

[  
   {  
      "id":"1",
      "title":"Title",
      "details":"details",
      "benefit":"Welcome",
      "expirationTimestamp":1549995900,
      "notice":"some text",     
   }
]

If I do

given()
  .spec(reqSpec).
when()
  .get().
then()
  .body("$", hasKey("id"));

I get an error like this:

java.lang.AssertionError: 1 expectation failed.
JSON path $ doesn't match.
Expected: map containing ["id"->ANYTHING]
  Actual: [{blabla=something, id=1, details=details, etc=etc}]

Please, can someone explain to me how this should work?

解决方案

Try this:

given()
  .spec(reqSpec).
when()
  .get().
then()
  .body("[0]", hasKey("id"));

Groovy GPath is used in Rest Assured. You can take a look at their guide here

Also there's a good tutorial here

这篇关于使用REST Assured,如何检查响应的json对象类型数组中是否存在字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆