JSON Schema Validation with REST-assured – 用REST-assured进行JSON模式验证

最后修改: 2018年 3月 29日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

The REST-assured library provides support for testing REST APIs, usually in JSON format.

REST-assured库为测试REST API提供支持,通常为JSON格式。

From time to time it may be desirable, without analyzing the response in detail, to know first-off whether the JSON body conforms to a certain JSON format.

有时可能需要在不详细分析响应的情况下,首先知道JSON体是否符合某种JSON格式。

In this quick tutorial, we’ll take a look at how we can validate a JSON response based on a predefined JSON schema.

在这个快速教程中,我们将看看我们如何根据预定义的JSON模式验证一个JSON响应

2. Setup

2.设置

The initial REST-assured setup is the same as our previous article.

最初的REST-assured设置与我们之前的文章相同。

In addition, we also need to include the json-schema-validator module in the pom.xml file:

此外,我们还需要在json-schema-validator文件中包括pom.xml模块。

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

To ensure you have the latest version, follow this link.

为确保你有最新的版本,请按照这个链接

3. JSON Schema Validation

3.JSON模式验证

Let’s have a look at an example.

让我们来看看一个例子。

As a JSON schema, we’ll use a JSON saved in a file called event_0.json, which is present in the classpath:

作为一个JSON模式,我们将使用保存在一个名为event_0.json的文件中的JSON,该文件存在于classpath中。

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

Then assuming that this is the general format followed by all data returned by our REST API, we can then check a JSON response for conformance like so:

然后假设这是我们的REST API返回的所有数据所遵循的一般格式,我们就可以像这样检查JSON响应的一致性。

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

Notice that we’ll still statically import matchesJsonSchemaInClasspath from io.restassured.module.jsv.JsonSchemaValidator.

注意,我们仍将从io.restassured.module.jsv.JsonSchemaValidator.静态导入matchesJsonSchemaInClasspath

4. JSON Schema Validation Settings

4.JSON模式验证设置

4.1. Validate a Response

4.1.验证一个回应

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

REST-assured的json-schema-validator模块让我们有能力通过定义我们自己的自定义配置规则来进行细粒度的验证。

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

假设我们希望我们的验证总是使用JSON模式的第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.

我们将通过使用JsonSchemaFactory和指定版本4SchemaVersion来做到这一点,并断言在发出请求时它正在使用该模式。

4.2. Check Validations

4.2.检查验证

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:

默认情况下,json-schema-validator对JSON响应字符串运行检查验证。这意味着,如果模式将odds定义为一个数组,如下面的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:

那么验证器将一直期待一个数组作为odds的值,因此一个oddsString的响应将无法验证。因此,如果我们想对我们的响应不那么严格,我们可以在验证期间添加一个自定义规则,首先进行以下静态导入。

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

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

然后执行测试,验证检查设置为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

4.3.全局验证配置

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:

我们将配置验证为未被选中,并且总是针对JSON模式版本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. Conclusion

5.结论

In this article, we’ve shown how we can validate a JSON response against a schema when using REST-assured.

在这篇文章中,我们展示了在使用REST-assured时,我们如何根据模式验证JSON响应。

As always, the full source code for the example is available over on GitHub.

一如既往,该示例的完整源代码可在GitHub上获得