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

如何在Cucumber中传递JSON数据至Step Definition及读取类路径JSON

在Cucumber中传递/读取复杂JSON测试REST API的方案

没问题,这两个需求Cucumber都能轻松搞定,我给你分两种常用方案详细说明,你可以根据场景选最合适的:

方案1:直接在Feature文件中嵌入JSON数据

如果你的JSON结构不算特别庞大,或者每个用例的JSON差异较大,直接把JSON写在Feature文件里会更直观。这里推荐用Cucumber的Doc String(三个反引号包裹)来处理多行JSON,可读性更好:

Feature文件示例

Feature: 测试用户创建API
  Scenario: 提交包含嵌套结构的用户数据
    Given 我准备了以下用户请求体
    """
    {
      "user": {
        "id": 1001,
        "name": "张三",
        "contact": {
          "phone": "13800138000",
          "email": "zhangsan@example.com"
        },
        "tags": ["VIP", "新用户"]
      }
    }
    """
    When 我调用POST接口 "/api/users"
    Then 接口返回状态码 201

Step Definition示例(Java)

Cucumber会自动把Doc String中的内容作为字符串参数传递给Step方法,你可以直接解析成JSON对象:

import io.cucumber.java.en.Given;
import org.json.JSONObject;
import io.restassured.RestAssured;

public class UserApiSteps {
    private JSONObject requestBody;

    @Given("我准备了以下用户请求体")
    public void prepareUserRequestBody(String jsonDocString) {
        // 将字符串解析为JSON对象
        this.requestBody = new JSONObject(jsonDocString);
        // 后续可以直接用RestAssured绑定请求体
        RestAssured.given().body(requestBody.toString());
    }
}

方案2:从Classpath中的JSON文件读取数据

如果JSON内容特别大、需要跨用例复用,或者想保持Feature文件简洁,推荐把JSON放在src/test/resources目录下(Maven/Gradle项目默认的classpath资源目录),然后在Step中读取。

第一步:放置JSON文件

把你的复杂JSON文件放到src/test/resources/api_data/目录下,比如命名为create_user_complex.json,内容就是你的测试JSON。

Feature文件示例

Feature: 测试用户创建API
  Scenario: 从文件加载复杂JSON提交请求
    Given 我加载classpath中的JSON文件 "api_data/create_user_complex.json" 作为请求体
    When 我调用POST接口 "/api/users"
    Then 接口返回状态码 201

Step Definition示例(Java)

通过类加载器读取classpath中的文件,解析成JSON:

import io.cucumber.java.en.Given;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class UserApiSteps {
    private JSONObject requestBody;

    @Given("我加载classpath中的JSON文件 {string} 作为请求体")
    public void loadJsonFromClasspath(String filePath) throws IOException {
        // 通过类加载器获取文件输入流
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filePath);
        if (inputStream == null) {
            throw new IllegalArgumentException("找不到指定的JSON文件: " + filePath);
        }
        // 将流转换为字符串
        String jsonContent = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
        // 解析为JSON对象
        this.requestBody = new JSONObject(jsonContent);
    }
}

如果你的项目用了Spring,也可以用ClassPathResource来简化读取:

import org.springframework.core.io.ClassPathResource;

// 替换上面的流读取部分
ClassPathResource resource = new ClassPathResource(filePath);
String jsonContent = new String(resource.getInputStream().readAllBytes(), StandardCharsets.UTF_8);

额外提示

如果需要把JSON映射为Java实体类(比如用Jackson),可以在读取字符串后直接转换:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();
UserCreateRequest userRequest = objectMapper.readValue(jsonContent, UserCreateRequest.class);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:54:42