[英]RestAssured - want to verify the body structure of JSON response in RestAssured
當我請求 GET 請求時,我得到 JSON 響應,但這里我的要求是驗證響應主體的結構。
例如:
{
"lotto":{
"lottoId":5,
"winning-numbers":[2,45,34,23,7,5,3],
"winners":[
{
"winnerId":23,
"numbers":[2,45,34,23,3,5]
},
{
"winnerId":54,
"numbers":[52,3,12,11,18,22]
}
]
}
}
上面的響應有結構,所以我需要驗證結構而不是一個鍵值對,我怎么能做到這一點?
最好的方法是驗證 json-schema 匹配。
首先,您需要將此依賴項添加到您的 pom.xml
<!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>3.3.0</version>
<scope>test</scope>
</dependency>
然后你需要創建一個文件 json-schema-your-name.json ,其結構如下:
{
"type": "object",
"properties": {
"data": {
"type": "array",
"items": {
"type": "object",
"properties": {
"flow_id": {
"type": "string",
"minLength": 36,
"maxLength": 36
},
"flow_org_id": {
"type": "string"
}
},
"required": [ "flow_id", "flow_org_id" ]
}
}
}
}
有一堆服務生成基於 json 的模式 - 例如 - 這個
模式文件准備好后,您需要以字符串格式提供文件的路徑 - 例如 -
private static final String GET_SUBSCRIPTION_JSON_SCHEMA_PATH =
"json/schemas/GetSubscriptionByIdSchema.json";
並調用matchesJsonSchemaInClasspath("your/path/to/json-schema")
方法進行斷言。
升級版:
所以流程基本上是這樣的:
實際上,它將如下所示:
@Test
public void someTestMethod() {
Response responseToValidate = // here you should assign and store returned response
responseToValidate
.assertThat()
.statusCode(200)
.body("json.path.to.needed.key", equalTo("123"))
.body(matchesJsonSchemaInClasspath("path/to/your/schema/in/string/format")); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.