ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
`Postman`的断言实际上就是往全局对象`tests`添加键值对。它的`key`会显示在报告界面上,`value`是可以解析为`boolean`的表达式。如果得出的值是true,在报告里就会显示为成功,`false`失败。 ## **创建断言** ![](https://img.kancloud.cn/a1/c9/a1c9fcf109af227c8a758744b455f7eb_1920x1030.png) ## **语法** * 环境变量 ~~~ // 获取 pm.environment.get("variable_key"); // 设置 pm.environment.set("variable_key", "variable_value"); // 清除 pm.environment.unset("variable_key"); ~~~ * 集合变量 ~~~ // 获取 pm.collectionVariables.get("variable_key"); // 设置 pm.collectionVariables.set("variable_key", "variable_value") // 清除 pm.collectionVariables.unset("variable_key") ~~~ * 全局变量 ~~~ // 获取 pm.globals.get("variable_key"); // 设置 pm.globals.set("variable_key", "variable_value"); // 清除 pm.globals.unset("variable_key"); ~~~ * 在环境变量和集合变量和全局变量中搜索变量 ~~~ pm.variables.get("variable_key"); ~~~ * 检查响应主体是否包含字符串 ~~~ pm.test("Body matches string", function () { pm.expect(pm.response.text()).to.include("string_you_want_to_search"); }); ~~~ * 检查响应主体是否等于字符串 ~~~ pm.test("Body is correct", function () { pm.response.to.have.body("response_body_string"); }); ~~~ * 检查JSON值 ~~~ pm.test("Your test name", function () { var jsonData = pm.response.json(); pm.expect(jsonData.value).to.eql(100); }); ~~~ * 存在Content-Type标头 ~~~ pm.test("Content-Type header is present", function () { pm.response.to.have.header("Content-Type"); }); ~~~ * 响应时间小于200ms ~~~ pm.test("Response time is less than 200ms", function () { pm.expect(pm.response.responseTime).to.be.below(200); }); ~~~ * 状态码为200 ~~~ pm.test("Status code is 200", function () { pm.response.to.have.status(200); }); ~~~ * 成功的POST请求状态代码 ~~~ pm.test("Successful POST request", function () { pm.expect(pm.response.code).to.be.oneOf([201,202]); }); ~~~