1. 概述
REST-assured 庫提供對 REST API 的支持,通常以 JSON 格式。
有時,在不深入分析響應內容的情況下,首先要知道 JSON 響應體是否符合特定的 JSON 格式是很有必要的。
在本快速教程中,我們將探討如何根據預定義的 JSON 模式驗證 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>為了確保您擁有最新版本,請按照 此鏈接 操作。
3. JSON 模式驗證
讓我們來看一個例子。
作為 JSON 模式,我們將使用保存在一個名為 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 驗證 Settings
4.1. 驗證響應
REST-assured 中的 json-schema-validator 模塊使我們能夠通過定義自定義配置規則執行精細化的驗證。
例如,如果我們希望驗證始終使用 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));
}我們將會通過使用 JsonSchemaFactory,並指定版本 4 的 SchemaVersion,以及在請求時斷言它正在使用該 schema 來實現。
4.2. 校驗驗證
默認情況下,<em >json-schema-validator</em> 會在 JSON 響應字符串上運行校驗驗證。這意味着如果模式定義 <em >odds</em> 為一個數組,如以下 JSON:
{
"odds": [{
"price": "1.30",
"name": "1"
},
{
"price": "5.25",
"name": "X"
}]
}然後驗證器始終會期望 odds 的值是一個數組,因此如果響應中 odds 是一個 String,則會失敗驗證。如果我們希望對響應進行更寬鬆的驗證,可以在驗證過程中添加自定義規則,首先進行以下靜態導入:
io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;然後執行測試,並將驗證檢查設置為 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 全局驗證配置
這些自定義選項非常靈活,但如果測試數量過多,我們必須為每個測試定義驗證規則,這既繁瑣又難以維護。
為了避免這種情況,我們有自由地一次定義配置,並讓其應用於所有測試。
我們將配置驗證為未選中狀態,並始終使用它來驗證 JSON 模式版本 3:
JsonSchemaFactory factory = JsonSchemaFactory.newBuilder()
.setValidationConfiguration(
ValidationConfiguration.newBuilder()
.setDefaultVersion(SchemaVersion.DRAFTV3)
.freeze()).freeze();
JsonSchemaValidator.settings = settings()
.with().jsonSchemaFactory(factory)
.and().with().checkedValidation(false);然後,要移除此配置,請調用 reset 方法:
JsonSchemaValidator.reset();結論
在本文中,我們展示瞭如何使用 REST-assured 驗證 JSON 響應與模式的匹配情況。