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。為了使用這個(gè)功能,我們需要添加 “json-schema-validator” Java 庫(kù)。
當(dāng)你在 Maven central repo 上搜索 json-schema-validator 時(shí),會(huì)出現(xiàn)許多相同名字的庫(kù)。確保 groupId 是 io.rest-assured。
Class JsonSchemaValidator
JsonSchemaValidator 類提供了許多重載的靜態(tài)的方法來執(zhí)行 JSON schema 校驗(yàn)。
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 文件保存在項(xiàng)目的 resource folder 或 src/test/resources maven 項(xiàng)目,就可以直接用 matchesJsonSchemaInClasspath() 方法,只要傳遞 JSON Schema 文件名。如果 JSON Schema 文件存儲(chǔ)在項(xiàng)目的不同地方或外部項(xiàng)目中,可以用 matchesJsonSchema() 方法。
Asserting JSON response against JSON Schema
Create JSON Schema
我們用到前一篇文章中相同的 JSON Schema,這個(gè) JSON Schema 是基于 Restful Booker – Auth API 生成的。把這個(gè) 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) 來調(diào)用 schema validator 方法。你可能會(huì)想到 JSON Schema validator 方法的返回類型是 JsonSchemaValidator, 怎么可以在 body(Matcher matcher) 方法調(diào)用呢。這是因?yàn)槎鄬永^承。 JsonSchemaValidator 類是間接實(shí)現(xiàn) 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"));}}上面的測(cè)試會(huì)成功,做一些改動(dòng)讓期望的 JSON Schema 驗(yàn)證失敗。
Adding extra required properties
上面 response 里只返回一個(gè)屬性 “token”,我們?cè)诩右粋€(gè)新的屬性 “nonExistingProperty” 在 JSON Schema “required” 部分:
失敗
從 log 里可以看出一個(gè)必要的字段 “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”,看看校驗(yàn)結(jié)果。
類型匹配失敗
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() 這個(gè)方法,否則會(huì)拋出 IllegalArgumentException 異常。
注意:前面提到 schema 文件放在 src/test/resources folder 下,其實(shí)你也可以將 schema 文件放在 src/main/resources folder 下。測(cè)試類可以放在 src/main/java 或 src/test/java,但是作為好的實(shí)踐標(biāo)準(zhǔn),我們最好將測(cè)試相關(guān)的類放在 src/test/java folder 下。最好在 pom.xml 添加依賴包時(shí)移除 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 下,我們就要用到另外一個(gè)靜態(tài)方法 matchesJsonSchema() ,需要傳一個(gè)完整的 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 方法的參數(shù)是一個(gè) File 對(duì)象,不是文件的完整路徑 string 類型。matchesJsonSchema() 期望的 JSON schema 是一個(gè) string 而不是一個(gè) 文件路徑的 string.
總結(jié)
總結(jié)
以上是生活随笔為你收集整理的REST Assured 55 - JSON Schema Validation In Rest Assured的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql执行计划中的temp_MYSQ
- 下一篇: 面试:整理面试中常被问到的8种数据结构