1. 程式人生 > >基礎註解(@BeforeClass、@Before、@Test、@After、@AfterClass)

基礎註解(@BeforeClass、@Before、@Test、@After、@AfterClass)

Junit4 註解提供了書寫單元測試的基本功能。本章將介紹@BeforeClass,@AfterClass,@Before,@After,@Test 這幾個基本註解。

@BeforeClass註解

被@BeforeClass註解的方法會是:
  • 只被執行一次
  • 執行junit測試類時第一個被執行的方法
這樣的方法被用作執行計算代價很大的任務,如開啟資料庫連線。被@BeforeClass 註解的方法應該是靜態的(即 static型別的)。

@AfterClass註解

被@AfterClass註解的方法應是:

  • 只被執行一次
  • 執行junit測試類是最後一個被執行的方法
該型別的方法被用作執行類似關閉資料庫連線的任務。被@AfterClass 註解的方法應該是靜態的(即 static型別的)。

@Before註解

被@Before 註解的方法應是:
  • junit測試類中的任意一個測試方法執行 前 都會執行此方法
該型別的方法可以被用來為測試方法初始化所需的資源。

@After註解

被@After註解的方法應是:
  • junit測試類中的任意一個測試方法執行後 都會執行此方法, 即使被@Test 或 @Before修飾的測試方法丟擲異常
該型別的方法被用來關閉由@Before註解修飾的測試方法開啟的資源。

@Test 註解

被@Test註解的測試方法包含了真正的測試程式碼,並且會被Junit應用為要測試的方法。@Test註解有兩個可選的引數:
  • expected 表示此測試方法執行後應該丟擲的異常,(值是異常名)
  • timeout 檢測測試方法的執行時間

Junit 4 註解例子

Arithmetic.java,本例要用到的需要Junit進行單元測試的類:

package in.co.javatutorials;
 
public class Arithmetic {
 
    public int add(int i, int j) {
        return i + j;
    }
}

ArithmeticTest.java,Arithmetic.java的Junit單元測試類:

package in.co.javatutorials;
 
import static org.junit.Assert.assertEquals;
 
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
 
public class ArithmeticTest {
 
    @BeforeClass
    public static void setUpClass() {
        // one time setup method
        System.out.println("@BeforeClass - executed only one time and is first method to be executed");
    }
 
    @AfterClass
    public static void tearDownClass() {
        // one time tear down method
        System.out.println("@AfterClass - executed only one time and is last method to be executed");
    }
 
    @Before
    public void setUp() {
        // set up method executed before every test method
        System.out.println("@Before - executed before every test method");
    }
 
    @After
    public void tearDown() {
        // tear down method executed after every test method
        System.out.println("@After - executed after every test method");
    }
 
    @Test
    public void testAdd() {
        Arithmetic arithmetic = new Arithmetic();
        int actualResult = arithmetic.add(3, 4);
        int expectedResult = 7;
        assertEquals(expectedResult, actualResult);
        System.out.println("@Test - defines test method");
    }
}

樣例結果輸出

本例在Eclipse Junit視窗的輸出結果如下:

樣例日誌輸出:

@BeforeClass - executed only one time and is first method to be executed
@Before - executed before every test method
@Test - defines test method
@After - executed after every test method
@AfterClass - executed only one time and is last method to be executed

本文出處為 http://blog.csdn.net/luanlouis,轉載請註明出處,謝謝!