junit 是单元测试框架
eclipse自动继承了这个框架,可以直接添加
1. 搭建 junit运行环境
- 方式一
选中项目 ----> bulidPath ----> config build ----> path ---->选中library ----> add library ----> junit 4 ---->apply
- 方式二
直接添加@Test
注解在方法上会报错,提示 add Libarary
添加指定的 junit library
2. 测试结果参数
-
进度条
- 绿色为测试通过
- 红色为测试不通过
-
Error:程序出现运行时异常(RuntimeException)
-
failtures:实际结果和预期结果不一致
-
断言测试
Assert.assertEquals(A, B)
;:用于比较实际结果与预期结果@Test public void demo03() { Math m = new Math(); int a = 1; int b = 2; int c = m.add(a, b); // 断言测试:c方法执行的结果,4我们预期的方法执行结果 // Assert是junit提供的类,有断言测试方法assertEquals assertEquals(c,4); System.out.println(c); } }
-
2.1 静态导入
- 如果只想调用 assertEquals 静态方法,可以使用静态导入
//该包的导入使用了静态权限修饰符,通过导入Assert包中的某个方法assertEquals
import static org.junit.Assert.assertEquals;
3. 测试中的注解
-
@Before
:在 @Test标记的方法之前执行,用于初始化数据 -
@After
:在@Test标记的方法之后执行,用于释放资源
public class Test {
Math math = null;
@Before // 在测试方法测试之前执行的方法
public void init() {
// 把math这个对象放到方法外面提升math的作用域
math = new Math();
System.out.println(" hello,我在test之前执行");
}
@After // 在测试方法测试之后执行的方法
public void destory() {
System.out.println(" hello,我在test后面执行的方法");
}
@Test
public void dmeo01() {
int a = math.add(2, 3);
System.out.println( a);
}
@Test
public void dmeo02() {
int mul = math.mul(3, 1);
System.out.println(mul);
}
}