更新时间:2024-04-10 GMT+08:00
分享

后置脚本

后置脚本是在请求发送后执行的代码片段,主要用于验证请求返回的结果(断言)、将请求返回的结果数据写入环境变量等场景。可以在接口的“后置脚本”页面中单击“添加后置操作”,发送接口请求后将自动运行后置脚本。

断言

可以利用后置脚本验证API响应返回结果的正确性。

// 示例1:pm.response.to.have
pm.test('Response status is 200', function() {
  pm.response.to.have.status(200);
});

// 示例2:pm.expect()
pm.test('this is production', function() {
  pm.expect(pm.environment.get('env')).to.equal('production');
});

// 示例3:response assertions
pm.test('no error', function() {
  pm.response.to.not.be.error;
  pm.response.to.have.jsonBody('');
  pm.response.to.not.have.jsonBody('error');
});

// 示例4:pm.response.to.be* 
pm.test('no error', function() {
  // 断言结果:info, success, redirection, clientError,  serverError, are other variants
  pm.response.to.be.ok;
  // 断言有body,并且是json格式
  pm.response.to.be.withBody;
  pm.response.to.be.json;
});

后置脚本与前置脚本具备相同能力,包括:打印日志、操作变量、发送请求、编写并执行复杂的JS函数等。

分享:

    相关文档

    相关产品