测试中GraphQlTester无法自动注入,调用时触发空指针异常
排查GraphQlTester注入为null的问题
出现的错误:
Error: Cannot invoke "org.springframework.graphql.test.tester.GraphQlTester.document(String)" because "this.graphQlTester" is null
已确认相关jar包存在,但开启root级别的debug日志后,仍未发现GraphQlTester的自动注入操作,测试代码如下:
package com.reports.controller; import com.reports.entity.ReportDetails; import com.reports.service.ReportDetailsService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.graphql.GraphQlTest; import org.springframework.context.annotation.Import; import org.springframework.graphql.test.tester.GraphQlTester; @Import(ReportDetailsService.class) @GraphQlTest(ReportsController.class) public class ReportsControllerIntTest { @Autowired GraphQlTester graphQlTester; @Test public void testReadAllReportsShouldReturnAllReports() throws Exception { String query = """ query { readAll { id reportName columns } } """; graphQlTester.document(query) .execute() .path("readAll") .entityList(ReportDetails.class) .hasSizeGreaterThan(1); } }
以下是具体排查方向:
- 检查JUnit版本与测试运行器:如果使用JUnit 4,测试类必须搭配Spring的运行器才能初始化Spring上下文,需在测试类上添加
@RunWith(SpringRunner.class);如果是JUnit 5,可添加@ExtendWith(SpringExtension.class)(JUnit5默认自动启用,但显式添加能排除配置遗漏问题)。 - 确认控制器类的正确性:检查
ReportsController是否标注了@Controller或@RestController注解,且正确关联了GraphQL Schema。如果控制器未被Spring识别,@GraphQlTest不会自动创建对应的GraphQlTester实例。 - 核对依赖版本兼容性:确保
spring-boot-starter-graphql和spring-boot-starter-test(内含graphql-test依赖)的版本匹配。Spring Boot 3.x需搭配GraphQL Spring Boot 1.x系列版本,Spring Boot 2.x对应GraphQL Spring Boot 0.x系列,版本不匹配会导致自动配置类失效。 - 手动构建GraphQlTester:若自动注入失败,可尝试手动构建实例,绕过自动配置问题:
@Autowired ApplicationContext context; private GraphQlTester graphQlTester; @Before public void setup() { graphQlTester = GraphQlTester.builder(context).build(); }
- 检查测试类包结构:测试类所在包需与主应用包保持一致或为其子包,否则Spring自动扫描可能无法覆盖。若测试包结构特殊,可调整
@GraphQlTest的basePackages属性指定扫描范围。 - 排查自定义测试配置:若项目中有自定义的
@TestConfiguration类,可能覆盖了@GraphQlTest的默认自动配置,导致GraphQlTester未被创建。可暂时移除自定义配置,验证是否恢复正常。
内容的提问来源于stack exchange,提问作者Shourya Sharma
相关产品推荐
相关产品推荐

