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

Spring Boot GraphQLTester文件上传测试:如何设置表单数据?

解决GraphQlTester测试GraphQL文件上传的方法

要通过GraphQlTester实现GraphQL文件上传测试,需要利用其multipart请求支持,模拟curl请求中表单数据的结构,具体步骤如下:

1. 准备测试文件资源

首先加载测试用的文件,通过ClassPathResource读取src/test/resources下的文件,包装为PartSource(Spring处理multipart请求的标准资源接口):

import org.springframework.core.io.ClassPathResource;
import org.springframework.http.codec.multipart.ResourcePartSource;
import org.springframework.http.codec.multipart.PartSource;

// 加载src/test/resources目录下的test.txt文件
PartSource testFilePart = new ResourcePartSource("0", new ClassPathResource("test.txt"));

2. 构建GraphQL请求并绑定文件

在测试代码中,通过GraphQlTester的multipart()方法将文件与GraphQL变量绑定,同时给变量设为null(对应curl请求中variables.file: null的占位逻辑):

@GraphQlTest(FileController.class)
@Import({GraphQLTestConfiguration.class})
class FileGraphQLControllerTest {

    @Autowired
    private GraphQlTester graphQlTester;

    @Test
    void testSingleFileUpload() {
        String mutation = """
            mutation ($file: Upload!) {
                singleUpload(file: $file)
            }
        """;

        PartSource testFilePart = new ResourcePartSource("0", new ClassPathResource("test.txt"));

        graphQlTester.document(mutation)
                .variable("file", null) // 变量仅作为占位,实际文件通过multipart传递
                .multipart("variables.file", testFilePart) // 将multipart文件与GraphQL变量绑定
                .execute()
                .path("singleUpload")
                .get(); // 获取返回结果,或用verify()验证请求执行成功
    }
}

关键说明

  • multipart("variables.file", testFilePart):对应curl请求中的map: {"0": ["variables.file"]},实现multipart文件部分与GraphQL变量$file的映射。
  • variable("file", null):符合GraphQL文件上传的规范,变量仅作为占位标识,实际文件内容通过multipart表单传递。
  • 确保测试文件存在于src/test/resources目录下,若文件路径不同,调整ClassPathResource的参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:46:01