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

Spring Boot 2.1.15集成测试@Autowired注入Bean为null如何解决?

问题原因分析
  • Spring Boot 2.1.15.RELEASE 配套的 Spring Test 版本对 JUnit4 的支持需要显式指定测试运行器,你当前的测试类缺少@RunWith(SpringRunner.class)注解,导致Spring测试上下文无法和JUnit4的测试生命周期绑定,上下文不会主动初始化,因此所有@Autowired注入的对象都为null。
  • Spring Boot 2.6.x 默认使用 JUnit5,@SpringBootTest注解已经默认整合了@ExtendWith(SpringExtension.class)能力,不需要额外配置运行器,因此升级后可以正常注入。
解决方案

只需要给测试类补充JUnit4的Spring运行器注解即可,步骤如下:

  1. 导入对应的依赖类:
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
  1. 在测试类上添加@RunWith(SpringRunner.class)注解。
  2. 额外优化:@ContextConfiguration(initializers = ...)配置在@SpringBootTest注解中已经默认实现,不需要额外声明,可以直接删除。
修正后的完整代码
import com.example.demo.helpers.Subtitle;
import com.example.demo.helpers.Summary;
import com.example.demo.helpers.Title;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Summary.class, Title.class, Subtitle.class},webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoApplicationTests {

    @Autowired
    ApplicationContext context;

    @Autowired
    Summary summary;

    @Autowired
    Title title;

    @Test
    public void contextLoads() {
        System.out.println("executed testcase..");
    }
}
其他可选排查点
  • 确认测试依赖spring-boot-starter-test没有排除junit相关组件,确保JUnit4的依赖正常引入
  • 确认Summary、Title、Subtitle类上已经添加了@Component/@Service等Spring托管注解
  • 确认测试方法的@Test注解导入的是org.junit.Test而非JUnit5的org.junit.jupiter.api.Test

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:06:05