1、導入Junit4jar包:
Eclipse中在項目上右鍵點擊Bulid Path,然后再點擊Add libraries,選擇JUnit
2、初次使用
首先先創建一個java項目如下:

Demo.java內容:
package cn.orlion.demo; public class Demo { public int method1(int p1 , int p2){ return p1 + p2; } public int method2(int p1 , int p2){ return p1 - p2; } public int method3(int p1 , int p2){ return p1 * p2; } }
然后在src上點擊右鍵添加一個source folder命名為test,在test下創建包cn.orlion.demo(包名要與要測試的包名一致),然在在此包右鍵new一個JUnit Test Case,命名為DemoTest。
寫測試類時有一些規范需要遵守:
(1)測試方法上必須使用@Test進行修飾(2)測試方法必須用public void修飾不能帶參數(3)需要新建一個源代碼目錄來存放測試代碼(4)測試類的包必須要與被測試類包名一致(5)測試單元中的每個方法必須可以獨立測試,方法間不能存在依賴(6)測試類使用Test作為后綴(7)測試方法使用test作為前綴
代碼如下所示:
package cn.orlion.demo; import static org.junit.Assert.*; import org.junit.Test; public class DemoTest { @Test public void testMethod1(){ assertEquals(3 , new Demo().method1(2 , 1)); } @Test public void testMethod2(){ assertEquals(1 , new Demo().method2(2 , 1)); } @Test public void testMethod3(){ assertEquals(2 , new Demo().method3(2 , 1)); } }
現在的項目結構如圖所示

在DemoTest.java類右鍵點擊Run As -> JUnit Test結果如下所示:

(Failures一般是由測試方法中斷言引起,這表示測試點出現了問題,證明被測試的方法返回的結果與我們預期的不一樣
Errors一般是由被測試方法或者是測試方法中存在異常導致。)
狀態條為綠色三個方法全部測試成功
3、JUnit運行流程
(1)@BeforeClass修飾的方法會在所有方法執行前執行,該方法是靜態的,所以當測試類被加載后就會運行它,在內存中只會存在一份,適合加載配置文件
(2)@AfterClass修飾符修飾的方法會在所有方法執行后執行,通常用來清理資源,比如關閉流
(3)@Before和@After會在每個測試方法執行前后各執行一次。
4、JUnit常用注解
(1)@Test
@Test有個expected屬性和timeout屬性(@Test(expected=NullPointerException.class),@Test(timeout=1000))
expected屬性可以捕獲測試方法和被測試方法中預期拋出的異常,timeout限定方法執行的時間
(2)@Ignore
@Ignore修飾的方法不會被執行,可以@Ignore("此方法被忽略")做一個注釋:此方法被忽略
(3)@RunWith可以更改測試運行器org.junit.runner.Runner
5、測試套件
隨着項目功能的逐漸完善我們的測試類也會越來越多,測試的時候不能一個一個的去執行,於是有了測試套件,也就是在一個入口類中包含若干個測試類,然后只要執行該入口類就可以執行其包含的若干個測試類
入口類必須是個空類,如下:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({DemoTest.class,DemoTest1.class})
public class SuiteTest {
}
6、JUnit參數化設置
在測試中很多測試代碼基本上差不多,所以可以采用參數化設置
import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; // 第一步:更改測試運行器 @RunWith(Parameterized.class) public class ParameterTest { // 第二步:聲明變量來存放預期值與輸入值 int expected = 0; int input1 = 0; int input2 = 0; // 第三步:聲明一個返回值為Collection的公共靜態方法,使用@Parameters修飾 @Parameters public static Collection<Object[]>t(){ return Arrays.asList(new Object[][]{ {3,1,2}, {1,2,1}, {2,2,1} }); } // 第四步:為測試類聲明一個帶參數的公共構造函數,並在其中為聲明變量賦值 public ParameterTest(int expected , int input1 , int input2){ this.expected = expected; this.input1 = input1; this.input2 = input2; } // 第五步:進行測試 @Test public void testMethod1(){ assertEquals(expected , new Demo().method1(input1 , input2)); } }
