Java單元測試工具:JUnit4(三)——JUnit詳解之執行流程及常用註解
阿新 • • 發佈:2018-12-14
(三)執行流程及常用註解
這篇筆記記錄JUnit測試類執行時,類中方法的執行順序;以及JUnit中常用的註解。1.JUnit的執行流程
1.1 新建測試類
右鍵被測試類,新建一個測試類。彈出框中,首先改變測試類所在的程式碼目錄,然後勾選4個方法:1.2 修改測試類程式碼
如下: [java] view plain- package jtzen9.util;
- import org.junit.After;
- import org.junit.AfterClass;
- import org.junit.Before;
- import org.junit.BeforeClass;
- import org.junit.Test;
- public class JunitFlowTest {
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- System.out.println("this is setUpBeforeClass()..."
- }
- @AfterClass
- public static void tearDownAfterClass() throws Exception {
- System.out.println("this is tearDownAfterClass()...");
- }
- @Before
- public void setUp() throws Exception {
- System.out.println("this is setUp()...");
- }
- @After
- public void tearDown() throws Exception {
- System.out.println("this is tearDown()...");
- }
- @Test
- public void test() {
- System.out.println("this is test()...");
- }
- }
控制檯輸出如下:
在測試類中,增加一個test2()測試方法: [java] view plain copy
- ......
- @Test
- public void test2(){
- System.out.println("this is test2()...");
- }
- ......
1.3 總結說明
①@BeforeClass修飾的方法會在所有方法被呼叫前被執行,而且該方法是靜態的,所以當測試類被載入後接著就會執行它,而且在記憶體中它只會存在一份例項,它比較適合載入配置檔案,進行初始化等等②@AfterClass所修飾的方法會在所有方法被呼叫後被執行,通常用來對資源的清理,如關閉資料庫的連線
③@Before和@After會在 每個測試方法的前後各執行一次。
2.JUnit常用註解
* @Test:將一個普通的方法修飾成為一個測試方法@Test(expected=XX.class)
@Test(timeout=毫秒)
* @BeforeClass:它會在所有的方法執行前被執行,static修飾
* @AfterClass:它會在所有的方法執行結束後被執行,static修飾
* @Before:會在每一個測試方法被執行前執行一次
* @After:會在每一個測試方法執行後被執行一次
* @Ignore:所修飾的測試方法會被測試執行器忽略
* @RunWith:可以更改測試執行器 org.junit.runner.Runner
2.1 @Test、@Ignore的測試
例子程式碼: [java] view plain copy- package jtzen9.util;
- import static org.junit.Assert.assertEquals;
- import org.junit.Ignore;
- import org.junit.Test;
- public class AnotationTest {
- @Test(expected=ArithmeticException.class)
- public void testDivide() {
- assertEquals("除法有問題",3, new Calculate().divide(6, 0)); //將除數設定為0
- }
- @Test(timeout=2000)
- public void testWhile() {
- while(true) {
- System.out.println("run forever..."); //一個死迴圈
- }
- }
- @Test(timeout=3000)
- public void testReadFile(){
- try {
- Thread.sleep(2000); //模擬讀檔案操作
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- @Ignore("...")
- @Test
- public void testIgnore() {
- System.out.println("會執行嗎?");
- }
- }
說明: ①testDivide()方法中,將除數設為0,本會丟擲Error,但設定了@Test(expected=ArithmeticException.class),說明我們預期它會丟擲一個算術異常,所以程式結果也符合我們的預期。 ②testWhile()方法是一個死迴圈,但設定了@Test(timeout=2000),即2秒之後,自動結束迴圈
③testReadFile()方法模擬讀取檔案操作,設定讀取超時時間為3秒,等於或大於測試時間則認為不成功,而程式睡眠了2秒,沒有超時。這裡表示用作一些效能的測試。 ④testIgnore()方法,因為使用的@Ignore註解,所以不會執行。