Java@Test注解實踐
利用Junit測試的@Test注解,可以避免經常編寫測試類。
@Test注解,方便我們對一段代碼進行測試。
需要導入相應的包:
import org.junit.Test;
在方法前加上 @Test , 則該方法即為測試方法,可以執行。
下圖為第五版《Java編程思想》的描述
但在實際使用中發現方法權限只能是public,不能用static修飾,而且不能用於內部類的方法。、
Case1 下面的代碼可以正常執行,輸出正常
import org.junit.Test;
public class TestExample {
private int num = 90;
@Test
public void testShow(){
System.out.println(num);
}
}
下面的幾種情況均不能執行。
Case2、3 用於內部類不能執行測試,添加“static”不能執行。
import org.junit.Test;
public class TestExample {
private int num = 90;
class inter{
@Test
public void testShow(){
System.out.println(num);
}
}
}
------------------------------------------
import org.junit.Test;
public class TestExample {
private int num = 90;
class inter{
@Test
public static void testShow(){
System.out.println(num);
}
}
}
@Test注解源碼描述。Junit首先構造類的一個新實例,然后調用帶注釋的方法。推測創建內部類對象和靜態方法均不滿足條件,后續補充相關知識后再進行完善。
補充
注解 | 描述 |
---|---|
@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
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