JUnit使用参数测试和一组测试

发表于:2015-8-19 10:36

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:blfshiye    来源:51Testing软件测试网采编

  参数测试
  作为替代阵列int a0,a1,a2喜欢,当测试加法assertEquals(3.0, h.add(1, 2), 0.1);相当于声明一个变量,要測试100个怎么办。
  所以,有了參数化測试,使用一个Collection收集全部的数据——加法时每一次測试须要的几个数据构成一组,n个组构成Collection。
  然后依照JUnit的使用方法要求,写出单元測试类。(偷懒一下,不想写被測试的业务类X了。
  以下的样例中如果要測试的方法是,推断一个数是否奇数。)
package myTest.param;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)//1.必须
public class ParametTestUnit {
private int input;
private boolean expected;//expected result
/**
* 2.public 构造器赋值一组測试数据
*/
public ParametTestUnit(int input,boolean expected ) {
this.input = input;
this.expected = expected;
}
/**
* 3.由@Parameterized.Parameters修饰一个
* public static Collection xxx()
*/
@Parameterized.Parameters
public static Collection data() {
return Arrays.asList(new Object[][] {
{ 1, true },
{ 3, true },//
{ 6, false },
{ 11, true },
{ 22, false },
{ 23, true }
});
}
/**
* 4.JUnit循环地使用各组数据
*/
@Test
public void testOdd() {
System.out.println("Parameterized Number is : " + input);
assertEquals(expected, input%2!=0);
}
}
  如今这个单元測试类编写完毕,可是在BlueJ中不可以直接执行它(不支持?)。自己写一个Main好了。
package myTest.param;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class Main {
public static void go() {
Result result = JUnitCore.runClasses(ParametTestUnit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号