這次來學習一下參數化測試功能,可以用來批量驗證數據集
代碼如下:
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;
}
}