3

我正在使用@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没有注入实现并给了我NullPointerException10 次。

4

1 回答 1

2

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

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

}
于 2013-08-02T10:29:16.127 回答