【问题标题】:Postman test to parse json response body and validate there are no duplicate values in arrayPostman 测试解析 json 响应正文并验证数组中没有重复值
【发布时间】:2020-05-14 02:32:30
【问题描述】:

我想在 Postman 中编写一个测试来验证对象数组中没有重复值。这是一个示例响应:

{
    "customerNumber": "123",
    "customCategories": [
        {
            "customCategoryID": "1546",
            "customCategoryDesc": "7100",
            "itemNumbers": [
                "7205",
                "1834"
            ]
        },
        {
            "customCategoryID": "1547",
            "customCategoryDesc": "7130",
            "itemNumbers": [
                "2251",
                "9832"
            ]
        },
        {
            "customCategoryID": "1548",
            "customCategoryDesc": "7315",
            "itemNumbers": [
                "1225541",
                "1197233"
            ]
        },
        {
            "customCategoryID": "1546",
            "customCategoryDesc": "7100",
            "itemNumbers": [
                "7205",
                "1834"
            ]
        },
    ]
}

如您所见,“customCategoryID”:“1546”被重复;因此我希望测试失败并显示此响应,并显示重复的 customCategoryID 值(“1546”)。

我在这个question 和这个question 中查看了几个答案,但是需要使用 Postman 的最新测试脚本语法更新了他们的 JS 库以及对重复数据的断言。

非常感谢您的帮助。

【问题讨论】:

    标签: validation duplicates automated-tests postman


    【解决方案1】:

    您可以尝试这样的方法来检查重复的 id:

    function checkIfArrayIsUnique(array) {
      return array.length === new Set(array).size;
    }
    
    pm.test('Check is Ids are unique', () => {
        let ids = []
        _.each(pm.response.json().customCategories, (item) => {
            ids.push(item.customCategoryID)
        })
    
        pm.expect(checkIfArrayIsUnique(ids), ids).to.be.true
    })
    

    它循环遍历customCategories 数组中每个对象的customCategoryID 属性,并将该值存储在ids 数组中。

    checkIfArrayIsUnique 函数使用ids 数组并使用Set 方法来帮助进行比较。

    Set 方法从 ids 数组中创建一个新对象,该对象仅包含唯一值,因此它会检查 ids 数组长度是否与新的 Set 大小匹配,这将返回 true 或 false。

    有一个基本的pm.expect() 语句来检查checkIfArrayIsUnique 函数是否返回true,如果它不是唯一的,它将返回false 并且测试失败。

    【讨论】:

    • 可以通过map生成Ids列表:let ids = pm.response.json().map(item => item.customCategories)
    猜你喜欢
    • 2020-12-16
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2016-05-01
    • 2019-01-29
    • 1970-01-01
    相关资源
    最近更新 更多