4

我正在开发一个使用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功能,我必须Injector通过它而不是TestNG创建。例如:

    Injector injector = LifecycleInjector.builder()
        .withModules(CommModules.class).build().createInjector();

而且我想尽可能透明地做到这一点,就像TestNG所做的那样。

我想知道是否:

  • 是否可以向TestNG提供我自己的Injector实例以重用注释方法?@Guice
  • 您知道任何将GovernatorTestNG集成的库吗?

你可以在这里找到我到目前为止所做的事情。

4

2 回答 2

3

直到现在这是不可能的。我已在 TestNG 的最新快照版本中修复了此问题。它应该在即将发布的 TestNG 版本中可用(任何大于 的版本7.0.0

我为跟踪此问题而创建的问题:https ://github.com/cbeust/testng/issues/2199

简而言之,您可以执行以下操作:

  • 实现接口org.testng.IInjectorFactory
  • 通过命令行参数插入新创建实现的完全限定类名-dependencyinjectorfactory
于 2019-11-29T17:54:44.313 回答
1

由于允许用户提供 DI 注入器 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:用于声明必须使用哪些GuiceInjector模块来创建with的自定义注释LifecycleInjector.builder()@Guice由于TestNG也将创建它的 Injector 并且声明的依赖项将被创建两次,因此我无法重用注释。

  • AutopilotSuiteListener:在 Suite 启动之前ISuiteListener创建父InjectorGovernator 的 LifecycleManager实例和绑定配置属性的实现。因此,每个套件都将有一个由Governator和一个生命周期管理器Injector构建的父级。

  • AutopilotTestListenerITestListener负责在运行的测试用例中注入依赖项的实现。

  • 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();
        }
    }
于 2019-12-03T13:17:13.147 回答