You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用RestAssured的matchesJsonSchemaInClasspath遇Schema为空错误

问题

使用RestAssured的matchesJsonSchemaInClasspath()方法验证JSON响应与Schema一致性时,抛出如下异常:

java.lang.IllegalArgumentException: Schema to use cannot be null
    at io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath(JsonSchemaValidator.java:...)

测试代码相关片段:

given()
    .header("Content-Type", ContentType.JSON)
    .body(jsonBody)
    .when()
    .post("http://localhost/api/v1/example")
    .then()
    .statusCode(200)
    .and()
    .body(matchesJsonSchemaInClasspath("src/test/resources/example-schema.json"));

项目结构:

src
├── main
│   └── java
└── test
    ├── java
    │   └── MyTestClass.java
    └── resources
        └── example-schema.json

已确认example-schema.json存在于src/test/resources目录,Schema内容合法,且通过代码验证文件在类路径中,但仍报错。

解决方案

  • 修正类路径路径参数
    matchesJsonSchemaInClasspath()接收的是类路径根目录下的相对路径,src/test/resources在测试阶段会被自动加入类路径根,因此无需带目录前缀,直接传入文件名即可:

    .body(matchesJsonSchemaInClasspath("example-schema.json"));
    
  • 清理并重新构建项目
    构建工具(Maven/Gradle)可能存在缓存,导致资源文件未被正确复制到类路径:

    • Maven执行:mvn clean test
    • Gradle执行:gradle clean test
  • 验证类路径加载有效性
    用以下代码确认文件是否能被类加载器读取,排查资源路径问题:

    InputStream schemaStream = getClass().getClassLoader().getResourceAsStream("example-schema.json");
    if (schemaStream == null) {
        throw new RuntimeException("Schema file not found in classpath");
    }
    

    若抛出异常,需检查构建工具的资源复制配置,确保src/test/resources下的文件被正确打包到测试类路径。

  • 升级RestAssured依赖版本
    部分旧版本的RestAssured JSON Schema验证模块存在类路径资源加载bug,建议升级到最新稳定版(如5.x系列)。Maven依赖示例:

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

内容的提问来源于stack exchange,提问作者Gabriel Carvalho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 23:03:14