testng - 如何在 TestNG 测试类中使用 @Factory 注释和 @Guice

标签 testng guice factory

我正在使用 @Guice 注释来加载我的模块,如下所示:

@Guice(modules={MyModule.class})
public class TestITest {

    private int a;
    private int b;
    private int exp;

    @Inject
    ITest iTest;

    public TestITest() {}

    @Factory(dataProvider="get values")
    public TestITest(int a, int b, int exp) {
        this.a = a;
        this.b = b;
        this.exp = exp;
    }

    @Test
    public void testITest() {
        assertEquals(iTest.calc(a, b), exp);
    }


    @DataProvider(name="get values")
    public Object[][] getValues() {
        Random rand = new Random();
        List<Object[]> result = new ArrayList<Object[]>();

        for (int i=0; i<10; i++) {
            int a = rand.nextInt();
            int b = rand.nextInt();
            int exp = a + b;
            result.add(new Object[] {a,b,exp});
        }

        return result.toArray(new Object[result.size()][3]);
    }

}

我创建了一个空的构造函数,因为 Guice 提示没有参数的构造函数,我知道添加它不会解决我的问题。然后我也添加了,然后出现了另一个问题。所有十个值都已创建,并且 TestNG 正在运行具有 10 个值的测试类,但是 ITest 实现没有被注入(inject)并给我 NullPointerException 10 次。

最佳答案

我解决了下面的问题(但我仍然确定还有另一种方法)

//@Guice(modules={MyModule.class})
public class TestITest {

    private int a;
    private int b;
    private int exp;

    @Inject
    ITest iTest;

       //added a static injector with the module
    public static final Injector injector = Guice.createInjector(new MyModule());

    @Factory(dataProvider="get values")
    public TestITest(int a, int b, int exp) {
        this.a = a;
        this.b = b;
        this.exp = exp;

             //Injected implementation here
        injector.injectMembers(this);
    }

    @Test
    public void testITest() {
        assertEquals(iTest.calc(a, b), exp);
    }

      // Changed modifier to static
    @DataProvider(name="get values")
    public static Object[][] getValues() {
        Random rand = new Random();
        List<Object[]> result = new ArrayList<Object[]>();

        for (int i=0; i<10; i++) {
            int a = rand.nextInt();
            int b = rand.nextInt();
            int exp = a + b;
            result.add(new Object[] {a,b,exp});
        }

        return result.toArray(new Object[result.size()][3]);
    }

}

关于testng - 如何在 TestNG 测试类中使用 @Factory 注释和 @Guice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18013165/

相关文章:

java - Webdriver TestNG 空指针异常

guice - 结合@Provides 和@Inject

java - Google Guice 依赖注入(inject) - 对象到底是在哪里创建的?

java - Play 在类路径上找不到 play.db.DBModule

javascript - Angular $watch 细微差别和工厂不反射(reflect)状态变化?

javascript - Angularjs:在服务中加载数据然后将其加载到 Controller

java - 添加测试用例的方法

java - "java.lang.OutOfMemoryError"每当我在 jenkins 中运行一个特定的 testng 套件文件时,我都会收到此错误

java - TestNG.xml - 第一个浏览器 session 关闭后,新的浏览器 session 不会打开

C++ 类工厂宏