我正在运行一个使用 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
注释,这意味着父类的设置方法为每个子测试类运行一次。这没问题,但等待多次运行相同的设置真的很慢。
所以我心想:我将ParentTestClass 中的@BeforeClass
注释更改为@BeforeSuite
!这将解决我所有的问题!
错了。
现在,当我运行它时,父类的 beforeClass()
方法中的 Assert.assertNotNull(serviceClient);
行失败。 简而言之,Spring 依赖项不会被注入(inject)到带有@BeforeSuite 注释的方法中,即使在使用@BeforeClass
注释时它们也会被注入(inject)到方法中。 p>
这里有什么想法吗?我真的很感激!
最佳答案
我相信这是按设计工作的。通过查看如何在 org.springframework.test.context.testng.AbstractTestNGSpringContextTests
(您从中扩展)中构建实现,依赖项通过 org.springframework 注入(inject)到您的测试类中.test.context.support.DependencyInjectionTestExecutionListener#injectDependencies
(这是一个监听器)。
包括 DependencyInjectionTestExecutionListener
在内的所有监听器仅通过 org.springframework.test.context.testng.AbstractTestNGSpringContextTests#springTestContextPrepareTestInstance
调用,这是一个 @BeforeClass(alwaysRun=true)
分类方法。
因此,除非此 @BeforeClass
注释方法运行完成,否则您的依赖项对您不可用。因此,您必须移出 @BeforeSuite
方法,并让它仅与 @BeforeClass
注释一起使用。
如果您不需要多次完成服务设置,则需要在测试代码中添加一个编辑检查以只有在未完成时才执行设置。。 p>
关于java - Spring 依赖项没有被注入(inject)到 BeforeSuite 方法中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42988450/