You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Postman中引用通过{{$randomWord}}生成的随机词

问题:如何引用Postman中{{$randomWord}}生成的随机词以验证密钥完整性?

我有一个生成随机名称密钥的请求:

curl --location --request PUT 'https://apitest.backendless.com/A1DA5DF0-8D22-BAC4-FF56-9A0074DC9B00/8834B7F8-88BD-4472-9051-71BE31A3EE5B/hive/rootKeys/set/{{$randomWord}}' \
--header 'Content-Type: application/json' \
--data-raw '["123", true]'

该请求返回新密钥的长度,我已在测试脚本中验证返回的长度:

let response = pm.response.json();

pm.test("Created new key", () => {
    pm.expect(response, "Error").to.eql(2)
});

但我还需要验证该密钥的完整性(即确认密钥已按指定值创建),请问如何引用通过{{$randomWord}}生成的这个随机词?


解决方案

Postman的内置动态变量(如{{$randomWord}})每次调用都会生成新值,直接在测试脚本中引用会得到和请求里不同的随机词。要解决这个问题,需要提前生成并存储随机词,确保请求和验证使用同一个值:

  1. 在Pre-request Script中生成并存储随机词
    打开请求的「Pre-request Script」标签,添加以下代码,将生成的随机词保存到环境变量:

    // 生成随机词并存储到环境变量
    const randomKey = pm.variables.replaceIn("{{$randomWord}}");
    pm.environment.set("randomKey", randomKey);
    
  2. 修改请求URL使用存储的变量
    将请求URL中的{{$randomWord}}替换为{{randomKey}},确保请求使用的是预先生成的随机词:

    curl --location --request PUT 'https://apitest.backendless.com/A1DA5DF0-8D22-BAC4-FF56-9A0074DC9B00/8834B7F8-88BD-4472-9051-71BE31A3EE5B/hive/rootKeys/set/{{randomKey}}' \
    --header 'Content-Type: application/json' \
    --data-raw '["123", true]'
    
  3. 在测试脚本中验证密钥完整性
    修改测试脚本,读取存储的随机词,发起GET请求获取密钥内容并验证:

    let response = pm.response.json();
    
    pm.test("Created new key", () => {
        pm.expect(response, "Error").to.eql(2);
    });
    
    // 获取预存的随机密钥名称
    const randomKey = pm.environment.get("randomKey");
    
    // 发起请求验证密钥内容
    pm.sendRequest({
        url: `https://apitest.backendless.com/A1DA5DF0-8D22-BAC4-FF56-9A0074DC9B00/8834B7F8-88BD-4472-9051-71BE31A3EE5B/hive/rootKeys/get/${randomKey}`,
        method: "GET",
        header: {
            "Content-Type": "application/json"
        }
    }, (err, res) => {
        if (err) {
            pm.test("Failed to fetch key content", () => {
                throw new Error("GET request for key content failed: " + err.message);
            });
        } else {
            const keyContent = res.json();
            pm.test("Key content matches expected value", () => {
                pm.expect(keyContent).to.eql(["123", true]);
            });
        }
    });
    

内容的提问来源于stack exchange,提问作者Nazariy Dmytryshyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 02:54:36