JUnit基础学习笔记,记录了基本的使用方式和常用命令。(该工具使用比较简单)
JUnit简介
什么是JUnit?
单元测试的工具,能提供自动化测试。
- 官方网站:www.junit.org
- 版本:junit4.12
- 下载地址:https://github.com/junit-team/junit4/wiki/Download-and-Install
- junit会用到hamcrest的断言机制,所以需要导入hamcrest-core-1.3.jar包
- Java断言(assert)一般作用于代码的单元测试中。
使用步骤
- 创建一个测试类,加载“import org.junit.”包和“import static org.junit.Assert.”包。
- 在需要测试的方法前加入注释命令(如@Test等)。
- 创建测试方法,增加错误条件(如结果不相同、超时等)
- 开启测试,如果满足测试条件则通过测试。
常用命令
注解命令 | 说明 |
---|---|
@Test | 表示这是一个测试方法 |
@Ingore | 跳过该条方法 |
@Before | 表示在所有方法运行前运行的方法;所有测试场景在执行前都会先执行该关键字修饰的方法 |
@After | 表示在所有的方法运行之后执行的方法;关闭数据库时执行该关键字修饰的方法 |
@Suite.SuiteClasses({}) | 打包所有需要测试的类 |
@FixMethodOrder(MethodSorters.JVM) |
参数设置 | 说明 |
---|---|
expected = Exception.class | 会抛出方法异常 |
timeout = 1000 | 超时1秒就算作错误 |
案例
案例1
测试RefectTest1类
- 如果FieldTest1方法在1秒内执行完不出错,则通过测试。
- 通过Add方法添加数值,如果getResult()的返回值等于4,则通过测试。(使用断言辅助测试)
- 如果执行divide(0)方法出现异常,则通过测试。
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class ReflectTest1Test {
@Test(timeout=1000)
public void testFieldTest1() {
ReflectTest1.mequalsAddress();
}
@Test
public void testAdd(){
ReflectTest1.add(2);
ReflectTest1.add(2);
//断言关键字
assertEquals(4,c.getResult());
}
@Test(expected=Exception.class)
public void testDivide() throw Exception{
ReflectTest1.divide(0);
}
}