一 前奏
Junit3.x系列基于反射。对测试类要求 必须继承junit.framework.TestCase这个抽象类。
对测试函数要求:
a) 函数名以test开头。
b) public +void + 没有参数+ 不会throws Exception
二 我的简单应用
编写一个类ArrayOperator,实现一个方法getMaxElment(),该方法为找出一个int数组的最大值。 编写测试类ArrayTestCase,测试该方法getMaxElment()。
1)结构
在工程build path中add libraries把Junit3 添加进去工程中。接着创建新的fold名为test。把测试类和源代码分离开是一个好做法。 注意技巧:将 被测试的类与测试类放在同一个包名下(尽管它们不在同一个文件夹中),这样在测试类中就不必再导包了。
2)代码
package com.sysu.junit3;
public class ArrayOperator {
public int getMaxElment(int[] args) throws Exception {
if (args == null || args.length == 0) //短路求值 ,若args.length == 0 放前,则当数组为空时,会抛出NullPointerException异常
throw new Exception("not null.");
int max = args[0];
for (int i = 0; i < args.length; i++) {
if (max < args[i])
max = args[i];
}
return max;
}
}
当数组指向null 时,条件判断结束,不会再执行args.length == 0 ,这是基于短路求值。例如eg :
expr1 && expr2 //若expr1计算后若为false,则不再计算expr2的值,因为该式肯定为false。否则,计算expr2的值。
expr1 || expr2 //若expr1计算后若为true,则不再计算expr2的值,因为该式肯定为true。否则,计算expr2的值 。
短路求值 ,若args.length == 0 放前,则当数组为空时,会抛出NullPointerException异常
package com.sysu.junit3;
import junit.framework.Assert;
import junit.framework.TestCase;
public class ArrayTestCase extends TestCase {
private ArrayOperator arrayCase = null;
@Override
protected void setUp() throws Exception { //重写setUp方法。它在每个测试函数前执行
arrayCase = new ArrayOperator();
}
public void testGetMaxELMENT() {
int max = 0;
try {
max = arrayCase.getMaxElment(new int[] { 23, 34, 1, 43, 43, 21, 4,
34, -4, 0 });
} catch (Exception e) {
Assert.fail("error 1"); //正常情况下,程序无误情况下,不会执行catch中内容;否则,failure
}
Assert.assertEquals(43, max); //Assert为TestCase父类,
}
public void testGetMaxELMENTwithException() {
Throwable exception = null;
int max = -6;
try {
max = arrayCase.getMaxElment(new int[] {});
Assert.fail("error 2"); //正常情况下,程序无误情况下,会跳过该语句;否则,failure
} catch (Exception e) {
exception = e;
}
Assert.assertNotNull(exception);
Assert.assertEquals(-6, max);
Assert.assertEquals(Exception.class, exception.getClass()); //判断 抛出的异常是否和 预期的 异常 类型相同(即Class对象相同)
Assert.assertEquals("not null.", exception.getMessage());
}
public void testCAseMAXelment3() {
Throwable ex = null;
int array[] = null;
try {
arrayCase.getMaxElment(array);
Assert.fail(); //正常情况下,程序无误情况下,会跳过该语句;否则,failure
} catch (Exception e) {
ex = e;
}
Assert.assertNotNull(ex);
Assert.assertEquals(Exception.class, ex.getClass());
Assert.assertEquals("not null.", ex.getMessage());
}
}
3)结果
通过了3个测试方法: