一、添加Junit插件。
1.file-->setting-->plugins-->搜索Junit-->安裝插件(一般已默認安裝,無需手動安裝)。
二、設置Junit測試參數:
1.新建一個文件夾test用於放置測試類
2.右鍵該文件夾選擇Mark directory as-->Test Resources Root
三、開始測試
1.選擇要測試的類按快捷鍵Ctrl+shift+t創建新的測試類
2.在彈出窗口勾選要測試的方法點擊確定。
3.在測試類中完成測試方法右鍵運行完成測試。
四、技巧
在測試類中調用assertEquals()方法檢驗結果。該方法有兩個參數,第一個是期望輸出的值,第二個是實際調用輸出的值。可以進行比較,若相同則測試供過。
五、使用
1@Before注解的方法會在每一個測試方法開始之前調用。@After注解的方法會在每一個測試方法結束后調用。@BeforeAll(Junit4中是@BeforeClass)注解的類方法在類加載時調用一次。@AfterAll(Junit4中是@AfterClass)注解的類方法在所有測試方法完成后調用
2.@Test(timeout=100,expected = ArithmeticException.class),第一個參數代表方法執行的時間限制,超時即報錯。第二個參數表示某異常是預料之中的事,即使出現也算測試通過。@Ignore注解表示忽略當前方法,測試其他方法。
3.@RunWith注解在類上,可以更改默認的測試運行器,參數是具體的測試運行器類的.class.
@RunWith(Suite.class)測試套件:可以批量測試多個測試類。將測試類的class對象傳入作為參數,要求被套件注解的類內容為空。如圖所示:
4.如何同時測試一個方法的多組數據?看下面的代碼
package he; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.*; @RunWith(Parameterized.class)//1.先更換測試運行器 public class ATest extends he.A { //2.定義參數用來存儲測試方法的參數和期望值 int expe=0; int input1=0; int input2=0; //該方法用於生成批量參數 @Parameters public static Collection<Object[]> canshu(){ return Arrays.asList(new Object[][]{ {3,1,2},{5,2,3}}); } //構造器用於將生成的批量參數賦值到類成員變量中 public ATest(int expe,int input1,int input2){ this.expe=expe; this.input1=input1; this.input2=input2; } //測試方法開始測試 @Test public void add() { assertEquals(expe,add(input1,input2)); } }