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

如何用Rest Assured编写含Headers与JSON请求体的Cucumber POST请求Step Definition

问题描述

我正尝试在Cucumber步骤定义类中编写执行POST请求的代码,该请求需在请求头中包含授权(Bearer Token)、Content-Type和Cookie,同时携带JSON格式的请求体。
我已完成Bearer Token的获取流程,将其用作授权头,Content-Type设为application/json,请求体结构如图所示。
我不确定如何用Rest Assured实现该需求,以下是已实现的@Given方法,它会根据环境设置Base URI和Bearer Token,后续执行POST请求时需使用该Token作为授权头:

@Given("Request the environment for the Master API {string}")
public void getMasterAPIBaseUrl(String region) throws JSONException {
    if (region.equalsIgnoreCase("DEV")) {
        bearerToken = accTokenSetup.accessTokenSetup(region);
        RestAssured.baseURI = urlProps.getProperty("devMasterAPIUrl");
    }
    else if (region.equalsIgnoreCase("STG")) {
        bearerToken = accTokenSetup.accessTokenSetup(region);
        RestAssured.baseURI = urlProps.getProperty("stgMasterAPIUrl");
    }
    Reporter.log("Getting master api base url for the environment which is " + RestAssured.baseURI, true);
}

现在我需要一个@When步骤来执行上述POST请求,包含指定的请求体、请求头(授权、Content-Type、Cookie),我知道需要端点、请求头、请求体等信息,但不知如何推进,恳请提供帮助。

解决方案

完整@When步骤实现

首先在步骤定义类中添加成员变量存储响应,方便后续断言使用:

private Response postResponse;

然后编写@When步骤代码:

@When("Send POST request to endpoint {string} with required headers and request body")
public void sendPostRequest(String endpoint) throws JSONException {
    // 1. 构造JSON请求体(根据实际业务结构调整字段)
    JSONObject requestBody = new JSONObject();
    requestBody.put("username", "test_user");
    requestBody.put("age", 30);
    // 嵌套结构示例
    JSONObject profile = new JSONObject();
    profile.put("address", "test address");
    profile.put("phone", "1234567890");
    requestBody.put("profile", profile);

    // 2. 发送POST请求并提取响应
    postResponse = given()
            // 设置Bearer Token授权头
            .header("Authorization", "Bearer " + bearerToken)
            // 设置Content-Type
            .header("Content-Type", "application/json")
            // 设置Cookie:单个Cookie用cookie(key, value),多个Cookie用header("Cookie", "key1=val1; key2=val2")
            .cookie("csrfToken", "your-csrf-token-value")
            // 传入构造好的请求体
            .body(requestBody.toString())
        .when()
            // 发送请求到指定端点
            .post(endpoint)
        .then()
            // 打印响应日志用于调试
            .log().all()
            // 提取响应对象供后续断言使用
            .extract().response();

    Reporter.log("POST request sent to: " + RestAssured.baseURI + endpoint, true);
}

关键细节说明

  • 请求体构造:使用org.json.JSONObject构建符合要求的JSON结构,字段和层级完全匹配你的实际接口要求即可;如果请求体过于复杂,也可以直接传入预定义的JSON字符串(比如从本地文件读取)。
  • 请求头配置:
    • 授权头直接拼接Bearer 和已获取的bearerToken变量;
    • Content-Type固定设置为application/json;
    • Cookie支持单个添加(.cookie(key, value))或通过Cookie请求头批量添加多个Cookie。
  • 响应存储:提取的Response对象可以在后续@Then步骤中验证状态码、响应体字段等内容。

示例断言步骤(可选)

@Then("Verify POST response status code is {int}")
public void verifyStatusCode(int expectedCode) {
    postResponse.then().statusCode(expectedCode);
    Reporter.log("Status code verified: " + expectedCode, true);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:45:34