ITeye博客

JUNIT4 笔记(八) 参数化测试

mwhgJava · 2010-10-08 08:26 · JUnit4 · 编程语言 · Markdown

为了用不同的参数测试同一个逻辑,需要写多个测试用例,出现代码冗余。一种不是很好的解决方案是在一个测试用例中采用循环的方式遍历参数。

@Test public void testAdd(){
		int[][] array = new int[][]{
				{2,1,1}, //1+1=2,能成功
				{6,2,2}, //2+2!=6,不能成功
				{7,2,5}, //2+5=7,能成功				
		};		
		for(int i=0; i<array.length; i++){
			assertEquals(array[i][2], array[i][0]+array[i][1]);
		}		
	}

这样在执行时有几个问题:1、出错了,难以精确定位是哪一对参数出错。2、前面的数据不能执行成功,后面的数据就不执行了。(上面的例子,2+5=7就不会执行)。

为了解决这个问题: 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;

@RunWith(Parameterized.class)
public class MyTestcase {
	private int sum ;
	private int firstAddend;
	private int secondAddend;
	
	@Parameters
	public static Collection<Integer[]> getData(){
		return Arrays.asList(new Integer[][]{
				{2,1,1},
				{6,2,2}, 
				{7,2,5},				
		});
	}
	
	public MyTestcase(int sum, int firstAddend, int secondAddend){
		this.sum = sum;
		this.firstAddend = firstAddend;
		this.secondAddend = secondAddend;
	}
	
	@Test public void testDivide(){
		assertEquals(sum, firstAddend + secondAddend);
	}
}

执行时,为每套参数创建一个测试类实例,这样就解决了刚才的两个问题:

说明: @RunWith(Parameterized.class):@RunWith用来指定测试运行器,这里指定的运行器是Parameterized.class。 @Parameters: 指定测试用例构成器使用的参数,要求是公有无参数的类方法,返回值要求能够造型为Collection。在实例化测试类时,将Object数组传给其构造器。 构造器:一般测试类可以采用Java默认的构造器,参数化测试类要求与@Parameters修饰的获取参数的方法的返回值对应。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。