鍍金池/ 教程/ Java/ JUnit注解
JUnit教程
使用Eclipse的JUnit實(shí)例
Eclipse JUnit簡(jiǎn)單示例
JUnit4忽略(Ignore)測(cè)試實(shí)例
創(chuàng)建參數(shù)化測(cè)試
JUnit介紹,JUnit是什么?
JUnit4時(shí)間(超時(shí))測(cè)試實(shí)例
JUnit規(guī)則
2.預(yù)期異常測(cè)試
JUnit套件測(cè)試實(shí)例
使用@Ignore注解
JUnit4參數(shù)化測(cè)試實(shí)例
在命令行中運(yùn)行JUnit測(cè)試
6.參數(shù)化測(cè)試實(shí)例
JUnit4測(cè)試方法異常拋出實(shí)例
JUnit4 基本用法實(shí)例
3.忽略(Ignore)測(cè)試實(shí)例
創(chuàng)建套件測(cè)試
JUnit注解
4.測(cè)試(超時(shí)返回)時(shí)間
JUnit斷言

JUnit注解

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

注解 描述
@Test
public void method()
測(cè)試注釋指示該公共無效方法它所附著可以作為一個(gè)測(cè)試用例。
@Before
public void method()
Before注釋表示,該方法必須在類中的每個(gè)測(cè)試之前執(zhí)行,以便執(zhí)行測(cè)試某些必要的先決條件。
@BeforeClass
public static void method()
BeforeClass注釋指出這是附著在靜態(tài)方法必須執(zhí)行一次并在類的所有測(cè)試之前。發(fā)生這種情況時(shí)一般是測(cè)試計(jì)算共享配置方法(如連接到數(shù)據(jù)庫)。
@After
public void method()
After 注釋指示,該方法在執(zhí)行每項(xiàng)測(cè)試后執(zhí)行(如執(zhí)行每一個(gè)測(cè)試后重置某些變量,刪除臨時(shí)變量等)
@AfterClass
public static void method()
當(dāng)需要執(zhí)行所有的測(cè)試在JUnit測(cè)試用例類后執(zhí)行,AfterClass注解可以使用以清理建立方法,(從數(shù)據(jù)庫如斷開連接)。注意:附有此批注(類似于BeforeClass)的方法必須定義為靜態(tài)。
@Ignore
public static void method()
當(dāng)想暫時(shí)禁用特定的測(cè)試執(zhí)行可以使用忽略注釋。每個(gè)被注解為@Ignore的方法將不被執(zhí)行。

 
讓我們看看一個(gè)測(cè)試類,在上面提到的一些注解的一個(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)行上面的測(cè)試,控制臺(tái)輸出將是以下幾點(diǎn):

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