【问题标题】:Matching the Json schema with the response getting from the API in rest-assured将 Json 模式与从 API 获得的响应相匹配,放心
【发布时间】:2026-01-10 09:15:01
【问题描述】:

我有一个 post API,我希望使用 JsonSchemaValidator 的方法,因为我希望验证整个响应,而不是通过执行断言来选择响应

我试过用

  1. matchesJsonSchemaInClasspath("我的文件名") 和
  2. matchesJsonSchema(我的文件对象)

我的 reposne 即将成为现实,方法正在通过,但我的架构文件没有检查或验证

public void directLoginWihSchemaValiadtor(){
    File file = new File("C:/Users/abeey/git/SlingAppWebService/Configurations/JsonSchemaValidator_DirectLogin_AWS.json");
    jsonasmap.put("contactNo", "some number");
    jsonasmap.put("loginType","0");
    jsonasmap.put("appid","2");
    jsonasmap.put("co*****ode","IN");
    JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.newBuilder().
    setValidationConfiguration(ValidationConfiguration.newBuilder().freeze()).freeze();

    given().contentType(ContentType.JSON).body(jsonasmap).when().
    post("https://60i*****.execute-api.us-west-2.amazonaws.com/some-api").
    then().assertThat().
    body(JsonSchemaValidator.matchesJsonSchema(file))).


    log().all();
    jsonasmap.clear();
}

//body(JsonSchemaValidator.matchesJsonSchemaInClasspath("JsonSchemaValidator_DirectLogin_AWS.json").using(jsonSchemaFactory))

我尝试使用 jsonSchemaFactory 来执行此操作,但我没有得到关于将什么设置为草稿版本或从何处获取它的信息

我是新手,如果你觉得这个问题太简单了,请多多包涵

【问题讨论】:

  • 在创建JsonSchemaFactory 时尝试指定要使用的架构草案。 DRAFTV4 是我使用的。
  • 我用过它,但它不起作用,我认为它仅用于检查 json 响应是否为 DraftV4 版本
  • 您可以发布您正在验证的架构吗?
  • 这是我使用 JsonSchemaFactory JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.newBuilder() 创建的代码。 setValidationConfiguration(ValidationConfiguration.newBuilder().setDefaultVersion(SchemaVersion.DRAFTV4).freeze()).freeze(); given().contentType(ContentType.JSON).body(jsonasmap).when().post("https://***d.execute-api.us-**-.amazonaws .com/some-api").then().assertThat().body(JsonSchemaValidator.matchesJsonSchema(file).using(jsonSchemaFactory)).log().all();如果您对改进它有任何建议,以便达到效果,请告诉
  • 问题是我在模式中输入的内容是正确还是不正确,无论如何它都会显示通过

标签: json rest automation rest-assured rest-assured-jsonpath


【解决方案1】:

对于这种情况,我通常会执行以下操作:

  1. 使用模式生成器并为json主体创建模式(我使用这个工具json-schema-generator

  2. 将生成的 json 模式放入类路径(例如 test/resources)

  3. 将此代码用作 REST Assured 测试的一部分:

    .body(matchesJsonSchemaInClasspath("your_schema_name.json"))

如果您想确保架构验证正常工作,您可以编辑架构文件并将任何必填字段的类型更改为其他内容,然后查看您的测试是否会失败。

你可以参考我的this post查看一些代码示例。

【讨论】:

  • 遗憾的是,过去几周我一直在手写我的。没想到检查工具来为你做一个模式。我找到了这个:jsonschema.net/#/editor
  • 确实有很多工具,我提到了一个,因为它很容易安装,不需要配置并且做得很好,已经使用了一年左右测试
  • 非常感谢@BigGinDaHouse 我正在给自己写模式,它的顺序不正确,所以这可能是我没有得到任何验证的原因,非常感谢
最近更新 更多