最近单元测试中写的一个Assert

该类提供的assert方法主要针对数据库的单元测试中, 使用Spring JdbcTemplate得到一个记录集, 然后与实际操作记录进行比对验证

public class MyAssert {

/**
* @param expected
* @param actual
* @param propertyNames
*/
public static void assertPropertyEquals(Object expected, Object actual,
String... propertyNames) {
for (String propertyName : propertyNames) {
try {
Object expectedValue = PropertyUtils.getProperty(expected,
propertyName);
Object actualValue = PropertyUtils.getProperty(actual,
propertyName);
if (expectedValue instanceof Date && actualValue instanceof Date) {
Assert.assertEquals(((Date)expectedValue).getTime(), ((Date)actualValue).getTime());
}else {
Assert.assertEquals(expectedValue, actualValue);
}
} catch (Exception e) {
throw new RuntimeException("比较" + expected + " 和 " + actual
+ "的属性" + propertyName + "失败!", e);
}
}
}

/**
* 指定map中的某个字段的值与期望的值相等
*
* @param map
* 一条记录
* @param fieldName
* 字段名(不区分大小写)
* @param expectValue
*/
@SuppressWarnings("unchecked")
public static void assertMapEquals(Map map, String fieldName,
Object expectValue) {
assertEquals(expectValue + "", map.get(fieldName.toUpperCase()) + "");
}

/**
* 对实际得到的列表中指定的字段(一般是主键)与期望的值进行比较是否相等
*
* @param <T>
* @param actualList
* @param fieldName
* 表的字段或者bean的属性名
* @param expectValues
*/
@SuppressWarnings("unchecked")
public static <T> void assertListEquals(List actualList, String fieldName,
T... expectValues) {
assertEquals(actualList.size(), expectValues.length);

for (Object entry : actualList) {
String actualValue = getActualValue(entry, fieldName);
boolean found = false;

for (T value : expectValues) {
if (actualValue.equals(value + "")) {
found = true;

break;
}
}

if (!found) {
Assert.fail("要查找的[" + actualValue + "]在查找到的结果记录集[" + actualList
+ "]中不存在");
}
}
}

/**
* entry可能为两种类型:Map和JavaBean, 分别取出里面指定key或属性的值
*
* @param entry
* @param fieldName
* @return
*/
@SuppressWarnings("unchecked")
private static String getActualValue(Object entry, String fieldName) {
Object actualValue;

if (entry instanceof Map) {
actualValue = ((Map) entry).get(fieldName.toUpperCase());
} else {// 取得指定javabean的某个属性的值
try {
actualValue = new PropertyUtilsBean().getSimpleProperty(entry,
fieldName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

return actualValue + "";
}

}

用法(里面借助了Spring的JdbcTemplate来做数据库查询):


Map map = queryForMap("select * from spu where spu_id = " + spu.getId());
MyAssert.assertMapEquals(map, "title", spuMock.getName());


List<Map> list = queryForList("select * from spu_image where spu_id = "
+ spuMock.getId());
MyAssert.assertListEquals(list, "image_url", otherImageMock.getUrl(),
anotherImageMock.getUrl(), spuPropertyImageMock.getUrl());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值