1 在Eclipse中引入 junit-4.8.jar
參考下載:Junit4.8 CSDN下載.
2 編寫測試代碼
import org.junit.*;
import org.junit.Test;
public class CalculateTest {
static int order = 0;
public static void show(String msg) {
System.out.println((order++) + " " + msg);
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
show("BeforeClasss");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
show("AfterClasss");
}
@Before
public void setUp() throws Exception {
show("BrforeTest");
}
@After
public void tearDown() throws Exception {
show("AfterTest");
}
@Test
public void test1() {
show("Test1....");
}
@Test
public void test2() {
show("Test2....");
}
}
輸出
如下最下方所示,ctrl+F11 運行全部,可以得到以下輸出:
0 BeforeClasss
1 BrforeTest
2 Test2....
3 AfterTest
4 BrforeTest
5 Test1....
6 AfterTest
7 AfterClasss
結論
JUnit可以方便在代碼執行的不同時期執行相應的代碼,從而達到測試的目的,又可以不影響程序的正式運行。
參考資料
[1] Junit的基本使用(詳解) https://blog.csdn.net/fulishafulisha/article/details/80158392