【问题标题】:How can I use google guice DI outside of testNG test classes in a testNG based framework?如何在基于 testNG 的框架中在 testNG 测试类之外使用 google guice DI?
【发布时间】:2018-02-18 08:47:27
【问题描述】:

将对象注入到 testNG 测试类中非常简单,它主要是为我们处理的,但是如何将 google guice DI 构建到我的框架中并将其用于不一定是测试的类?

我想对我的页面对象类的依赖项使用简单的依赖注入进行注入,这些与 testNG 无关,那么我们如何才能为那些初始化依赖项呢?

这是我要替换的简单示例代码:

public class HeaderComponent extends AbstractBasePageObject {
    private static final Logger LOG = LoggerFactory.getLogger(HeaderComponent.class);
    private MenuComponent menu = new MenuComponent(getDriver());


    public HeaderComponent(NgWebDriver ngdriver) {
        super(ngdriver);
    }

    public MenuComponent getMenuComponent() {
        return menu;
    }
}

这个类与testNG本身完全没有关系,所以我该如何初始化所有的结果:

@Inject
MenuComponent menu

我尝试菜单的所有操作都会引发 nullPointerException,因为我认为我在加载 guice 时遇到了问题。

【问题讨论】:

  • 我相信空指针是因为要初始化 MenuComponent 对象,您需要将驱动程序作为参数传入。您是否尝试过@AssistedInject,因为这看起来像是一个运行时值?有没有其他没有参数的注入在这个类中工作?

标签: java testng guice


【解决方案1】:

我为您创建了一些通用示例 - test with injection example

我希望它可以按您的预期工作。它提供了一些测试配置,将它们注入到驱动程序中,最后驱动程序被注入到测试组件中。

结果测试如下:

import com.google.inject.Inject;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;

@Guice(modules = {TestModule.class})
public class SimpleTest {

    @Inject
    ComponentUnderTest component;

    @Test
    public void sampleTest() {
        System.out.println(component.getParamToTest());
        System.out.println(component.param);
        System.out.println(component.elseone);
    }

}

【讨论】:

  • 这很容易,将一些实例变量注入页面对象怎么样?这不是一个 TestClass
  • 你检查示例了吗?您是否需要在测试范围之外获取带有注入实例的 PageObject?你的用例是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多