[英]How to inject dependecies using Governator within TestNG test cases?
我正在研究使用TestNG的测试自动化框架。 我决定使用依赖注入模式来实现更具可读性、可重用性的页面对象和测试。
我选择Google Guice 是因为TestNG提供了用Guice Modules注入测试对象的内置支持。 我只需要指定我的Guice 模块,你可以在下一个代码片段中看到:
@Guice(modules = CommModule.class)
public class CommunicationTest {
@Inject
private Communication comms;
@Test
public void testSendMessage() {
Assertions.assertThat(comms.sendMessage("Hello World!")).isTrue();
}
}
到目前为止一切顺利,尽管我将需要更多高级 DI 功能,例如:
因此,我想使用Netflix/Governator,因为它通过这些功能增强了Google Guice 。 为了触发Governator功能,我必须通过它而不是TestNG创建Injector
。 例如:
Injector injector = LifecycleInjector.builder()
.withModules(CommModules.class).build().createInjector();
我想尽可能透明地做它,就像TestNG那样。
我想知道是否:
Injector
实例以重用@Guice
注释方法?你可以在这里找到我到目前为止所做的。
直到现在,这是不可能的。 我已经在最新的 TestNG 快照版本中修复了这个问题。 它应该在即将推出的 TestNG 版本中可用(任何大于7.0.0
版本)
我为跟踪此问题而创建的问题: https : //github.com/cbeust/testng/issues/2199
简而言之,您可以执行以下操作:
org.testng.IInjectorFactory
-dependencyinjectorfactory
插入新创建的实现的完全限定类名由于允许用户提供 DI Injector TestNG功能将出现在高于7.0.0
版本中。 我使用TestNG 7.0.0
版侦听器实现了一个解决方案。
首先,我创建了一个名为autopilot-testng-runner的模块,具有以下依赖项:
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
</dependency>
<dependency>
<groupId>com.netflix.governator</groupId>
<artifactId>governator</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
</dependencies>
该模块包含接下来描述的工件:
@AutopilotTest :用于声明必须使用哪些Guice模块通过LifecycleInjector.builder()
创建Injector
自定义注释。 我无法重用@Guice
注释,因为TestNG也会创建它的 Injector,并且声明的依赖项将被创建两次。
AutopilotSuiteListener : ISuiteListener
实现,用于在 Suite 启动之前创建父Injector
、 Governator 的LifecycleManager
实例并绑定配置属性。 因此,每个套件都将有一个使用Governator构建的父Injector
和一个生命周期管理器。
AutopilotTestListener : ITestListener
实现负责在运行的测试用例中注入依赖项。
META-INF/services/org.testng.ITestNGListener :包含两个ITestNGListener
实现的完全限定名称的服务提供者配置文件。
然后,我在我的项目中添加了autopilot-testng-runner
作为 maven 依赖项
<dependency>
<groupId>com.github.eljaiek.playground</groupId>
<artifactId>autopilot-testng-runner</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
最后,我换成@Guice
批注与@AutopilotTest
@AutopilotTest(modules = CommModule.class)
public class CommunicationTest {
@Inject
private Communication comms;
@Test
public void testSendMessage() {
Assertions.assertThat(comms.sendMessage("Hello World!")).isTrue();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.