IDEA 单元测试 导入JUnit4到项目

一、IDEA自带JUnit4的jar包,现在让我们来导入。 

Step 1. IDEA最上面一栏的菜单栏中,选File->Project Structure(从上往下第11个),弹出窗口左边有一个列表,选Module。

Step 2. 右侧有一个带3个标签的窗口,选Dependencies标签

Step 3. 下面的列表框列出了项目的jar包,右侧有个绿色的'+'号,左键点击,在左键菜单里选第一个

Step 4. 在弹出的文件浏览窗口,选择"IDEA的安装目录libjunit-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的安装目录libhamcrest-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);
    }
}
原文地址:https://www.cnblogs.com/junhuawang/p/6952748.html