2013-07-31 22 views

回答

2

有2個特別的註釋,可以幫助你這個問題,並打算在情況下使用,例如你的:

@After定義了一定的方法必須在每次@Test後執行,同時@AfterClass是方法一旦完成整個測試類的執行。把後者想象成最後的清理方法來清除你迄今在測試中使用和共享的任何結構或記錄。

下面是一個例子:

@After 
public void cleanIndex() { 
    index.clear(); //Assuming you have a collection 
} 

@AfterClass 
public void finalCleanup() { 
    //Clean both the index and, for example, a database record. 
} 

:他們通過調用@Test方法之前相關的方法和開始執行該@Test之前有其對應物(@Before@BeforeClass),其以完全相反的定義在這個類上。這是在以前版本的JUnit中使用的setUp


如果你不能使用註釋,另一種方法是使用好老tearDown方法:

public void tearDown() { 
    index.clear(); //Assuming you have a collection. 
} 

這是由JUnit框架提供和表現如同@After註釋的方法。

1

您應該使用@Before註釋來確保每個測試都從乾淨狀態運行。請參閱:Test Fixtures

1

在您的junit測試課程中,您可以覆蓋方法setupteardownsetup將在每次測試之前運行,而teardown將在每次測試完成後運行。

例如:

public class JunitTest1 { 

    private Collection collection; 

    //Will initialize the collection for every test you run 
    @Before 
    public void setUp() { 
     collection = new ArrayList(); 
     System.out.println("@Before - setUp"); 
    } 

    //Will clean up the collection for every test you run 
    @After 
    public void tearDown() { 
     collection.clear(); 
     System.out.println("@After - tearDown"); 
    } 

    //Your tests go here 
} 

這是其間的測試清理出有用的數據,但也可以讓你不必重新初始化每一個測試你的內場。

相關問題