您的位置:首页 > 其它

JUNIT(Parameterized运行参数化测试)

2015-06-09 21:19 453 查看
Parameterized的测试运行期允许使用者使用不同参数多次运行同一个测试。
我们假设,有一个方法,可以返回两个字符串拼接之后的值,简单的说str1  + str2的结果。然后我们要测试一下我们的实现是否符合逻辑,一般需要多次传入参数来测试,才能达到目的。如果我们要测试3组入参,执行3次test还是可以接受的,但是如果是一组数据呢,可能成千上万,这样要是人工测试就累死了。介绍一下junit的运行参数化测试。
两个字符串的拼接我们直接卸载测试方法中不重新创建类了,那样比较繁琐。


package org.csdn.hxq.junit.paramterized;

import static org.junit.Assert.*;

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(value = Parameterized.class)
public class StringTest {

private String a;
private String b;
private String c;

public StringTest(String a,String b,String c){
this.a = a;
this.b = b;
this.c = c;
};

@Parameters
public static Collection<String []> getParams(){
return Arrays.asList(new String [][]{
{"a","b","ab"},
{"a","b","ab1"},
});
}

@Test
public void test(){
assertEquals(re(a,b), c);
}

public String re(String a,String b){
return a+b;
}

}


这里值得注意的是:

1.runwith中使用value = Parameterized.class。

2.必须提供@Parameters方法,方法签名必须是public static Collection,不能有参数,并且collection元素必须是相同长度的数组。同事数组的长度必须与唯一的公共构造函数的参数数量相匹配。在本例中,我们数组的长度是3,构造方法的参数数量也是3,并且类型匹配。

3.之后执行test方法,并且调用了我们提供的参数。



在图中我们可以看到,依次调用了我们的参数进行断言,结果符合预想。

注意:不能有多个构造方法,否则会报错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: