是否可以在 pm.test() 中包含多个 pm.test()

时间:2021-01-25 09:49:01

标签: api testing postman

在一个 pm.test() 中可以有多个 pm.test() 吗?这样,如果任何内部 pm.test() 失败,外部 pm.test() 也将失败。如果没有内部 pm.test() 失败,则外部 pm.test() 通过。

我的要求类似于 pm.expect() 的工作方式。但我想改用 pm.test() 以便我可以在“测试结果”选项卡中查看每个测试的状态。

我的代码如下。

var response = pm.response.json()
pm.test("Test scenario 1", ()=> {
    
    pm.test("Checking response code", ()=> {
        pm.expect(response.code).to.eql(200);
    });
    
    pm.test("Checking response message", ()=> {
        pm.expect(response.message).to.eql('OK');
    });
   
    //more pm test
});

非常感谢。

2 个答案:

答案 0 :(得分:1)

pm.test("Test scenario 1", ()=> {
    
    pm.test("Checking response code", ()=> {
        pm.expect(pm.response.code).to.eql(200);
    });
    
    pm.test("Checking response message", ()=> {
        pm.expect(pm.response.status).to.eql('5OK');
    });
   
    //more pm test
});

你可以,但输出只会显示三个测试,内部测试的结果不会影响外部抽象

enter image description here

简而言之,您可以,但它不会像您一样提供行为

答案 1 :(得分:0)

通过实施一些 counter 我能够实现我想要的。我在内部 counter 的末尾增加了 pm.test()。如果 pm.expect() 失败,则 counter 不会递增。

当所有内部 pm.test() 完成后,我将 counter+1pm.test.index() 进行比较。如果它们相等,我什么都不做(基本上通过外部 pm.test())。如果它们不相等,我抛出 pm.expect.fail()

注意:pm.test.index() 返回在该时间点执行的测试数。

pm.test("To test able to do that", () => {
    let numberOfPassedTest = 0;
    
    pm.test("This test will pass", () => {
        //put assertion here
        pm.expect(200).to.eql(200)
        numberOfPassedTest += 1;
    });
    
    pm.test("This test will fail", () => {
        pm.expect(200).to.eql(201)
        numberOfPassedTest += 1; // this line is not executed because the previous line (pm.expect()) failed.
    });
    
    
    if(pm.test.index() === numberOfPassedTest+1){
        //do nothing. meaning no test failed and the whole pm.test() will be passed
    } else {
        pm.expect.fail("At least one of the tests failed. So this test case is marked as failed.");
    }
});

失败的示例结果: enter image description here

相关问题