2014-12-05 25 views
9

對於一些持續用於單一測試方法的JUnit測試,我們使用自定義的Guice範圍@TestScoped,並且JUnit @Rule可以適當地進入和退出範圍。它看起來像這樣:如何將自定義Guice範圍與TestNG集成?

public class MyJUnitTest { 
    @Rule public CustomRule customRule = new CustomRule(MyModule.class); 

    @Inject private Thing thing; 

    @Test 
    public void test1() { 
     // Use "thing" 
    } 

    @Test 
    public void test2() { 
     // Assuming "Thing" is @TestScoped, we'll have a new instance 
    } 
} 

我們開始使用TestNG的一些我們在其他項目的測試,我們希望有一個類似的模式。到目前爲止,我們已經想出了這一點:

@Listeners(CustomTestNGListener.class) 
@Guice(modules = MyModule.class) 
public class MyTestNGTest { 
    @Inject private Provider<Thing> thingProvider; 

    @Test 
    public void test1() { 
     Thing thing = thingProvider.get(); 
     // Use "thing" 
    } 

    @Test 
    public void test2() { 
     Thing thing = thingProvider.get(); 
     // Assuming "Thing" is @TestScoped, we'll have a new instance 
    } 
} 

public class CustomTestNGListener implements IHookable { 
    @Override 
    public void run(IHookCallBack callBack, ITestResult testResult) { 
     TestScope.INSTANCE.enter(); 
     try { 
      callBack.runTestMethod(testResult); 
     } finally { 
      TestScope.INSTANCE.exit(); 
     } 
    } 
} 

有幾個問題,這樣的設計:

  • 與JUnit,TestNG的使用測試類每種方法的同一個實例。這意味着我們必須注入Provider<Thing>而不是僅僅Thing,這很尷尬。

  • 出於某種原因,我們所有的測試都運行了CustomTestNGListener,即使是那些沒有@Listeners(CustomTestNGListener.class)註釋的測試。我已經通過明確地檢查了監聽器中的註釋來解決這個問題,但感覺像是一種破解(雖然我確實看到MockitoTestNGListener做同樣的事情)。

有人對TestNG更加熟悉對處理這些問題有什麼建議嗎?

回答

0

而不是

public class MyTestNGTest { 
    @Inject private Provider<Thing> thingProvider; 

    @Test 
    public void test1() { 
     Thing thing = thingProvider.get(); 

TestNG中,你可以使用

public class MyTestNGTest { 
    @Inject 
    private Thing thingInjected; 
    private Thing thing; 

    @BeforeTest 
    public void doBeforeTest() { 
     thing = thingInjected.clone(); 
    } 

或者只是調用thingProvider.get()doBeforeTest(),最好在你有很多幾乎沒有的@ Test

public class MyTestNGTest { 
    @Inject private Provider<Thing> thingProvider; 
    private Thing thing; 

    @BeforeTest 
    public void doBeforeTest() { 
     thing = thingProvider.get(); 
    } 
+0

的我們的類型是clonaeble – 2015-12-15 23:34:11

+0

至少,你可以稱之爲「東西= thingProvider.get();「在@ BeforeTest不在@ Test。如果你有很多@測試,那會更好 – 2015-12-15 23:37:15