微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

邮递员测试自动化-验证JSON数组响应

如何解决邮递员测试自动化-验证JSON数组响应

我有一个简单的api GET请求,响应主体如下所示。我正在使用Postman API自动功能,我想验证响应并使用Postman测试检查是否满足以下条件。

  1. 响应数组的大小应始终为2
  2. 在每个数组项中,“ build.time”值应为日期时间。
  3. 在每个数组项中,“ build.artifact”值应等于“ main_component”。
  4. 一个数组项的“ build.name”值应等于“ web app”
  5. 第二个数组项的“ build.name”值应等于“后端”。
[
    {
        "build.time": "2020-01-24 02:07:03 UTC","build.artifact": "main_component","build.name": "web app","build.version": "1.0.0"
    },{
        "build.time": "2019-07-10 15:26:18 UTC","build.name": "back-end","build.version": "1.0.1"
    }
]

解决方法

我很难克服这种UTC格式,因此我只是将其转换为字符串。做完了工作,但并不适合所有情况。

// Import moment.js for date validation
var moment = require('moment');

// Load response into object
const jsonData = pm.response.json();

// Test HTTP status code
pm.test("Check if HTTP status code is 200",() => {
pm.response.to.have.status(200);
});

// Check if response contains an array
pm.test("Check if response contains an array",() => {
pm.expect(jsonData).to.be.an("array");
});

// Response array size should always be 2
pm.test("Check if response array size is 2",() => {
pm.expect(Object.keys(pm.response.json()).length).to.eql(2);
});

// In each of the array item,the “build.time” value should be a date time.
pm.test("Check in each of the array item,the “build.time” value is of type datetime",() => {
pm.expect(jsonData[0]).to.have.property("build.time");
pm.expect(jsonData[1]).to.have.property("build.time");
});

// In each of the array item,the “build.time” value should be a date time.

// Get full timestamp
var timestamp = jsonData[0]["build.time"];

// Get time
var time = timestamp.substring(0,19);

// Get timezone
var timezone = timestamp.toString().substring(20);

// Test the time format
pm.test("Check in each of the array item,() => {
pm.expect(moment(new Date(time)).format("YYYY-MM-DD HH:mm:ss") == time);
});

pm.test("Timezone is valid",() => {
pm.expect(timezone).eql("UTC");
});

// In each of the array item,the “build.artifact” value should be equal to 
“main_component”.
pm.test("Check in each of the array item,the “build.artifact” value equals 
“main_component”",() => {
pm.expect(jsonData[0]["build.artifact"]).to.eql("main_component");
pm.expect(jsonData[1]["build.artifact"]).to.eql("main_component");
});

// “build.name” value of the 1st array item must equal to “web app”
pm.test("Check if “build.name” value of the 1st array item equals 'web app'",() => {
pm.expect(jsonData[0]["build.name"]).to.eql("web app");
});

// “build.name” value of the 2nd array item equals to “back-end”.
pm.test("Check if “build.name” value of the 2nd array item equals 'web app'",() => {
pm.expect(jsonData[1]["build.name"]).to.eql("back-end");
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。