该类提供的assert方法主要针对数据库的单元测试中, 使用Spring JdbcTemplate得到一个记录集, 然后与实际操作记录进行比对验证
用法(里面借助了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());