我们如何断言JSON响应字段类型(如果是字符串或INT)?

发布于 2025-02-14 00:45:52 字数 248 浏览 1 评论 0原文

我们如何断言JSON响应字段类型?

{
  "Data" : [
     "Id" : 1,
     "Name" : "ABC"
  ]
}

有什么方法可以验证ID应该包含int名称应该是String?我不想验证值。

How do we assert the JSON response field type?

{
  "Data" : [
     "Id" : 1,
     "Name" : "ABC"
  ]
}

Is there any way to validate that ID should contain an int and Name should be a String? I don't want to validate the values.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖不如嘢 2025-02-21 00:45:53

概述

您询问如何检查JSON文档结构。
JSON文档验证针对JSON模式(JSON Schema验证)是执行此类检查的一种方式。

简介

让我们将以下版本视为当前版本:

  • 请放心:5.1.1
  • junit:5.8.2

解决

方案保证支持JSON模式验证。

草稿示例单元测试

单元测试类包含两个测试:成功和失败。

以下消息:

java.lang.AssertionError: 1 expectation failed.
Response body doesn't match expectation.
Expected: The content to match the given JSON schema.
error: instance type (object) does not match any allowed primitive type (allowed: ["string"])
    level: "error"
    schema: {"loadingURI":"file:/<the-project-path>/target/test-classes/schema.json#","pointer":"/properties/Data/items/0/properties/Name"}
    instance: {"pointer":"/Data/0/Name"}
    domain: "validation"
    keyword: "type"
    found: "object"
    expected: ["string"]

  Actual: {
  "Data": [
    {
      "Id": 1,
      "Name": {
        "FirstName": "First",
        "LastName": "Last"
      }
    }
  ]
}

maven项目(pom.xml

<properties>
    <restassured.version>5.1.1</restassured.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>${restassured.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>${restassured.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.github.tomakehurst</groupId>
        <artifactId>wiremock-jre8</artifactId>
        <version>2.33.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

的测试失败了

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "Data": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "properties": {
            "Id": {
              "type": "integer"
            },
            "Name": {
              "type": "string"
            }
          },
          "required": [
            "Id",
            "Name"
          ]
        }
      ]
    }
  },
  "required": [
    "Data"
  ]
}

失败 /test/resources/__ files/data.json )

{
  "Data": [
    {
      "Id": 1,
      "Name": "ABC"
    }
  ]
}

测试数据(src/test/test/resources/__文件/data-invalid.json

{
  "Data": [
    {
      "Id": 1,
      "Name": {
        "FirstName": "First",
        "LastName": "Last"
      }
    }
  ]
}

单元测试类(src/test/java/info/brunov/stackoverflow/Question72903880/dataserviceTest.java

package info.brunov.stackoverflow.question72903880;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.log.LogDetail;
import io.restassured.module.jsv.JsonSchemaValidator;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

public final class DataServiceTest {
    private final WireMockServer server;
    private final RequestSpecification requestSpecification;

    public DataServiceTest() {
        server = new WireMockServer(
            WireMockConfiguration.wireMockConfig().dynamicPort()
        );
        server.stubFor(
            WireMock.get("/data")
                .willReturn(
                    WireMock.aResponse().withBodyFile("data.json")
                )
        );
        server.stubFor(
            WireMock.get("/data-invalid")
                .willReturn(
                    WireMock.aResponse().withBodyFile("data-invalid.json")
                )
        );
        server.start();

        final RequestSpecBuilder requestSpecBuilder = new RequestSpecBuilder();
        requestSpecBuilder.setPort(server.port());
        requestSpecification = requestSpecBuilder.build();
    }

    @AfterEach
    void tearDown() {
        server.stop();
    }

    @Test
    public void getData_responseConformsSchema_success() {
        RestAssured.given()
            .spec(requestSpecification)
            .get("/data")
            .then()
            .log().ifValidationFails(LogDetail.ALL)
            .assertThat()
            .statusCode(200)
            .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("schema.json"));
    }

    // NOTE: Deliberately failing test.
    @Test
    public void getInvalidData_responseConformSchema_fail() {
        RestAssured.given()
            .spec(requestSpecification)
            .get("/data-invalid")
            .then()
            .log().ifValidationFails(LogDetail.ALL)
            .assertThat()
            .statusCode(200)
            .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("schema.json"));
    }
}

