Junit--参数化测试

为保证单元测试的严谨性,咱们模拟了不一样的状况来测试方法,为此写了大量的单元测试方法。可是这些方法都差很少只是参数和指望值不一样,如今使用Junit的参数化测试能很好的应对这个问题java

参数化测试的编写稍微有点麻烦函数

1.  为准备使用参数化测试的测试类指定特殊的运行器org.junit.runners.Parameterized。
2.  为测试类声明几个变量,分别用于存放指望值和测试所用数据。
3.  为测试类提供参数的方法声明一个使用注解org.junit.runners.Parameterized.Parameters 修饰的,返回值为java.util.Collection 的公共静态方法,并在此方法中初始化全部须要测试的参数对。
4.  为测试类声明一个带有参数的公共构造函数,并在其中为第二个环节中声明的几个变量赋值。
5.  编写测试方法,使用定义的变量做为参数进行测试。单元测试

package com.tiamaes.junit;

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 TestWordDealUtilWithParam {
	
	private String expected;
	private String target;
	
	@SuppressWarnings("rawtypes")
	@Parameters
	public static Collection words(){
		return Arrays.asList(new Object[][]{
				{"EMPLOYEE_INFO","employeeInfo"},	//正常状况
				{null,null},						//参数为null
				{"",""},							//空字符串
				{"EMPLOYEE_INFO","EmployeeInfo"},	//首字母大写
				{"EMPLOYEE_INFO_A","EmployeeInfoA"},//尾字母大写
				{"EMPLOYEE_A_INFO","EmployeeAInfo"}	//多个大写字母相连
		});
	}
	
	public TestWordDealUtilWithParam(String expected,String target){
		this.expected = expected;
		this.target = target;
	}
	
	@Test
	public void testWordFomat4DB() {
		assertEquals(this.expected, WordDealUtil.wordFomat4DB(this.target));
	}
	
}