微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

RestAssured - 想在 RestAssured 中验证 JSON 响应的主体结构

如何解决RestAssured - 想在 RestAssured 中验证 JSON 响应的主体结构

当我请求 GET 请求时,我得到的是 JSON 响应,但这里我的要求是验证响应正文的结构。

例如:

{
   "lotto":{
      "lottoId":5,"winning-numbers":[2,45,34,23,7,5,3],"winners":[
         {
            "winnerId":23,"numbers":[2,3,5]
         },{
            "winnerId":54,"numbers":[52,12,11,18,22]
         }
      ]
   }
}

上述响应具有结构,所以我需要验证结构而不是一个键值对,我该如何实现?

解决方法

最好的方法是验证json-schema匹配。

首先,您需要将此依赖项添加到您的 pom.xml

<!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
<dependency>
  <groupId>io.rest-assured</groupId>
  <artifactId>json-schema-validator</artifactId>
  <version>3.3.0</version>
  <scope>test</scope>
</dependency>

然后你需要创建一个文件 json-schema-your-name.json ,结构如下:

{
  "type": "object","properties": {
    "data": {
      "type": "array","items": {
        "type": "object","properties": {
          "flow_id": {
            "type": "string","minLength": 36,"maxLength": 36
          },"flow_org_id": {
            "type": "string"
          }
        },"required": [ "flow_id","flow_org_id" ]
      }
    }
  }
}

有很多服务基于 json 生成模式 - 例如 - this one

一旦架构文件准备好,您需要以字符串格式提供文件的路径 - 例如 -

private static final String GET_SUBSCRIPTION_JSON_SCHEMA_PATH =
    "json/schemas/GetSubscriptionByIdSchema.json";

并调用 matchesJsonSchemaInClasspath("your/path/to/json-schema") 方法进行断言。

UPD:

所以流程基本上是这样的:

  • 您在项目目录的某处有一个架构文件(并且知道它的路径)
  • 您在某些测试方法中达到了端点
  • 您将收到的响应与架构文件相匹配

实际上,它将如下所示:

  @Test
  public void someTestMethod() {
    Response responseToValidate = // here you should assign and store returned response
    
    responseToValidate
      .assertThat()      
      .statusCode(200)
      .body("json.path.to.needed.key",equalTo("123"))

.body(matchesJsonSchemaInClasspath("path/to/your/schema/in/string/format")); }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。