这次来学习一下参数化测试功能,可以用来批量验证数据集
代码如下:
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
/**
* 判断时间是否有重合 并学习参数化测试方法 依赖 junit 包
*
* Creted by Dean on 2019-05-22.
*/
@RunWith(Parameterized.class) //此注解语句必须加在这里
public class DateDuplicateParameterizedTests {
//此注解需要 加在 返回待测试的 数据集 方法 上
@Parameterized.Parameters
//必须为 static 方法,返回类型必须为 Collection
public static Collection data() {
String timeStartPostfix = " 00:00:00";
String timeEndPostfix = " 23:59:59";
Date oldStartDate = parseDateTime("2019-05-01" + timeStartPostfix);
Date oldEndDate = parseDateTime("2019-05-31" + timeEndPostfix);
return Arrays.asList(new Object[][]{
{parseDateTime("2019-04-01" + timeStartPostfix), parseDateTime("2019-05-04" + timeEndPostfix), oldStartDate, oldEndDate, "不通过"},
{parseDateTime("2019-05-04" + timeStartPostfix), parseDateTime("2019-06-04" + timeEndPostfix), oldStartDate, oldEndDate, "不通过"},
{parseDateTime("2019-05-01" + timeStartPostfix), parseDateTime("2019-05-15" + timeEndPostfix), oldStartDate, oldEndDate, "不通过"},
{parseDateTime("2019-05-10" + timeStartPostfix), parseDateTime("2019-05-31" + timeEndPostfix), oldStartDate, oldEndDate, "不通过"},
{parseDateTime("2019-05-01" + timeStartPostfix), parseDateTime("2019-05-31" + timeEndPostfix), oldStartDate, oldEndDate, "不通过"},
{parseDateTime("2019-05-10" + timeStartPostfix), parseDateTime("2019-05-20" + timeEndPostfix), oldStartDate, oldEndDate, "不通过"},
{parseDateTime("2019-04-01" + timeStartPostfix), parseDateTime("2019-06-01" + timeEndPostfix), oldStartDate, oldEndDate, "不通过"},
{parseDateTime("2019-03-01" + timeStartPostfix), parseDateTime("2019-04-01" + timeEndPostfix), oldStartDate, oldEndDate, "通过"},
{parseDateTime("2019-06-01" + timeStartPostfix), parseDateTime("2019-07-01" + timeEndPostfix), oldStartDate, oldEndDate, "通过"},
});
}
/** 以下 成员 变量 对应 数据集中的 数据项 */
private Date newStartDate;
private Date newEndDate;
private Date oldStartDate;
private Date oldEndDate;
private String expected;
/** 构造器 参数 需要与 数据集中的 数据项 顺序对应 */
public DateDuplicateParameterizedTests(Date newStartDate, Date newEndDate, Date oldStartDate, Date oldEndDate, String expected) {
this.newStartDate = newStartDate;
this.newEndDate = newEndDate;
this.oldStartDate = oldStartDate;
this.oldEndDate = oldEndDate;
this.expected = expected;
}
@Test
public void checkDateDuplicate(){
boolean result = ! (newStartDate.after(oldEndDate) || newEndDate.before(oldStartDate));
Assert.assertEquals(expected, result ? "不通过" : "通过");
}
/** 时间解析工具方法 */
private static Date parseDateTime(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return format.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}