前面已經分析過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; }輸出結果:會給出計算的值和期望的值對比,這里是測試期望的值無意義。
參數化測試能夠最大限度的復用測試代碼
引用: Parameterized unit tests with JUnit 4 https://blogs.Oracle.com/jacobc/entry/parameterized_unit_tests_with_junit
新聞熱點
疑難解答