`

junit4的参数化测试

阅读更多

 

     我感觉它的设计意图就是为了解决我们有时候测试的时候,测试数据的构造不同,其他的均相同的情况下可能比较有用

 

    参数化测试的编写稍微有点麻烦(当然这是相对于 JUnit 中其它特性而言):

1. 为准备使用参数化测试的测试类指定特殊的运行器 org.junit.runners.Parameterized。

2. 为测试类声明几个变量,分别用于存放期望值和测试所用数据。

3. 为测试类声明一个使用注解 org.junit.runners.Parameterized.Parameters 修饰的,

返回值为 java.util.Collection 的公共静态方法,并在此方法中初始化所有需要测试的参数对。

4. 为测试类声明一个带有参数的公共构造函数,并在其中为第二个环节中声明的几个变量赋值。

5. 编写测试方法,使用定义的变量作为参数进行测试。

 

 

 

	import java.util.Collection;

	import junit.framework.Assert;

	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 ParameterizedTest {
		private String extected;
		private String target;
		
		public ParameterizedTest(String target,String extected) {
			super();
			this.target = target;
			this.extected = extected;
		}
		
		@Parameters
		public static Collection<?> contructData(){
			return Arrays.asList(new Object[][]{
					{"aaa","AAA"},
					{null,null},
					{"",""},
					{"BBB","BBB"}
			});
		}
		
		@Parameters
		public static Collection<?> contructData1(){
			return Arrays.asList(new Object[][]{
					{"aaa1","AAA1"},
					{null,null},
					{"",""},
					{"BBB1","BBB1"}
			});
		}
		
		public String toUpperCase(String str){
			if(null == str){
				return str;
			}
			return str.toUpperCase();
		}
		
		@Test
		public void testUpperCase(){
			Assert.assertEquals(extected, toUpperCase(target));
		}
	}
 

    同时,感觉这个地方实现的不好的地方就是整个类只有第一个标有@Parameters的static静态方法起作用,也就

限制了它的灵活使用。随便看下它里面对注解的处理部分

 

List<FrameworkMethod> methods= testClass

				.getAnnotatedMethods(Parameters.class);
		for (FrameworkMethod each : methods) {
			int modifiers= each.getMethod().getModifiers();
			if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))
				return each;
		}

 

实际上它是找到第一个就返回了,其实我们如果为了灵活的话,可以再标注下,然后去找一个特殊的方法,然后多个方法的parametrized的测试就可以放到一个类里面了。当然这么做的话,肯定有有一些其他的不好的地方。

 

分享到:
评论
4 楼 asialee 2015-02-10  
蓝月儿 写道
如果有多个参数的话,这些参数和期望输出怎么写呢

你是说不是一个? 我感觉value可以传递一个json的string对象,在测试例子里面再反向序列化回来,我的qq: 327379252
3 楼 蓝月儿 2015-02-04  
如果有多个参数的话,这些参数和期望输出怎么写呢
2 楼 asialee 2012-07-06  
僧_唐 写道
之前没有注意,看了你的文章才发现 只有第一个@Parametrized 标记的方法才有用。受益

是的,我看了实现,发现是这样
1 楼 僧_唐 2012-07-06  
之前没有注意,看了你的文章才发现 只有第一个@Parametrized 标记的方法才有用。受益

相关推荐

Global site tag (gtag.js) - Google Analytics