JUnit註解

在本節中,我們將提到支持在JUnit4基本註釋,下表列出了這些註釋的概括:

註解

描述

@Test
public void method()

測試註釋指示該公共無效方法它所附着可以作爲一個測試用例。

@Before
public void method()

Before註釋表示,該方法必須在類中的每個測試之前執行,以便執行測試某些必要的先決條件。

@BeforeClass
public static void method()

BeforeClass註釋指出這是附着在靜態方法必須執行一次並在類的所有測試之前。發生這種情況時一般是測試計算共享配置方法(如連接到數據庫)。

@After
public void method()

After 註釋指示,該方法在執行每項測試後執行(如執行每一個測試後重置某些變量,刪除臨時變量等)

@AfterClass
public static void method()

當需要執行所有的測試在JUnit測試用例類後執行,AfterClass註解可以使用以清理建立方法,(從數據庫如斷開連接)。注意:附有此批註(類似於BeforeClass)的方法必須定義爲靜態。

@Ignore
public static void method()

當想暫時禁用特定的測試執行可以使用忽略註釋。每個被註解爲@Ignore的方法將不被執行。

 
讓我們看看一個測試類,在上面提到的一些註解的一個例子。

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");
}

}

如果我們運行上面的測試,控制檯輸出將是以下幾點:

@BeforeClass: onceExecutedBeforeAll
@Before: executedBeforeEach
@Test: EmptyArrayList
@After: executedAfterEach
@Before: executedBeforeEach
@Test: OneItemArrayList
@After: executedAfterEach
@AfterClass: onceExecutedAfterAll