Overview

You are asking how to check the JSON document structure.
JSON document validation against a JSON schema (JSON schema validation) is a way to perform such check.

Introduction

Let's consider the following versions as the current versions:

  • REST Assured: 5.1.1.
  • JUnit: 5.8.2.

Solution

REST Assured supports JSON schema validation.

Draft example unit test

The unit test class contain two tests: successful and failing.

The failing test fails with the following message:

java.lang.AssertionError: 1 expectation failed.
Response body doesn't match expectation.
Expected: The content to match the given JSON schema.
error: instance type (object) does not match any allowed primitive type (allowed: ["string"])
    level: "error"
    schema: {"loadingURI":"file:/<the-project-path>/target/test-classes/schema.json#","pointer":"/properties/Data/items/0/properties/Name"}
    instance: {"pointer":"/Data/0/Name"}
    domain: "validation"
    keyword: "type"
    found: "object"
    expected: ["string"]

  Actual: {
  "Data": [
    {
      "Id": 1,
      "Name": {
        "FirstName": "First",
        "LastName": "Last"
      }
    }
  ]
}

Maven project (pom.xml)

<properties>
    <restassured.version>5.1.1</restassured.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>${restassured.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>${restassured.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.github.tomakehurst</groupId>
        <artifactId>wiremock-jre8</artifactId>
        <version>2.33.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

JSON schema (src/test/resources/schema.json)

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "Data": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "properties": {
            "Id": {
              "type": "integer"
            },
            "Name": {
              "type": "string"
            }
          },
          "required": [
            "Id",
            "Name"
          ]
        }
      ]
    }
  },
  "required": [
    "Data"
  ]
}

Test data (src/test/resources/__files/data.json)

{
  "Data": [
    {
      "Id": 1,
      "Name": "ABC"
    }
  ]
}

Test data (src/test/resources/__files/data-invalid.json)

{
  "Data": [
    {
      "Id": 1,
      "Name": {
        "FirstName": "First",
        "LastName": "Last"
      }
    }
  ]
}

Unit test class (src/test/java/info/brunov/stackoverflow/question72903880/DataServiceTest.java)

package info.brunov.stackoverflow.question72903880;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.log.LogDetail;
import io.restassured.module.jsv.JsonSchemaValidator;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

public final class DataServiceTest {
    private final WireMockServer server;
    private final RequestSpecification requestSpecification;

    public DataServiceTest() {
        server = new WireMockServer(
            WireMockConfiguration.wireMockConfig().dynamicPort()
        );
        server.stubFor(
            WireMock.get("/data")
                .willReturn(
                    WireMock.aResponse().withBodyFile("data.json")
                )
        );
        server.stubFor(
            WireMock.get("/data-invalid")
                .willReturn(
                    WireMock.aResponse().withBodyFile("data-invalid.json")
                )
        );
        server.start();

        final RequestSpecBuilder requestSpecBuilder = new RequestSpecBuilder();
        requestSpecBuilder.setPort(server.port());
        requestSpecification = requestSpecBuilder.build();
    }

    @AfterEach
    void tearDown() {
        server.stop();
    }

    @Test
    public void getData_responseConformsSchema_success() {
        RestAssured.given()
            .spec(requestSpecification)
            .get("/data")
            .then()
            .log().ifValidationFails(LogDetail.ALL)
            .assertThat()
            .statusCode(200)
            .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("schema.json"));
    }

    // NOTE: Deliberately failing test.
    @Test
    public void getInvalidData_responseConformSchema_fail() {
        RestAssured.given()
            .spec(requestSpecification)
            .get("/data-invalid")
            .then()
            .log().ifValidationFails(LogDetail.ALL)
            .assertThat()
            .statusCode(200)
            .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("schema.json"));
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文