前面已經分析過junit單元測試的用法,這篇詳細學習junit4的參數化測試
格式
在測試類上面添加 @RunWith(Parameterized.class)
提供資料集合使用 @Parameterized.Parameters(),提供的資料集合必須傳回
一個數組類型的集合
@Parameterized.Parameters()
public static Iterable
原理
測試運作器被調用時,将執行資料生成方法,和它将傳回一組數組,每個數組是一組測試資料。測試運作器将執行個體化類和第一組測試資料傳遞給構造函數。構造函數将存儲資料的字段。然後将執行每個測試方法,每個測試方法獲得,第一組測試資料。每個測試方法執行後,對象将被執行個體化,這一次使用集合中的第二個元素的數組,等等。
代碼分析
該測試用例,用來測試時間格式化。
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
/**
* Created by weichyang on 2017/2/7.
* 參數序列測試
*/
@RunWith(Parameterized.class)
public class FrommatUtilTest {
private boolean mExpected = true;
private Long[] mArgs;
@Parameterized.Parameters()
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][]{
{false, new Long[]{1483490840155l, 1483499648767l}},
{false, new Long[]{0l, 1483499648767l}},
{false, new Long[]{112120l, 0l}},
{false, new Long[]{1483413248767l, 1483499648767l}},
{false, new Long[]{1480648448767l, 1483499648767l}},
{false, new Long[]{1480648448767l - (10 * 86400000), 1483499648767l}}
});
}
public FrommatUtilTest(boolean expected, Long... args) {
mExpected = expected;
mArgs = args;
}
@Test
public void showTimeState() throws Exception {
Assert.assertEquals(mExpected, FrommatUtil.showTimeState(mArgs[0], mArgs[1]));
}
}
被測試方法
/**
* @param sellOutMillisecond 售罄時間
* @param curTimeMillisecond 目前時間
* @return
*/
public static String showTimeState(long sellOutMillisecond, long curTimeMillisecond) {
long calculateTime = curTimeMillisecond - sellOutMillisecond;
if (calculateTime <= 0 || sellOutMillisecond <= 0) {
return "剛剛";
}
// LogUtil.d("sellOutMillisecond =" + sellOutMillisecond
// + " curTimeMillisecond =" + curTimeMillisecond +
// " calculateTime=" + calculateTime);
long days = calculateTime / (1000 * 60 * 60 * 24);
long hours = (calculateTime - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
String returnValue = "";
if (days > 0 || hours > 23) {
//顯示日期
DateFormat formatter = new SimpleDateFormat("M月d日");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(sellOutMillisecond);
returnValue = formatter.format(calendar.getTime());
} else if (days <= 0 && hours >= 1 && hours <= 23) {
//顯示小時數
returnValue = hours + "小時前";
} else if (days == 0 && hours == 0) {
returnValue = "剛剛";
}
return returnValue;
}
輸出結果:會給出計算的值和期望的值對比,這裡是測試期望的值無意義。