`

JUnit4中的参数化测试

阅读更多
    为了保证单元测试的严谨性,我们模拟了不同的测试数据来测试方法的处理能力,为此我们编写了大量的单元测试方法。这些测试方法都是大同小异:代码结构都是相同的,不同的仅仅是测试数据和期望值。为了解决这个问题,Junit4提供了参数化测试。
   
1)为准备使用参数化测试的测试类指定特殊的运行器,org.junit.runners.Parameterized
2)为测试声明几个变量,非别用于存放期望值和测试所用数据。
3)为测试了类声明一个使用注解org.junit.runners.Parameterized.Parameters修饰的,返回值为java.util.Collection的公共静态方法,并在此方法中初始化所有需要的测试的参数对。
4)为测试类声明一个带有参数的公共构成函数,并在其中为第二个环节中声明的几个变量赋值。

下面是一个测试加法的参数化测试,测试通过程序计算 1+2=3? 0+0=0? -1-3=-4?
package demo.junit4;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;


/**
 * 参数化设置
 * 
 * 1 测试类必须由parameterized测试运行器修饰
 * 2 准备数据,数据的准备需要在一个方法中进行,该方法需要满足一定的要求
 *   1)该方法必须有parameters注解修饰
 *   2)该方法必须为public static的
 *   3)该方法必须返回Collection类型
 *   4)该方法的名字不作要求
 *   5)该方法没有参数
 *   
 *   int.class == Integer.TYPE != Integer.class
 */
// 测试运行器
@RunWith(Parameterized.class)
public class ParameterTest {
	private int expeted;
	private int input1;
	private int input2;
	
	@Parameters
	@SuppressWarnings("unchecked")
	public static Collection perpareData() {
		Object[][] objects = { {3,1,2}, {0,0,0}, {-4,-1,-3} };
		
		return Arrays.asList(objects);
	}
	
	public ParameterTest(int expected, int input1, int input2){
		this.expeted = expected;
		this.input1 = input1;
		this.input2 = input2;
	}
	
	@Test public void testAdd() {
		Calculator cal = new Calculator();
		assertEquals(expeted, cal.add(input1, input2));
	}
}

分享到:
评论
1 楼 lantian_123 2011-04-15  
如果是测试一个数组中最大值该怎么设置参数呢

相关推荐

Global site tag (gtag.js) - Google Analytics