【问题标题】:Does Postman support controlling format of request body?Postman 是否支持控制请求体的格式?
【发布时间】:2019-01-20 16:43:55
【问题描述】:

我正在考虑使用 Postman 来自动化我的 REST API 测试,并且只使用了几天。到目前为止,我已经为我的初始集合创建了足够数量的请求。我也在我的请求前脚本、测试和请求正文中使用了全局变量、环境变量和集合变量。我希望控制请求中包含哪些属性,而无需制作同一请求的多个副本以排除某些属性。

例如,我有一个 JSON 请求正文:

{
    "Username": "{{Username}}",
    "Password": "{{Password}}",
    "AnotherProperty": ""
}

如果“AnotherProperty”为 null 或为空,我想从请求中完全删除该属性。我只希望“AnotherProperty”包含在请求中,如果它有一个值。因此,如果为 null 或为空,则请求应显示为:

{
    "Username": "{{Username}}",
    "Password": "{{Password}}"
}

我发现完成此操作的唯一方法是保存集合中带有和不带有属性的单独请求,但是当有许多属性时,对请求中的每个属性执行此操作似乎并不有效。是否可以控制请求中包含的属性,如果它们的值为 null 或为空?

【问题讨论】:

    标签: json rest testing automation postman


    【解决方案1】:

    如果您有来自先前请求的 JSON 请求正文,请将其保存为 environment variable。然后您可以更新您计划在主请求的pre-request script 中发送的正文,或更新前面请求的test script 中的正文。

    然后在主请求中,您可以使用{{variableName}} 语法将正文发送为raw

    预请求脚本示例:

    // retrieve the environment variable
    let potentialBody = JSON.parse(pm.environment.get("bodyToSend"));
    
    // remove the property if empty
    if (potentialBody.AnotherProperty === "") {
        delete potentialBody.AnotherProperty;
    } 
    
    // re-save the environment variable so it can be used in the primary request
    pm.environment.set("bodyToSend", JSON.stringify(potentialBody));
    

    正文示例(选择原始):

    {{bodyToSend}}
    

    【讨论】:

    • 谢谢,我试试看!
    猜你喜欢
    • 2021-12-31
    • 2018-10-13
    • 2021-07-25
    • 2020-04-22
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多