我认为这是一个很好的问题,除了我很好奇,所以我做了一些研究并找到了解决方法。这有点复杂。我不确定是否值得。
首先,Postman Mock Server(简称 Mock Server)无法执行任何测试和预脚本,因此它无法计算事物。你需要在这里计算,你要怎么做?好吧,您可以定义一个environment
for Mock Server,它使您能够在模拟响应中使用动态值。
我将继续一步一步地展示这个过程。
1 - 打开一个带有环境的模拟服务器:
1.1 - 为新的 Mock Server 创建一个集合:

您的模拟响应将如下所示:
{"due_date": "{{date}}"}
1.2 - 创建环境:

1.3 - 完成创建:

1.4 - 完成后,Postman 会创建一个如下所示的集合:

1.5 - 你可以从这个集合中测试你的模拟服务器:

如您所见,Mock Server 在其响应中使用环境变量。
现在,我们必须弄清楚如何更新环境变量。
您必须使用外部服务来更新您的环境变量。您可以将 Postman Monitor 用于此作业,因为它可以执行测试(意味着任何代码)并且像 CRON 作业一样工作,这意味着您可以将 Postman Monitor 设置为每 24 小时更新一次特定的环境变量。
2 - 打开 Postman Monitor 以更新您的环境:
2.1 - 这一步非常简单,创建一个 Postman Monitor 如下配置:

2.2 - 编写测试以更新环境:

测试将如下所示:
// you have to use pm.test() otherwise Postman Monitor not execute the test
const moment = require("moment");
pm.test("update date", () => {
// set date 2 days past
let startdate = moment();
const dayCount = 2;
startdate = startdate.subtract(dayCount, "days");
startdate = startdate.format("YYYY-MM-DD");
// this is not work on Postman Monitor, use Postman API like below
//pm.environment.set('date', startdate);
const data = JSON.stringify({
environment: {
values: [
{
key: "date",
value: startdate,
},
],
},
});
const environmentID = "<your-environment-id>";
// Set environment variable with Postman API
const postRequest = {
url: `https://api.getpostman.com/environments/${environmentID}`,
method: "PUT",
header: {
"Content-Type": "application/json",
"X-API-Key":
"<your-postman-api-key>",
},
body: {
mode: "raw",
raw: data,
},
};
pm.sendRequest(postRequest, (error, response) => {
console.log(error ? error : response.json());
// force to fail test if any error occours
if (error) pm.expect(true).to.equal(false);
});
});
pm.environment
使用 Postman Monitor 时无法更改环境变量。您应该在测试中使用 Postman API pm.sendRequest
。
您需要获取 Postman API 密钥并且需要了解您的环境 ID。您可以从 Postman API 中了解环境 id。
要了解您的环境 ID,请使用此端点:https ://www.postman.com/postman/workspace/postman-public-workspace/request/12959542-b7ace502-4a5a-4f1c-8164-158811bbf236
要了解如何获取 Postman API 密钥:https ://learning.postman.com/docs/developer/intro-api/#generating-a-postman-api-key
2.3 - 手动运行 Postman Monitor 以确保测试正常工作:

2.4 - 如您所见,Postman Monitor 执行脚本:

2.5 - 当我检查环境时,我可以看到结果:

您可以从浏览器测试以查看结果:
