如何编写邮递员测试来比较响应json与另一个json?

时间:2017-08-10 14:04:43

标签: javascript json postman

运行Rest API的postMan测试后,我有以下json响应:

"string"

现在我想将上面的json与预定义的json进行比较。说,它与上面相同。

如何通过Postman测试比较两个jsons?

7 个答案:

答案 0 :(得分:1)

您可以在Postman的Tests选项卡中编写javascript代码。只需编写简单的代码即可比较并检查测试中的结果。

var serverData = JSON.parse(responseBody);
var JSONtoCompare = {}; //set your predefined JSON here.
tests["Body is correct"] = serverData === JSONtoCompare;

答案 1 :(得分:1)

您可以将此代码粘贴到集合或单个请求测试标签中。

此代码的作用是使用该请求的键将请求保存到全局变量中。您可以更改环境并按相同的请求,如果响应不同,则测试将失败。

const responseKey = [pm.info.requestName, 'response'].join('/');
let res = '';
try {
    res = JSON.stringify(pm.response.json());
} catch(e) {
    res = pm.response.text();
}

if (!pm.globals.has(responseKey)) {
    pm.globals.set(responseKey, res);
} else {    
    pm.test(responseKey, function () {
        const response = pm.globals.get(responseKey);
        pm.globals.unset(responseKey);
        try {
            const data = pm.response.json();
            pm.expect(JSON.stringify(data)).to.eql(response);
        } catch(e) {
            const data = pm.response.text();
            pm.expect(data).to.eql(response);
        }
    });
}

希望获得帮助。

答案 2 :(得分:1)

一段时间后我明白了。在您的请求中添加测试,并使用Runner运行集合中的所有请求。

邮递员信息:Mac版7.10.0。

测试脚本:

pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.eql({
        "key1": "value1",
        "key2": 100
    });
});

答案 3 :(得分:0)

POSTMAN: Comparing object Environment variable with response's object看来问同样的问题,该问题还列出了一个有效的解决方案,即使用JSON.stringify()objects转换为strings,然后比较字符串。

答案 4 :(得分:0)

除了我的JSON还包含对象数组之外,我还有一个类似的问题要解决。我使用了以下技术,可以对问题中的简单字符串数组进行修改。我创建了一个名为“ assert”的全局函数数组,其中包含诸如“ areEqual”和“ areArraysOfObjectsEqual”之类的辅助函数并将其保存在测试顶部文件夹中的“测试”标签。

msg.payload.pattern

您的“测试前脚本”将设置您期望的对象

assert = {
    areEqual: (actual, expected, objectName) => {
        pm.test(`Actual ${objectName} '` + actual + `' matches Expected ${objectName} '` + expected + `'`, () => {
            pm.expect(_.isEqual(actual, expected)).to.be.true;
        });
    },
    areArraysOfObjectsEqual: (actual, expected, objectName) => {
        if (!_.isEqual(actual, expected)) {

            // Arrays are not equal so report what the differences are
            for (var indexItem = 0; indexItem < expected.length; indexItem++) {
                assert.compareArrayObject(actual[indexItem], expected[indexItem], objectName);
            }
        }
        else
        {
            // This fake test will always pass and is just here for displaying output to highlight that the array has been verified as part of the test run
            pm.test(`actual '${objectName}' array matches expected '${objectName}' array`);
        }
    },
    compareArrayObject: (actualObject, expectedObject, objectName) => {
        for (var key in expectedObject) {
            if (expectedObject.hasOwnProperty(key)) {
                assert.areEqual(expectedObject[key], actualObject[key], objectName + " - " + key);
            }
        }
    }
};

您的测试将单独或在阵列级别测试每个项目,如下所示:

 const expectedResponse =
    {
        "id": "3726b0d7-b449-4088-8dd0-74ece139f2bf",
        "array": [
            {
                "item": "ABC",
                "value": 1
            },
            {
                "item": "XYZ",
                "value": 2
            }
        ]
    };

    pm.globals.set("expectedResponse", expectedResponse); 

该技术将提供出色的“属性名称实际值与期望值匹配”输出,并且可以将对象数组作为要比较的JSON的一部分。

更新: 要测试字符串数组“ GlossSeeAlso”,只需在任何测试中调用提供的全局帮助器方法,如下所示:

const actualResponse = JSON.parse(responseBody);
const expectedResponse = pm.globals.get("expectedResponse");

assert.areEqual(
    actualResponse.id,
    expectedResponse.id,
    "id");

assert.areArraysOfObjectsEqual(
    actualResponse.myArray,
    expectedResponse.myArray,
    "myArrayName");

可以像这样测试JSON键值对中的原始类型:

assert.compareArrayObject(
    actualResponse.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso,       
    expectedResponse.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso,
    "glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso");

答案 5 :(得分:0)

我遇到了同样的问题,试图测试两个不同API的输出是否相同。基本的断言将不起作用,因为JSON对象不能保证元素的顺序。

this question on StackOverlow开始,并意识到Lodash被烘焙到Postman沙箱中-Postman Sandbox API reference-两种JSON来源的基本测试可以很简单:

    pm.test("compare responses", function () { 
   let identical = _.isEqual(pm.response.json(), pm.globals.get("response_json"));
   pm.expect(identical).to.equal(true);
});

全局JSON可以由您直接设置,也可以在之前的请求中设置。

答案 6 :(得分:-1)

在“测试”部分下编写JavaScript代码。有关详细信息,请参阅以下链接。

Click Here