You need to enable JavaScript to run this app. 如何为基于GraphQL SPQR的Spring Boot项目编写JUnit测试
优惠活动
大模型
产品
解决方案
定价
更多

如何为基于GraphQL SPQR的Spring Boot项目编写JUnit测试

SPQR GraphQL端点JUnit测试方案

SPQR实现的GraphQL端点完全兼容标准GraphQL HTTP请求规范,WebTestClient完全可以胜任测试工作,也可以选择SPQR专属的非Web测试方案,具体实现如下:

1 WebTestClient测试实现

GraphQL POST请求标准请求体包含三个字段:query(必填,查询/变更语句)、variables(可选,查询变量)、operationName(可选,操作名称),按照该格式构造请求即可,示例如下:

1.1 Query测试示例

import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.junit.jupiter.api.Test;
import java.util.Map;

@Test
void testUserQuery() {
    // 构造GraphQL查询语句
    String query = """
        query getUserById($userId: ID!) {
            getUser(id: $userId) {
                id
                name
                email
                createTime
            }
        }
        """;
    // 构造查询变量
    Map<String, Object> variables = Map.of("userId", "1001");
    // 组装请求体
    Map<String, Object> requestBody = Map.of(
        "query", query,
        "variables", variables
    );

    // 发送请求并校验结果
    webTestClient.post()
        .uri("/graphql") // 替换为你实际配置的SPQR端点路径
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(requestBody)
        .exchange()
        .expectStatus().isOk()
        // 校验无接口报错
        .jsonPath("$.errors").doesNotExist()
        // 校验返回字段符合预期
        .jsonPath("$.data.getUser.name").isEqualTo("测试用户")
        .jsonPath("$.data.getUser.email").isEqualTo("test@example.com");
}

1.2 Mutation测试示例

Mutation的请求构造逻辑和Query完全一致,仅需将查询语句中的query关键字替换为mutation即可:

@Test
void testCreateUserMutation() {
    String mutation = """
        mutation addNewUser($userInput: UserInput!) {
            createUser(input: $userInput) {
                id
                name
            }
        }
        """;
    Map<String, Object> userInput = Map.of(
        "name", "新用户",
        "email", "new@example.com",
        "age", 25
    );
    Map<String, Object> requestBody = Map.of(
        "query", mutation,
        "variables", Map.of("userInput", userInput)
    );

    webTestClient.post()
        .uri("/graphql")
        .contentType(MediaType.APPLICATION_JSON)
        .bodyValue(requestBody)
        .exchange()
        .expectStatus().isOk()
        .jsonPath("$.errors").doesNotExist()
        .jsonPath("$.data.createUser.name").isEqualTo("新用户");
}

1.3 常见注意事项

  • 端点路径需和SPQR配置保持一致,默认SPQR Starter的端点为/graphql,如果你自定义过graphql.spqr.http.endpoint配置,需替换为对应路径
  • 如果接口有权限校验,按照REST测试的逻辑在请求头中添加对应token、cookie即可
  • 如果查询不需要变量,可以省略variables字段,直接传递写死参数的query即可

2 SPQR专属单元测试方案

如果不需要验证完整的Web请求链路,仅需要测试GraphQL业务逻辑的正确性,可以直接注入SPQR自动配置的GraphQL实例直接执行查询,无需启动Web环境,执行速度更快:

import graphql.ExecutionResult;
import graphql.GraphQL;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
public class SpqrServiceTest {

    // SPQR自动配置的GraphQL实例可直接注入
    @Autowired
    private GraphQL graphQL;

    @Test
    void testQueryLogic() {
        String query = """
            query {
                listAllEnabledUsers {
                    id
                    name
                }
            }
            """;
        ExecutionResult result = graphQL.execute(query);
        
        // 校验执行无错误
        assertTrue(result.getErrors().isEmpty());
        // 自定义校验返回数据
        // List<Map> userList = (List<Map>) result.getData().get("listAllEnabledUsers");
        // assertEquals(10, userList.size());
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 00:57:02