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
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
4.2. Check Validations
By default, the
{
"odds": [{
"price": "1.30",
"name": "1"
},
{
"price": "5.25",
"name": "X"
}]
}
then the validator will always be expecting an array as the value for
io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
then execute the test with the validation check set to
@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’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 響應與模式。