二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

1.0 前言? 前面我們介紹了白盒測試方法,后面我們來介紹一下Junit 4 , 使用的是eclipse(用IDEA的小伙伴可以撤了)
1.1 配置Junit 41.1.1 安裝包我們需要三個jar包:

  • org.junit_4.13.2.v20211018-1956.jar
  • org.hamcrest.core_1.3.0.v20180420-1519.jar
  • org.hamcrest-library-1.3.jar
org.junit_4.13.2.v20211018-1956.jar和org.hamcrest.core_1.3.0.v20180420-1519.jar這兩個jar包是eclipse自帶的
然后我們需要下一個org.hamcrest-library-1.3.jar
1.1.2 創建Junit項目點擊 new >> New >> Project
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

文章插圖
選擇Java Project 點擊next
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

文章插圖
輸入項目名,選擇jre,點擊next
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

文章插圖
選擇 Libraries >> Classpath >> Add Extemal JARs
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

文章插圖
選擇之前我們的三個jar包,一般放在eclipsed的plugins目錄,org.hamcrest-library-1.3.jar則在自己下載的目錄(可以把下載下來的jar包也丟這里),點擊Finish
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

文章插圖
我們新建一個文件夾存放junit代碼
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

文章插圖
新建一個項目
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

文章插圖
編寫Demo.java代碼:
public class Demo { public int add (int a, int b) {return a + b; } public int div (int a, int b) {return a / b; }}右鍵項目,new一個,這里沒有junit,我們去其他里面找
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

文章插圖
在java下的junit,選擇Test Case,點擊next
【二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解】
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

文章插圖
選擇junit4,選擇目錄到我們剛剛建的junit文件夾,選擇Finish
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解

文章插圖
在DemoTest.java中輸入代碼:
import static org.junit.Assert.*;import org.junit.After;import org.junit.Before;import org.junit.Test;public class DemoTest { Demo demo; @Before public void setUp() throws Exception {demo = new Demo(); } @After public void tearDown() throws Exception {demo = null; } @Test public void testAdd() {// 實例化一個類Demo demo = new Demo();// 期望值int expetected = 2;// 真實值int trueValue = https://www.huyubaike.com/biancheng/demo.add(1, 1);// 斷言方法assertEquals(expetected, trueValue); } @Test public void testDiv() {// 實例化一個類Demo demo = new Demo();// 期望值int expetected = 2;// 真實值int trueValue = demo.div(2, 1);// 斷言方法assertEquals(expetected, trueValue); }}運行
二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解
1.2 Junit 4 注解1.2.1 測試用例相關的注解1.2.1.1 @Beforepublic void setUp() throws Exception {// 初始化所需的資源}在每個測試方法之前執行,用以初始化需要初始化的資源
1.2.1.2 @After@Afterpublic void tearDown() throws Exception {// 關閉資源}在每個測試方法之后執行,用以關閉需要初始化的資源
1.2.1.3 @BeforeClass@BeforeClasspublic static void setup()throws Exception {// 初始化資源}在所有方法執行之前執行,一般被用作執行計算代價很大的任務,如打開數據庫連接 。被@BeforeClass 注解的方法應該是靜態的(即 static類型的) 。
1.2.1.4 @AfterClass@AfterClasspublic static void tearDown()throws Exception {// 關閉資源}在所有方法執行之后執行,一般被用作執行類似關閉數據庫連接的任務 。被@AfterClass 注解的方法應該是靜態的(即 static類型的) 。
1.2.1.5 @Test@Testpublic void test01() { // 測試,斷言等}包含了真正的測試代碼,并且會被Junit應用為要測試的方法 。
@Test注解有兩個可選的參數:
  • expected表示此測試方法執行后應該拋出的異常,(值是異常名)
  • timeout檢測測試方法的執行時間
1.2.1.6 @Ignore注釋掉一個測試方法或者一個類,被注釋的方法或類 , 不會被執行 。
注意:JUnite4的執行順序:@BeforeClass > @Before > @Test1 > @After > @Before > @Test2 > @After ...... > @AfterClass

推薦閱讀