javascript
REST Assured 55 - JSON Schema Validation In Rest Assured
REST Assured 系列匯總 之 REST Assured 55 - JSON Schema Validation In Rest Assured
前提條件
添加 rest assured 依賴包
<!-- REST Assured --> <dependency><groupId>io.rest-assured</groupId><artifactId>rest-assured</artifactId><version>4.4.0</version> </dependency>添加 json-schema-validator 依賴包
Rest Assured 自 2.1.0 版本起支持 JSON Schema validatation。為了使用這個功能,我們需要添加 “json-schema-validator” Java 庫。
當你在 Maven central repo 上搜索 json-schema-validator 時,會出現許多相同名字的庫。確保 groupId 是 io.rest-assured。
Class JsonSchemaValidator
JsonSchemaValidator 類提供了許多重載的靜態的方法來執行 JSON schema 校驗。
public static JsonSchemaValidator matchesJsonSchemaInClasspath(String pathToSchemaInClasspath) – Creates a Hamcrest matcher that validates that a JSON document conforms to the JSON schema provided to this method.
public static JsonSchemaValidator matchesJsonSchema(File file) – Creates a Hamcrest matcher that validates that a JSON document conforms to the JSON schema provided to this method.
如果將 JSON Schema 文件保存在項目的 resource folder 或 src/test/resources maven 項目,就可以直接用 matchesJsonSchemaInClasspath() 方法,只要傳遞 JSON Schema 文件名。如果 JSON Schema 文件存儲在項目的不同地方或外部項目中,可以用 matchesJsonSchema() 方法。
Asserting JSON response against JSON Schema
Create JSON Schema
我們用到前一篇文章中相同的 JSON Schema,這個 JSON Schema 是基于 Restful Booker – Auth API 生成的。把這個 JSON Schema 存放在 src/test/resources。
AuthJsonSchema.json
{"$schema": "http://json-schema.org/draft-07/schema","$id": "http://example.com/example.json","type": "object","title": "The root schema","description": "The root schema comprises the entire JSON document.","default": {},"examples": [{"token": "abc123"}],"required": ["token"],"properties": {"token": {"$id": "#/properties/token","type": "string","title": "The token schema","description": "An explanation about the purpose of this instance.","default": "","examples": ["abc123"]}},"additionalProperties": true }Performing JSON Schema validation using matchesJsonSchemaInClasspath()
我們也可以直接在 body(Matcher matcher) 來調用 schema validator 方法。你可能會想到 JSON Schema validator 方法的返回類型是 JsonSchemaValidator, 怎么可以在 body(Matcher matcher) 方法調用呢。這是因為多層繼承。 JsonSchemaValidator 類是間接實現 Matcher 接口。
import org.hamcrest.Matchers; import org.junit.Test;import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.module.jsv.JsonSchemaValidator;public class VerifyJsonSchema {@Testpublic void verifyJsonSchema() {String jsonStringPayload = "{\"username\" : \"admin\",\"password\" : \"password123\"}";// GIVENRestAssured.given().baseUri("https://restful-booker.herokuapp.com/auth").contentType(ContentType.JSON).body(jsonStringPayload)// WHEN.when().post()// THEN.then().assertThat().statusCode(200).body("token", Matchers.notNullValue()).body(JsonSchemaValidator.matchesJsonSchemaInClasspath("AuthJsonSchema.json"));}}上面的測試會成功,做一些改動讓期望的 JSON Schema 驗證失敗。
Adding extra required properties
上面 response 里只返回一個屬性 “token”,我們在加一個新的屬性 “nonExistingProperty” 在 JSON Schema “required” 部分:
失敗
從 log 里可以看出一個必要的字段 “nonExistingProperty” 缺失了。
required: ["nonExistingProperty","token"] missing: ["nonExistingProperty"]
java.lang.AssertionError: 1 expectation failed. Response body doesn't match expectation. Expected: The content to match the given JSON schema. warning: the following keywords are unknown and will be ignored: [$id, examples]level: "warning"schema: {"loadingURI":"file:/C:/ForKelly/Automation/RestAssuredDemo/target/test-classes/AuthJsonSchema.json#","pointer":""}domain: "syntax"ignored: ["$id","examples"] warning: the following keywords are unknown and will be ignored: [$id, examples]level: "warning"schema: {"loadingURI":"file:/C:/ForKelly/Automation/RestAssuredDemo/target/test-classes/AuthJsonSchema.json#","pointer":"/properties/token"}domain: "syntax"ignored: ["$id","examples"] error: object has missing required properties (["nonExistingProperty"])level: "error"schema: {"loadingURI":"file:/C:/ForKelly/Automation/RestAssuredDemo/target/test-classes/AuthJsonSchema.json#","pointer":""}instance: {"pointer":""}domain: "validation"keyword: "required"required: ["nonExistingProperty","token"]missing: ["nonExistingProperty"]Actual: [token:11b60187aad762d] ...............................Change the data type of properties
屬性 “token” 字段的值類型是 string,我們把它改成 integer 類型 “type”: “integer”,看看校驗結果。
類型匹配失敗
error: instance type (string) does not match any allowed primitive type (allowed: ["integer"])
java.lang.AssertionError: 1 expectation failed. Response body doesn't match expectation. Expected: The content to match the given JSON schema. warning: the following keywords are unknown and will be ignored: [$id, examples]level: "warning"schema: {"loadingURI":"file:/C:/ForKelly/Automation/RestAssuredDemo/target/test-classes/AuthJsonSchema.json#","pointer":""}domain: "syntax"ignored: ["$id","examples"] warning: the following keywords are unknown and will be ignored: [$id, examples]level: "warning"schema: {"loadingURI":"file:/C:/ForKelly/Automation/RestAssuredDemo/target/test-classes/AuthJsonSchema.json#","pointer":"/properties/token"}domain: "syntax"ignored: ["$id","examples"] warning: the following keywords are unknown and will be ignored: [$id, examples]level: "warning"schema: {"loadingURI":"file:/C:/ForKelly/Automation/RestAssuredDemo/target/test-classes/AuthJsonSchema.json#","pointer":"/properties/token"}domain: "syntax"ignored: ["$id","examples"] error: instance type (string) does not match any allowed primitive type (allowed: ["integer"])level: "error"schema: {"loadingURI":"file:/C:/ForKelly/Automation/RestAssuredDemo/target/test-classes/AuthJsonSchema.json#","pointer":"/properties/token"}instance: {"pointer":"/token"}domain: "validation"keyword: "type"found: "string"expected: ["integer"]Actual: [token:88a742f48f20b7c]Performing JSON Schema validation using matchesJsonSchema()
上面的例子中我們將 JSON Schema 文件放在 src/test/resources folder 下,可以使用 matchesJsonSchemaInClasspath() 方法。如果我們將 JSON Schema 文件不是放在 resource 文件夾下,那么就不能使用 matchesJsonSchemaInClasspath() 這個方法,否則會拋出 IllegalArgumentException 異常。
注意:前面提到 schema 文件放在 src/test/resources folder 下,其實你也可以將 schema 文件放在 src/main/resources folder 下。測試類可以放在 src/main/java 或 src/test/java,但是作為好的實踐標準,我們最好將測試相關的類放在 src/test/java folder 下。最好在 pom.xml 添加依賴包時移除 tag,這樣就能避免不必要的范圍限制。
例如:
移除 tag
<!-- json schema validation --> <dependency><groupId>io.rest-assured</groupId><artifactId>json-schema-validator</artifactId><version>4.3.0</version> </dependency>如果將 schema 文件不是放在 resource folder 下,我們就要用到另外一個靜態方法 matchesJsonSchema() ,需要傳一個完整的 JSON Schema 文件路徑。
import java.io.File;import org.hamcrest.Matchers; import org.junit.Test;import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.module.jsv.JsonSchemaValidator;public class VerifyJsonSchemaNonResource {@Testpublic void verifyJsonSchema() {String jsonStringPayload = "{\"username\" : \"admin\",\"password\" : \"password123\"}";// GIVENRestAssured.given().baseUri("https://restful-booker.herokuapp.com/auth").contentType(ContentType.JSON).body(jsonStringPayload)// WHEN.when().post()// THEN.then().assertThat().statusCode(200).body("token", Matchers.notNullValue()).body(JsonSchemaValidator.matchesJsonSchema(new File("C:\\Users\\kkk\\git\\master\\src\\test\\java\\JsonSchema\\schema.json")));}}記住:matchesJsonSchema 方法的參數是一個 File 對象,不是文件的完整路徑 string 類型。matchesJsonSchema() 期望的 JSON schema 是一個 string 而不是一個 文件路徑的 string.
總結
總結
以上是生活随笔為你收集整理的REST Assured 55 - JSON Schema Validation In Rest Assured的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql执行计划中的temp_MYSQ
- 下一篇: 面试:整理面试中常被问到的8种数据结构