首页 > 学院 > 开发设计 > 正文

Parameterized unit tests with JUnit 4

2019-11-09 16:10:36
字体:
来源:转载
供稿:网友

前面已经分析过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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表