1. 概述

REST-assured 库为测试 REST API(通常是 JSON 格式)提供了强大支持。

有时我们不需要深入分析响应细节,只想快速确认 JSON 响是否符合特定格式。本文将演示如何基于预定义的 JSON Schema 验证 JSON 响应

2. 环境配置

基础 REST-assured 配置与我们之前的文章一致。此外,需在 pom.xml 中添加 json-schema-validator 模块:

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

获取最新版本可访问 Maven 仓库

3. JSON Schema 验证

看个实际例子。我们使用类路径下的 event_0.json 作为 Schema 文件:

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

假设这是 REST API 返回数据的标准格式,验证响应是否符合该结构的代码如下:

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

注意需静态导入 io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath

4. JSON Schema 验证设置

4.1. 自定义验证规则

REST-assured 的 json-schema-validator 模块允许通过自定义配置实现精细控制。例如强制使用 JSON Schema v4 版本:

@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));
}

通过 JsonSchemaFactory 指定 SchemaVersion.DRAFTV4,确保请求使用该版本验证。

4.2. 验证模式选择

默认启用严格验证(checked validation)。若 Schema 定义 odds 为数组:

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

odds 数组结构示例

则响应中 odds 必须是数组,否则验证失败。若需放宽限制,可关闭严格验证:

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

需静态导入 io.restassured.module.jsv.JsonSchemaValidatorSettings.settings

4.3. 全局验证配置

为每个测试单独配置验证规则很繁琐。更优雅的方式是定义全局配置

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

此配置将全局生效,直到调用重置方法:

JsonSchemaValidator.reset();

5. 总结

本文展示了使用 REST-assured 进行 JSON Schema 验证的核心技巧:

基础验证:通过 matchesJsonSchemaInClasspath 快速验证响应结构
版本控制:使用 JsonSchemaFactory 指定 Schema 版本
严格模式:通过 checkedValidation 控制验证严格程度
全局配置:避免重复代码,统一管理验证规则

这些技巧能显著提升 API 测试的健壮性,尤其适合需要严格校验响应格式的场景。


原始标题:JSON Schema Validation with REST-assured | Baeldung