软件测试-单元测试-参数化

通过注解来绑定测试参数

package testPacage;

import static org.junit.Assert.*;

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

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

@RunWith(Parameterized.class)
public class Test04Test2 {
	
	Test04 t = new Test04();
	
	@Parameter(value = 0)
	public String lett;
	
	@Parameter(value = 1)
	public String result;

	@Parameters
	public static Collection data() {
		return Arrays.asList(new Object[][] {{"ab123", "替换前缀后的字符串为:ef123"}, 
			{"32cd1cd", "替换cd后的字符串为:32gh1gh"}, 
			{"ab123cd", "大写字母的字符串为:AB123CD"}});
	}

	@Test
	public void test() {
		Assert.assertEquals(result, t.testFun(lett));
		System.out.println("result = " + result);
	}

}

参数化测试的必要部分:

  1. @RunWith(Parameterized.class),表示在测试方法类上
  2. @Parameters,表示在参数列表方法上
  3. 参数列表方法,必须返回Collection类型,必须是static修饰的静态方法,将被测方法的入参和预期结果依次填入数组中(保持前后顺序)
  4. @Parameter(value = ),使用注解绑定测试参数,value表示索引,从0开始,如:参数列表方法中有{"abc","字符:abc"},前者是入参,后者是预期结果,则
    @Parameter(value = 0)
    public String chars;
    
    @Parameter(value = 1)
    public String result;
    
  5. 切记,使用注解绑定测试参数时,变量一定使用public修饰
  6. 使用断言时就可以直接使用定义好的参数了

       

通过构造函数来绑定测试参数

package testPacage;

import static org.junit.Assert.*;

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

import org.junit.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 Test04Test2 {
	
	Test04 t = new Test04();
	
	private String lett;
	private String result;
	
	public Test04Test2(String lett, String result){
		this.lett = lett;
		this.result = result;
	}
	
	@Parameters
	public static Collection data() {
		return Arrays.asList(new Object[][] {{"ab123", "替换前缀后的字符串为:ef123"}, 
			{"32cd1cd", "替换cd后的字符串为:32gh1gh"}, 
			{"ab123cd", "大写字母的字符串为:AB123CD"}});
	}

	@Test
	public void test() {
		Assert.assertEquals(result, t.testFun(lett));
		System.out.println("result = " + result);
	}

}
  1. 新建构造函数,入参的顺序要与参数列表方法中的顺序一样
  2. 后续的使用方法同上
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值