一、運行流程
在test文件夾下新建一個JUnitTest測試類,勾選自動提供的四個method stubs。
package com.junit;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class JunitTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("BeforeClass");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("AfterClass");
}
@Before
public void setUp() throws Exception {
System.out.println("Before");
}
@After
public void tearDown() throws Exception {
System.out.println("After");
}
@Test
public void test1() {
System.out.println("test1");
}
@Test
public void test2(){
System.out.println("test2");
}
}
運行程序可以發現,@BeforeClass和@AfterClass在所有方法被調用前執行一次,而@Before和@After會在每個測試方法前後各執行一次。
@BeforeClass是靜態的,當測試類加載後接着就會執行它,內存中只有一份實例,比較適合加載配置文件;
@AfterClass所修飾的方法用來對資源的清理,如關閉對數據庫的連接。
二、常用註解
@Test:將每個普通方法修飾爲測試方法
1、expected = XXX.class
@Test(expected = ArithmeticException.class)
public void testDivide() {
assertEquals(4,new Number().divide(8, 0));
}
2、timeout
@Test(timeout = 2000)
public void testReadFile(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Ignore:所修飾的測試方法會被測試器忽略
@Ignore
@Test(timeout = 1000)
public void testWhile(){
while(true){
System.out.println("hello world");
}
}
@BeforeClass:在所有方法運行前被執行,static修飾
@AfterClass:在所有方法運行結束後被執行,static修飾
@Before:在每個測試方法運行前執行一次
@After:在每個測試方法運行後執行一次