最近写单测,需要枚举对象的元素来比对,感觉太麻烦了:
@Test
public void get_on_normalCase() {
User result = get();
User expected = generateExpected();
assertEquals(expected.getBuyerId(), result.getBuyerId());
assertEquals(expected.getFansId(), result.getFansId());
assertEquals(expected.getFansType(), result.getFansType());
assertEquals(expected.getNobody(), expected.getNobody());
}
spring bean中有个方便的方法:
BeanUtils.copyProperties(activity, target);
于是打算参考一下它的源码,实现一个通用的数据检验。
原理其实也挺简单,基本上就是一个反射,一个调用java bean信息的接口就可以实现了。
import com.dpriest.tool.automan.User;
import org.junit.Test;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* Created by zhangwenhao on 13/12/2017.
*/
public class DataComparator {
/**
* @param expected expected value
* @param actual the value to check against <code>expected</code>
*/
public static void compare(Object expected, Object actual) {
Class<?> expectedClass = expected.getClass();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(expectedClass);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method readMethod = propertyDescriptor.getReadMethod();
Object expectedValue = readMethod.invoke(expected);
Object actualValue = readMethod.invoke(actual);
if (!expectedValue.equals(actualValue)) {
fail(propertyDescriptor.getName() + " not equal \nexpected:" + expectedValue + "\n"
+ "actual:" + actualValue);
}
}
} catch (Exception e) {
fail(e.getMessage());
}
}
}
最后直接引入DataComparator就可以比较了,非常方便:
@Test
public void get_on_normalCaseV2() {
User result = get();
User expected = generateExpected();
DataComparator.compare(expected, result);
}
这个工具类目前仅支持简单对象属性,集合对象属性可以稍微改一下就可以用了。
网友评论