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

JUnit 5环境下SpringBoot测试@Autowired注入为空问题求解

问题原因
  • 你测试类中手动通过new ThrottleRateServiceImpl()实例化了服务类,这个实例没有被Spring上下文托管,因此Spring不会处理实例内部的@Autowired注解,导致Repository字段为null,该问题和JUnit版本无关,属于Spring容器托管逻辑的通用规则。
  • 额外冗余注解:@SpringBootTest已经默认集成了@ExtendWith(SpringExtension.class),不需要额外单独声明,测试类上的@SpringBootConfiguration如果你的项目启动类在包扫描路径下也可以省略。
修正方案

直接从Spring容器中注入你要测试的Service实例即可,修正后的测试代码如下:

@SpringBootTest
public class ThrottleRateServiceTest {
    
    // 直接注入容器托管的Service实例,内部的Repository会被自动注入
    @Autowired
    ThrottleRateService service;
    
    @Test
    public void testThrottoling() {
        service.isAllowed("test");
    }
}
额外注意事项
  • 确保ThrottleRateRepository上添加了@Repository注解,且该类、ThrottleRateServiceImpl类都在Spring Boot启动类的包扫描路径下(默认是启动类所在包及所有子包)
  • 如果你需要指定启动类,可调整@SpringBootTest注解为@SpringBootTest(classes = 你的项目启动类.class)
  • 生产代码更推荐使用构造器注入代替字段@Autowired注入,不需要额外依赖注入框架的情况下也能正常初始化成员变量,代码可测试性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:45:03