本人正在学习单元测试,在使用Juni4参数化测试的时候遇到一些问题。主要问题是,如何做对象的参数化,网上关于Junit4参数化的例子基本都是算术题,太easy,在真正实战中我想肯定要复杂的多,对于我们初学者来讲,尤其是俺们自学的同学,复杂的参数怎么做,几乎没有指引啊。经过一点努力,小可终于发掘出了点名堂,现在写来于大家分享一下,如有不当之处,请大家一起修正,欢迎讨论共进步啊。- package main.java;
public class Triangle {
protected long SideA=0;
protected long SideB=0;
protected long SideC=0;
public Triangle(long A,long B, long C){//构造函数
this.SideA=A;
this.SideB=B;
this.SideC=C;
}
public boolean isTriangle(Triangle triangle){//判断是否为三角形
boolean istrue=false;
...
return istrue;
}
public String isType(Triangle triangle){//判断三角形的类型
String strtype="";
...
return strtype;
}
测试类如下:
- package test.cc;
- import static org.junit.Assert.assertEquals;
- 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;
- import main.java.Triangle;
-
-
-
-
- @RunWith(Parameterized.class)
- public class TriangleTest {
- private long param1;
- private long param2;
- private long param3;
- private boolean expected=false;
- private String exp_type="";
-
-
-
-
-
-
-
-
-
-
- @Parameters
- @SuppressWarnings("unchecked")
- public static Collection date(){
- //将所有测试数据放在object数组对象中
- //object数组对象可使用任意数据类型
- //实际测试时 自己加入更多的测试数据
- Object[][] object={{3,4,5,true,"scalene triangle"},
- {-3,-4,-5,false,"not a triangle"},
- {2,3,5,false,"not a triangle"},
- {3,3,3,true,"equilateral triangle"},
- {5,3,3,true,"isosceles triangle"}}
- return Arrays.asList(object);
- }
- /*此构造函数不可缺少,并且参数要和参数结合中的类型及数量一致*/
- public TriangleTest(long param1,long param2,long param3,boolean expected,String type){
- this.param1=param1;
- this.param2=param2;
- this.param3=param3;
- this.expected=expected;
- this.exp_type=type;
- }
- @Test
- public void testistriangle(){
- //生成对象时,直接将结合中的参数传入即可
- Triangle triangle=new Triangle(param1,param2,param3);
- boolean result=triangle.isTriangle(triangle);
- assertEquals(expected,result);
- }
- @Test
- public void testistype(){
- Triangle triangle=new Triangle(param1,param2,param3);
- String result_type=triangle.isType(triangle);
- assertEquals(exp_type,result_type);
- }
}
运行结果通过,如下图:(实际测试时可以加入更多的测试数据)