IDEA 單元測試 導入JUnit4到項目


 

一、IDEA自帶JUnit4的jar包,現在讓我們來導入。 

Step 1. IDEA最上面一欄的菜單欄中,選File->Project Structure(從上往下第11個),彈出窗口左邊有一個列表,選Module。

Step 2. 右側有一個帶3個標簽的窗口,選Dependencies標簽

Step 3. 下面的列表框列出了項目的jar包,右側有個綠色的'+'號,左鍵點擊,在左鍵菜單里選第一個

Step 4. 在彈出的文件瀏覽窗口,選擇"IDEA的安裝目錄\lib\junit-4.11.jar" 選完后別忘了點擊對號和OK

 

測試類寫好后右鍵測試類名,在右鍵菜單選 Run ‘AddOperationTest’,一切似乎就要搞定了

等等,突然報錯,輸出窗口里一行令人不悅的紅字出現了

    Java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

這個錯誤的原因是,junit-4.11版本還需要一個jar包叫做hamcrest(IDEA官方幫助傳送門htt把ps://ww中w.jetbrains.c文om/idea/help/去configuring-testing-libraries.h掉tml)

在上面的Step 4.中,還需要選擇"IDEA的安裝目錄\lib\hamcrest-core-1.3.jar"

 

二、單元測試

import static org.junit.Assert.assertEquals;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.MyMath;
//單元測試
public class MyMathTest {
    
    private static MyMath mm;
    
//    @Before  //每個測試方法執行前自動調用
    @BeforeClass //加載類的字節碼時就執行,只執行一次
    public static void init(){
        mm = new MyMath();
    }
//    @After
    @AfterClass
    public static void destory(){
        mm = null;
    }
    
    /*
     * 測試方法:用於測試的方法
     * 1、必須是pulbic的
     * 2、必須沒有返回值
     * 3、方法參數為空
     * 4、有@Test注解
     */
    
    @Test
    public void testAdd() {
//        MyMath mm = new MyMath();
        int result = mm.add(1, 2);
        // 斷言
        assertEquals(3, result);//期望值和實際運行結果進行比對。成功,綠色的bar
    }

    @Test
    public void testDivide() {
//        MyMath mm = new MyMath();
        int result = mm.divide(10, 2);
        assertEquals(5, result);
    }
    
    //測試異常
    @Test(expected=java.lang.ArithmeticException.class)
    public void testException() {
//        MyMath mm = new MyMath();
        mm.divide(10, 0);
    }
    //測試方法的執行效率
    @Test(timeout=100)//即使期望值和實際值相同的。超出運行時間,也是失敗的。time指定的值為毫秒值。
    public void testEfficiency() {
//        MyMath mm = new MyMath();
        int result = mm.add(1, 2);
        // 斷言
        assertEquals(3, result);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM