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

继承AbstractTestNGSpringContextTests的抽象基类中@Autowired依赖始终为空

解决Spring TestNG基类中@Autowired实例为空的问题

这个问题我之前也碰到过,核心原因是TestNG的@BeforeSuite执行时机早于Spring上下文的初始化时机,导致@Autowired注入的MyActions还没被实例化就被调用了。下面给你具体的分析和解决方案:

问题根源

AbstractTestNGSpringContextTests的Spring上下文是在TestNG的@BeforeClass阶段完成初始化和依赖注入的,但@BeforeSuite是在所有测试类加载之前就执行的。这时候你的beforeUISuite方法已经被调用,但Spring还没来得及把MyActions实例注入到BaseTest中,自然就会出现空指针异常。另外你注解里的dependsOnMethods = "beforeSuite"其实是多余的,因为AbstractTestNGSpringContextTests并没有这个方法,反而可能干扰执行逻辑。

解决方案

方案一:调整生命周期注解(推荐)

把@BeforeSuite改成@BeforeClass,这样方法会在Spring上下文初始化完成后执行,此时@Autowired的bean已经被正确注入:

@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
@ActiveProfiles(resolver = ActiveProfileResolver.class)
public abstract class BaseTest extends AbstractTestNGSpringContextTests {
    @Autowired
    private MyActions myActions;

    @BeforeClass(alwaysRun = true)
    public void beforeUIClass() {
        myActions.doSomething();
    }
}

方案二:手动触发上下文初始化(如果必须用@BeforeSuite)

如果你确实需要在Suite级别执行这个方法,可以手动调用Spring测试框架的上下文初始化方法,提前完成依赖注入:

@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
@ActiveProfiles(resolver = ActiveProfileResolver.class)
public abstract class BaseTest extends AbstractTestNGSpringContextTests {
    @Autowired
    private MyActions myActions;

    @BeforeSuite(alwaysRun = true)
    public void beforeUISuite() {
        // 手动触发Spring上下文初始化和依赖注入
        springTestContextPrepareTestInstance();
        myActions.doSomething();
    }
}

额外检查项

别忘了确认:

  • MyActions类上是否标注了@Component/@Service等Spring组件注解,或者在spring-test-config.xml中有没有定义这个bean
  • spring-test-config.xml是否被正确放置在classpath下,能被Spring扫描到

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:40:46