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

GCP Cloud Function Java集成测试如何在请求体传入name参数

实现方案

你当前的测试使用GET请求发送,默认不会携带请求体,因此无法触发函数从JSON请求体读取name参数的逻辑,只需将测试请求修改为带JSON请求体的POST请求即可,修改后的测试代码如下:

@Test
void helloHttp_shouldRunWithFunctionsFramework() throws Throwable {
    String functionUrl = BASE_URL + "/helloHttp";
    // 构造带name参数的JSON请求体
    String requestBody = "{\"name\": \"David\"}";
    // 改为POST请求,设置JSON格式头并携带请求体
    HttpRequest postRequest = HttpRequest.newBuilder()
        .uri(URI.create(functionUrl))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8))
        .build();

    RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
        .maxAttempts(6)
        .intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2))
        .retryExceptions(IOException.class)
        .retryOnResult(body -> body.toString().length() == 0)
        .build());
    Retry retry = registry.retry("my");

    String body = Retry.decorateCheckedSupplier(retry, () -> client.send(
        postRequest,
        HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)).body()
    ).apply();
    // 修改断言匹配预期返回结果
    assertThat(body).isEqualTo("Hello David!");
}

核心改动说明

  • 把原GET请求替换为POST请求,HTTP协议中GET请求通常不携带请求体,POST是提交请求体的标准方式
  • 添加Content-Type: application/json请求头,通知云函数请求体为JSON格式,避免解析异常
  • 构造包含name字段的JSON请求体,通过HttpRequest.BodyPublishers.ofString传入请求
  • 修改断言逻辑,匹配期望返回的问候语

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:42:01