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

使用@SpringBootTest做集成测试抛NullPointerException 上下文无法加载如何解决

问题解决方案

你遇到的NullPointerException是因为UserJdbcRepository没有被成功注入到测试类中,本质是Spring上下文未正确加载、对应Bean未被创建导致的,可按照以下步骤排查解决:

  • 检查测试依赖的JUnit版本与注解匹配
    Spring Boot 2.3.x默认集成JUnit5作为测试框架,如果你的@Test注解导入的是JUnit4的org.junit.Test,需要在测试类上额外添加@RunWith(SpringRunner.class)注解让Spring的测试注解生效;如果使用JUnit5,请将@Test替换为org.junit.jupiter.api.Test,无需额外加RunWith注解。
    修正后的JUnit4测试类示例:
    @ActiveProfiles("test")
    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class UserJdbcRepositoryIT {
        @Autowired
        private UserJdbcRepository subject;
    
        @Test
        public void test() {
            subject.findByDocument("000.000.001-91");
        }
    }
    
  • 明确指定@SpringBootTest的启动类
    @SpringBootTest默认会扫描测试类当前包路径下的SpringBoot启动类,如果测试类包路径和主项目启动类(带@SpringBootApplication注解的类)的包路径不一致,会导致上下文无法正常扫描到Bean。可手动指定启动类:
    @SpringBootTest(classes = 你的主启动类名.class)
    
  • 修复版本冲突问题
    你的pom.xml中手动指定了spring-jdbc的版本为5.2.16.RELEASE,和Spring Boot 2.3.7.RELEASE自带的Spring JDBC版本不一致,容易引发Bean初始化失败。建议删除pom中单独引入的spring-jdbc依赖,直接使用spring-boot-starter-data-jdbc自带的兼容版本。
  • 检查测试配置文件位置
    确认application-test.properties文件放置在src/test/resources目录下,执行mvn clean test-compile后查看target/test-classes目录下是否存在该配置文件,避免配置未加载导致数据源初始化失败、上下文启动异常。
  • 排查包扫描规则
    确认UserJdbcRepository所在的包路径在Spring的包扫描范围内,如果主启动类上自定义了@ComponentScan的扫描路径,需要将Repository所在的包路径加入扫描列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:21:01