【问题标题】:Spring dependencies not being injected into BeforeSuite method?Spring依赖没有被注入到BeforeSuite方法中?
【发布时间】:2017-03-23 22:53:44
【问题描述】:

我正在运行一个使用 TestNG 作为测试框架的 Spring Boot 应用程序。我的测试是这样设置的:

一个父类,负责设置逻辑并负责所有的配置工作:

@ContextConfiguration(classes = {TestingConfig.class}, initializers = ConfigFileApplicationContextInitializer.class)
@ContextConfiguration(classes = TestConfig.class)
@TestPropertySource(locations = "classpath:application.yml")
public abstract ParentTestClass extends AbstractTestNGSpringContextTests {

    @Autowired
    private ServiceClient serviceClient;

    @BeforeSuite
    public void beforeClass() {

        Assert.assertNotNull(serviceClient);

        serviceClient.doSomeSetupWork();
    }
}

有多个子测试类。每个 on 都继承自父测试类,因此它们共享相同的设置逻辑。

public ChildTestClass1 extends ParentTestClass {

    @Test
    public void someTest() {
    ...
    }

    // More tests not shown
}

public ChildTestClass2 extends ParentTestClass {

    @Test
    public void anotherTest() {
    ...
    }

    // More tests not shown
}

serviceClient 是测试套件所依赖的 Web 服务之一的客户端。在运行测试用例之前,我正在与服务客户端进行调用以在其他服务中设置数据。

问题是这样的:以前我使用@BeforeClass 注释,这意味着父类的 setup 方法为每个子测试类运行一次。这没问题,但是等待多次运行相同的设置真的很慢。

所以我心想:我只需将 ParentTestClass 中的 @BeforeClass 注释更改为 @BeforeSuite!这将解决我所有的问题!

错了。

现在当我运行它时,父类的beforeClass() 方法中的Assert.assertNotNull(serviceClient); 行失败。 简而言之,Spring 依赖项并没有被注入到 @BeforeSuite 注释的方法中,即使它们被注入到使用 @BeforeClass 注释的方法中。

这里有什么想法吗?我真的很感激!

【问题讨论】:

    标签: java spring unit-testing testng


    【解决方案1】:

    我相信这是按设计工作的。通过查看实现是如何在org.springframework.test.context.testng.AbstractTestNGSpringContextTests(您从中扩展)中构建的,依赖项通过org.springframework.test.context.support.DependencyInjectionTestExecutionListener#injectDependencies(这是一个侦听器)注入到您的测试类中。 包括DependencyInjectionTestExecutionListener 在内的所有监听器只能通过org.springframework.test.context.testng.AbstractTestNGSpringContextTests#springTestContextPrepareTestInstance 调用,这是一个@BeforeClass(alwaysRun=true) 分类方法。

    因此,除非此 @BeforeClass 注释方法运行完成,否则您的依赖项对您不可用。因此,您必须移出您的 @BeforeSuite 方法并让它仅与 @BeforeClass 注释一起使用。

    如果您不需要多次完成服务设置,那么您需要在测试代码中添加一个编辑检查以执行设置仅在未完成时。。 p>

    【讨论】:

    • 很遗憾,他们仅将其实现为与 BeforeClass 注释一起使用...这将为我创造大量额外的工作:/感谢您对此有所了解!
    【解决方案2】:

    这里是您所有问题的解决方案。

    @Override
    @BeforeSuite
    protected void springTestContextPrepareTestInstance() throws Exception {
    super.springTestContextPrepareTestInstance();  
    }
    

    希望这可以帮助您注入依赖项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多