一般接口响应结果是json格式,所以可使用JSON Schema进行返回值字段的校验。
主要涉及的校验包括:
- 字段类型(type)
- 是否必须存在(required)
- 数值类型大小(minimum、maximum)
- 取值(const)
- array类型item个数(minItems、maxItems)
- ……
JSON Schema的简单例子
json数据如下:
{
"resultCode": "0",
"resultData": {
"access_token": "42ae7d01",
"token_type": "bearer",
"refresh_token": "f59dfdcf",
"expires_in": 81737,
"scope": "test"
},
"resultDesc": "success"
}
与此对应JSON Schema如下:
{
"type":"object",
"properties":{
"resultCode":{
"type":"string"
},
"resultData":{
"type":"object",
"properties":{
"access_token":{
"type":"string"
},
"token_type":{
"type":"string"
},
"refresh_token":{
"type":"string"
},
"expires_in":{
"type":"number"
},
"scope":{
"type":"string"
}
}
},
"resultDesc":{
"type":"string"
}
},
"required":["resultCode","resultData"]
}
注:推荐使用可自动生成JSON Schema的在线工具
如何通过代码进行校验呢?
在使用前,需在pom文件中添加依赖包
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
测试一下JsonSchemaFactory的功能,代码如下:
public static void main(String[] args){
String jsonStr="{\"resultCode\":\"0\",\"resultData\":{\"access_token\":\"42ae7d01\",\"token_type\":\"bearer\",\"refresh_token\":\"f59dfdcf\",\"expires_in\":81737,\"scope\":\"test\"},\"resultDesc\":\"success\"}";
String jsonSchema = "{\"type\":\"object\",\"properties\":{\"resultCode\":{\"type\":\"string\"},\"resultData\":{\"type\":\"object\",\"properties\":{\"access_token\":{\"type\":\"string\"},\"token_type\":{\"type\":\"string\"},\"refresh_token\":{\"type\":\"string\"},\"expires_in\":{\"type\":\"number\"},\"scope\":{\"type\":\"string\"}}},\"resultDesc\":{\"type\":\"string\"}},\"required\":[\"resultCode\",\"resultData\"]}";
JsonNode jsonStrNode = null;
JsonNode jsonSchemaNode = null;
try{
jsonStrNode = JsonLoader.fromString(jsonStr);
jsonSchemaNode = JsonLoader.fromString(jsonSchema);
}catch (IOException e){
e.printStackTrace();
}
ProcessingReport report = JsonSchemaFactory.byDefault().getValidator().validateUnchecked(jsonSchemaNode,jsonStrNode);
if(report.isSuccess()){
System.out.print("校验成功!");
}else{
System.out.print("校验失败!");
}
}
最后
为了可复用,我们可以编写校验的工具类,详见JSON数据格式校验
可在测试用例中添加以下校验代码:
String jsonStr = String.valueOf(response);
JsonSchema jsonSchema = new JsonSchema();
Boolean checkResult = jsonSchema.jsonSchemaCheck(jsonStr,System.getProperty("user.dir") + "\\json"+"\\tushengLogin.json");
Assert.assertTrue(checkResult);