邮递员测试-自动化测试

时间:2020-01-23 07:57:00

标签: json postman

如何编写 Postman 测试,以检查我的响应正文是否包含nets": {"4": "1"}? 我很难将此"parameter_list": { "2": ...部分放入pm.expect()中。 “ parmeter_list”可以包含许多名称为“ number”的对象

{
    "request_id": 358624578,
    "product_list": [
        {
            "symbol": "AX-174",
            "value_ids": [
                271,
                1437038,
                .
                .
                .
                1757620
            ],
            "id": 65869
        }
    ],
    "do_show": true,
    "do_show_list": {
        "do_show_products": true,
        "do_show_parameters": true,
        "do_show_parameter_values": true,
        "do_show_flags": false
    },
    "parameter_list": {
        "2": {
            "value_type_id": 0,
            "name_full_txt": "Producent",
            "unit_text": null,
            "product_count": 1,
            "nets": {
                "3": "1"
            },
            "pos": 0,
            "id": 2
        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果您只需要针对 parameter_list 中的“ 2”键进行测试,则建议采取以下解决方案:

const jsonBody = pm.response.json();
const parameterList = jsonBody.parameter_list["2"];
const nets = {
    "nets": {
        "4": "1"
    }
};

pm.test("check parameter '2' contains nets",  () => pm.expect(parameterList).to.deep.include(nets));

我相信,您可以轻松修改netsparameterList来匹配您的实际情况。

编辑: 如果您需要遍历 parameter_list 中的所有对象,则可以在测试中使用for..in循环:

const jsonBody = pm.response.json();
const nets = {
    "nets": {
        "3": "1"
    }
};

pm.test("check all parameters contains nets",  () => {
    for(let parameter in jsonBody.parameter_list) {
        pm.expect(jsonBody.parameter_list[parameter]).to.deep.include(nets);
    }
});

或者为了提高可读性,请使用tests[]

for(let parameter in jsonBody.parameter_list) {
    tests[`Check 'nets' object is in ${parameter} parameter`] = pm.expect(jsonBody.parameter_list[parameter]).to.deep.include(nets);
}

答案 1 :(得分:0)

为了添加到@n-verbitsky 接受的答案,邮递员在请求的“测试”选项卡中提供了测试片段。有关 Postman 中的测试以及如何编写测试脚本的更多信息可以从他们的文档中获取:learning center

我认为展示您已经编写的测试代码会有所帮助。

enter image description here