使用 REST-assured 進行 JSON Schema 驗證

HTTP Client-Side,REST,Testing
Remote
1
11:32 AM · Dec 01 ,2025

1. 概述

REST-assured 庫提供對 REST API 的支持,通常以 JSON 格式。

有時,在不詳細分析響應內容的情況下,想要首先知道 JSON 響應體是否符合某種 JSON 格式也是有必要的。

在本快速教程中,我們將探討如何根據預定義的 JSON 模式驗證 JSON 響應 我們可以基於預定義的 JSON 模式驗證 JSON 響應

2. 安裝配置

初始的 REST-assured 安裝方式與我們上一篇文章相同。

此外,還需要在 json-schema-validator 模塊中添加至 pom.xml 文件:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>5.5.0</version>
    <scope>test</scope>
</dependency>

為了確保您擁有最新版本,請訪問 此鏈接

3. JSON Schema 驗證讓我們來看一個例子。

作為 JSON Schema,我們將使用保存的文件 event_0.json,該文件位於 classpath 中:

{
    "id": "390",
    "data": {
        "leagueId": 35,
        "homeTeam": "Norway",
        "visitingTeam": "England",
    },
    "odds": [{
        "price": "1.30",
        "name": "1"
    },
    {
        "price": "5.25",
        "name": "X"
    }]
}

假設這是所有通過我們的 REST API 返回的數據所遵循的一般格式,我們可以這樣檢查 JSON 響應的符合性:

@Test
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {
    get("/events?id=390").then().assertThat()
      .body(matchesJsonSchemaInClasspath("event_0.json"));
}

請注意,我們仍然會靜態導入 matchesJsonSchemaInClasspath 來自 io.restassured.module.jsv.JsonSchemaValidator.

4. JSON Schema Validation Settings

4.1. Validate a Response

The json-schema-validator module of REST-assured gives us the power to perform fine-grained validation by defining our own custom configuration rules.

Say we want our validation to always use the JSON schema version 4:

@Test
public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() {
    JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.newBuilder()
      .setValidationConfiguration(
        ValidationConfiguration.newBuilder()
          .setDefaultVersion(SchemaVersion.DRAFTV4).freeze())
            .freeze();
    get("/events?id=390").then().assertThat()
      .body(matchesJsonSchemaInClasspath("event_0.json")
        .using(jsonSchemaFactory));
}

We would do this by using the JsonSchemaFactory and specify the version 4 SchemaVersion and assert that it is using that schema when a request is made.

4.2. Check Validations

By default, the json-schema-validator runs checked validations on the JSON response String. This means that if the schema defines odds as an array as in the following JSON:

{
    "odds": [{
        "price": "1.30",
        "name": "1"
    },
    {
        "price": "5.25",
        "name": "X"
    }]
}

then the validator will always be expecting an array as the value for odds, hence a response where odds is a String will fail validation. So, if we would like to be less strict with our responses, we can add a custom rule during validation by first making the following static import:

io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;

then execute the test with the validation check set to false:

@Test
public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() {
    get("/events?id=390").then().assertThat().body(matchesJsonSchemaInClasspath
      ("event_0.json").using(settings().with().checkedValidation(false)));
}

4.3. Global Validation Configuration

These customizations are very flexible, but with a large number of tests we would have to define a validation for each test, this is cumbersome and not very maintainable.

To avoid this, we have the freedom to define our configuration just once and let it apply to all tests.

We’ll configure the validation to be unchecked and to always use it against JSON schema version 3:

JsonSchemaFactory factory = JsonSchemaFactory.newBuilder()
  .setValidationConfiguration(
   ValidationConfiguration.newBuilder()
    .setDefaultVersion(SchemaVersion.DRAFTV3)
      .freeze()).freeze();
JsonSchemaValidator.settings = settings()
  .with().jsonSchemaFactory(factory)
      .and().with().checkedValidation(false);

then to remove this configuration call the reset method:

JsonSchemaValidator.reset();

5. 結論

在本文中,我們展示瞭如何使用 REST-assured 驗證 JSON 響應與模式。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.