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

时间:2013-08-02 09:18:51

标签: 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实现没有被注入,并且给我NullPointerException 10次。

1 个答案:

答案 0 :(得分:1)

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

//@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]);
    }

}