目錄:
1迹蛤、斷言請求結(jié)果的某個字段值
2、匿名JSON根節(jié)點驗證
3、Json Schema Validation斷言json結(jié)構(gòu)是否復(fù)合規(guī)范
4盗飒、不使用rest-assured的Json Schema Validation
一嚷量、斷言請求結(jié)果
若有如下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]
}]
}
}
如果想要判斷l(xiāng)ottoId的值是否等于5,可以這樣做:
get("/lotto").then().body("lotto.lottoId", equalTo(5));
想要檢查winnerId的取值包括23和54:
get("/lotto").then().body("lotto.winners.winnerId", hasItems(23, 54));
注意: equalTo 和 hasItems 是 Hamcrest matchers的方法逆趣,所以需要靜態(tài)導(dǎo)入 org.hamcrest.Matchers蝶溶。
二、匿名JSON根節(jié)點驗證
若存在JSON文件中根節(jié)點名稱不確定的情況下宣渗,可以使用$
或者空格字符串作為路徑來識別抖所,例如有JSON如下:
[1,2痕囱,3]
驗證方法如下:
when().
get("/json").
then().
body("$", hasItems(1, 2, 3));
三田轧、斷言json結(jié)構(gòu)是否復(fù)合規(guī)范
step1:
生成schema.json文件,放置在classpath中(idea的話可以放在resources目錄下)鞍恢。
step2:
在pom.xml文件下添加maven依賴
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>3.0.1</version>
</dependency>
step3:
matchesJsonSchemaInClasspath
靜態(tài)導(dǎo)入自 io.restassured.module.jsv.JsonSchemaValidator
推薦從這個類中靜態(tài)導(dǎo)入所有的方法
step4:
// Given
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.newBuilder().setValidationConfiguration(ValidationConfiguration.newBuilder().setDefaultVersion(DRAFTV4).freeze()).freeze();
// When
get("/products").then().assertThat().body(matchesJsonSchemaInClasspath("products-schema.json").using(jsonSchemaFactory));
四傻粘、不使用rest-assured的Json Schema Validation
您也可以在不依賴rest-assured的情況下使用json-schema-validator module。如想要把json文本表示為String類型的字符串有序,可以這樣做:
import org.junit.Test;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.MatcherAssert.assertThat;
public class JsonSchemaValidatorWithoutRestAssuredTest {
@Test
public void validates_schema_in_classpath() {
// Given
String json = ... // Greeting response
// Then
assertThat(json, matchesJsonSchemaInClasspath("greeting-schema.json"));
}
} ```