背景
某功能模塊的服務端主要功能是對接算法和前端,關鍵是保持二者數據結構一致,避免字段拼寫錯誤、字段類型錯誤等約定問題發生;(消費者驅動的測試)
服務端與算法不在一個團隊,不方便使用契約測試的pact框架;
故爲了保證算法輸出的質量,使用測試算法接口工具postman的tests功能;
接口類型爲REST;
目標:驗證數據結構、字段類型;
腳本示例
// Define the JSON Schema
const customerSchema = {
"properties": {
"errno": {
"type": "number"
},"errmsg": {
"type": "string"
},"data": {
"type": "array",
"items": {
"properties": {
"phone": {
"type": "string"
},"idcard": {
"type": "string"
},"imei": {
"type": "string"
},"idfa": {
"type": "string"
},"imsi": {
"type": "string"
},"bindTime": {
"type": "string"
}
}
}
}
}
};
// Test whether the response matches the schema
var customer = JSON.parse(responseBody);
tests["Customer is valid"] = tv4.validate(customer, customerSchema);
對應數據
{
"errno": 0,
"errmsg": "success",
"data": [{
"phone": "18600000000",
"idCard": "",
"imei": "",
"idfa": "",
"imsi": "",
"bindTime": "2019-05-23 00:08:21"
}, {
"phone": "18600000000",
"idCard": "",
"imei": "",
"idfa": "",
"imsi": "0123",
"bindTime": ""
}]
}
腳本說明
使用示例可參考:https://blog.getpostman.com/2017/07/28/api-testing-tips-from-a-postman-professional/
schema的定義見:https://json-schema.org/understanding-json-schema/reference/index.html