2013-08-02 33 views
3

我使用@Guice註釋使用@Factory標註與@Guice一起加載像下面我模塊: 如何在TestNG的測試類

@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

我解決了如下問題(但我仍相信有另一種方式)

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

}