最近这几天正在学习 junit , junit 在我们日常的开发工作会发挥很大的作用,但是在使用 junit 的过程中如何写出正确的测试用例,也是一个很有技巧的事情,有的时候对于一个类中的某个方法写测试用例,一个方法要写出几个测试用例,这样才能保证从各个方面对于该方法做出测试,保证程序的正确性。
同时,现在的 junit 也出现了分裂的局面,比较重要的两个版本是 junit3.8 和 junit4.X ,这两个版本中 junit 的实现和使用都存在着很大的区别,其中 junit4.X 中主要是使用 Annotation 来实现,现在主要介绍 junit3.8 的使用:
Largest.java 这个类中的 getLargest 方法主要是获取一个整型数组中的最大值:
package com.junit;
/**
*
* <p>
* Title: 获取一个整形数组中最大的数
* </p>
* <p>
* Description:
* </p>
* @version 1.0
* @author 董宗磊
* @date 2012-2-9
*/
public class Largest {
public int getLargest(int array[]) throws Exception{
if(null == array || 0 == array.length){
throw new Exception(" 数组不能为空 ");
}
int result = array[0];
for (int i = 0; i < array.length; i++) {
if(result < array[i]){
result = array[i];
}
}
return result;
}
}
LargestTest.java 中的方法用来测试 Largest.java 中的 getLargest 方法的正确性:
package com.junit;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
*
* <p>
* Title: Largest 类的 junit 测试类
* </p>
* <p>
* Description:
* </p>
* @version 1.0
* @author 董宗磊
* @date 2012-2-9
*/
public class LargestTest extends TestCase {
private Largest largest;
@Override
public void setUp(){
largest = new Largest();
}
/**
* 测试正常执行结果是否正确
*/
public void testGetLargest(){
int array[] = {10,29,89,37,76};
int result = 0;
try {
result = largest.getLargest(array);
} catch (Exception e) {
Assert.fail(" 测试失败 ");
}
assertEquals(89, result);
}
/**
* 测试数组内没有内容时的异常情况
*/
public void testGetLargest2(){
Throwable tw = null;
int array[] = {};
try {
largest.getLargest(array);
Assert.fail(" 测试失败 ");
} catch (Exception e) {
tw = e;
}
Assert.assertNotNull(tw);
Assert.assertEquals(Exception.class, tw.getClass());
Assert.assertEquals(" 数组不能为空 ", tw.getMessage());
}
/**
* 测试数组为空的异常情况
*/
public void testGetLargest3(){
Throwable tw = null;
int array[] = null;
try {
largest.getLargest(array);
Assert.fail(" 测试失败 ");
} catch (Exception e) {
tw = e;
}
Assert.assertNotNull(tw);
Assert.assertEquals(Exception.class, tw.getClass());
Assert.assertEquals(" 数组不能为空 ", tw.getMessage());
}
public static void main(String[] args) {
junit.textui.TestRunner.run(LargestTest.class);
junit.awtui.TestRunner.run(LargestTest.class);
junit.swingui.TestRunner.run(LargestTest.class);
}
}
在这个 junit 的测试类中我们只是对于一个类中的一个方法进行测试,其中 testGetLargest 方法主要测试在正常的情况,数组存在且不为空的情况下是否可以正确的查找出数组中最大的那个数; testGetLargest2 这个方法主要测试在数组存在但是数组中没有内容的情况下,是否可以正常的抛出异常; testGetLargest3 这个方法中主要是测试数组为空的情况下是程序是否可以正常的抛出异常。通过这个小程序我们可以看出,我们只是写一个很小的应用,但是却要对这个方法写出三个测试方法进行全面的测试,所以从这里我们可以看出,编写测试用例也是一项工作量很大的事情。
对于使用 junit3.8 编写测试用例的时候需要有几点需要注意的事情:
1) 编写的测试方法需要以 test 开头,这样 junit3.8 就可以识别这是一个测试方法,执行测试程序,如果不以 test 开头则 junit 默认不会当做测试方法来执行。
2) 编写的测试方法不能带有参数。
3) 编写的测试方法不能有返回值,返回值为 void 。
4) 编写的测试方法应该是 public 。
5) 编写的测试类必须要继承于 TestCase 父类
以上这几条规则是 junit3.8 中一些强制性的规定,但是我们在使用 junit3.8 时还有一些最佳的实践,这些虽不是 junit3.8 的强制性规定,但是却可以提高我们的工作效率:
1) 新建一个名为 test 的 source folder ,用于存放测试类源代码
2) 目标类与测试类应该位于同一个包下面,这样测试类中就不必导入源代码所在的包,因为他们 位于同一个包下面
3) 测试类的命名规则:假如目标类是 Calculator ,那么测试类应该命名为 TestCalculator 或者是 CalculatorTest