在Junit单元测试中,经常需要对一些领域模型的属性赋值,以便传递给业务类测试,常见的场景如下:
com.enation.javashop.Goods goods = new com.enation.javashop.Goods(); goods.setBrandId(1); goods.setCategoryId(1); goods.setGoodsName("测试商品"); goods.setPrice(1.01); goods.setSn("100001"); goods.setWeight(1.01);
如果领域模型的属性特别多,手工去写set方法令人发指,写了一个生成的工具类,用法如下:
String mockCode = MockDataGenerator.create(Goods.class);
生成结果:
com.enation.javashop.Goods goods = new com.enation.javashop.Goods(); goods.setBrandId(819); goods.setCategoryId(109); goods.setCost(1.01); goods.setGoodsId(970); goods.setGoodsName("random_str748"); goods.setGoodsTransfeeCharge(164); goods.setHaveSpec(506); goods.setIntro("random_str344"); goods.setMarketEnable(878); goods.setMktprice(1.01); goods.setPrice(1.01); goods.setSn("random_str316"); goods.setWeight(1.01);
工具类代码:
package com.enation.app.javashop.saas; import com.enation.app.javashop.framework.util.StringUtil; import org.springframework.beans.BeanUtils; import java.beans.PropertyDescriptor; /** * 模拟数据生成器 * @author kingapex * @version 1.0 * @since 7.1.0 * 2019-08-06 */ public class MockDataGenerator { public static String create(Class clz) { StringBuffer mockStr = new StringBuffer(); PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(clz); String objName = clz.getSimpleName(); char[] chars =objName.toCharArray(); chars[0]+=32; objName = String.valueOf(chars); mockStr.append(clz.getName() + " "+ objName+" = new "+ clz.getName() +"(); "); for (PropertyDescriptor descriptor : propertyDescriptors) { if (descriptor.getWriteMethod() != null) { String name = descriptor.getWriteMethod().getName(); String value = createValue( descriptor.getPropertyType()); mockStr.append(objName + "." + name + "(" + value + "); "); } } return mockStr.toString(); } private static String createValue( Class clz) { if (clz.equals(java.lang.Integer.class)) { return StringUtil.getRandStr(3); } if (clz.equals(java.lang.Double.class)) { return "1.01"; } if (clz.equals(java.lang.String.class)) { return ""random_str"+ StringUtil.getRandStr(3)+"""; } return ""; } }