在本節(jié)中,我們將提到支持在JUnit4基本注釋,下表列出了這些注釋的概括:
注解 | 描述 |
---|---|
@Test public void method() |
測試注釋指示該公共無效方法它所附著可以作為一個(gè)測試用例。 |
@Before public void method() |
Before注釋表示,該方法必須在類中的每個(gè)測試之前執(zhí)行,以便執(zhí)行測試某些必要的先決條件。 |
@BeforeClass public static void method() |
BeforeClass注釋指出這是附著在靜態(tài)方法必須執(zhí)行一次并在類的所有測試之前。發(fā)生這種情況時(shí)一般是測試計(jì)算共享配置方法(如連接到數(shù)據(jù)庫)。 |
@After public void method() |
After 注釋指示,該方法在執(zhí)行每項(xiàng)測試后執(zhí)行(如執(zhí)行每一個(gè)測試后重置某些變量,刪除臨時(shí)變量等) |
@AfterClass public static void method() |
當(dāng)需要執(zhí)行所有的測試在JUnit測試用例類后執(zhí)行,AfterClass注解可以使用以清理建立方法,(從數(shù)據(jù)庫如斷開連接)。注意:附有此批注(類似于BeforeClass)的方法必須定義為靜態(tài)。 |
@Ignore public static void method() |
當(dāng)想暫時(shí)禁用特定的測試執(zhí)行可以使用忽略注釋。每個(gè)被注解為@Ignore的方法將不被執(zhí)行。 |
讓我們看看一個(gè)測試類,在上面提到的一些注解的一個(gè)例子。
AnnotationsTest.java
package com.yiibai.junit; import static org.junit.Assert.*; import java.util.*; import org.junit.*; public class AnnotationsTest { private ArrayList testList; @BeforeClass public static void onceExecutedBeforeAll() { System.out.println("@BeforeClass: onceExecutedBeforeAll"); } @Before public void executedBeforeEach() { testList = new ArrayList(); System.out.println("@Before: executedBeforeEach"); } @AfterClass public static void onceExecutedAfterAll() { System.out.println("@AfterClass: onceExecutedAfterAll"); } @After public void executedAfterEach() { testList.clear(); System.out.println("@After: executedAfterEach"); } @Test public void EmptyCollection() { assertTrue(testList.isEmpty()); System.out.println("@Test: EmptyArrayList"); } @Test public void OneItemCollection() { testList.add("oneItem"); assertEquals(1, testList.size()); System.out.println("@Test: OneItemArrayList"); } @Ignore public void executionIgnored() { System.out.println("@Ignore: This execution is ignored"); } }
如果我們運(yùn)行上面的測試,控制臺(tái)輸出將是以下幾點(diǎn):
@BeforeClass: onceExecutedBeforeAll @Before: executedBeforeEach @Test: EmptyArrayList @After: executedAfterEach @Before: executedBeforeEach @Test: OneItemArrayList @After: executedAfterEach @AfterClass: onceExecutedAfterAll