单元测试如下
public class DataSourceModelTest {
@Test
public void test1() throws Exception {
//创建一个对象,用于赋值操作
DataSourceModel model = new DataSourceModel();
//加载配置文件()
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.propertise");
Properties properties = new Properties();
//使用缓存流进行加载
properties.load(new BufferedInputStream(inputStream));
//获取配置类的Class对象对应的所有方法
Method[] methods = DataSourceModel.class.getMethods();
for (Method method : methods) {
//获取方法名称
String methodName = method.getName();
//判断方法前缀是否是set开头
if (methodName.startsWith("set")) {
//获取userName中的serName
String afterName = methodName.substring(4);
//获取属性第一个字母,也就是setUserName中的U
String firstName = methodName.substring(3, 4);
String newName = firstName.toLowerCase() + afterName;
String property = properties.getProperty(newName);
if (!Objects.isNull(property)) {
//获取方法形参类型
Class>[] parameterTypes = method.getParameterTypes();
String sn = parameterTypes[0].getSimpleName();
Object arg = null;
//判断属于那种数据类型
if (sn.equals("int") || sn.equals("Integer")) {
arg = Integer.parseInt(property);
} else if (sn.equals("long") || sn.equals("Long")) {
arg = Long.parseLong(property);
} else if (sn.equals("double") || sn.equals("Double")) {
arg = Double.parseDouble(property);
} else if (sn.equals("boolean") || sn.equals("Boolean")) {
arg = Boolean.parseBoolean(property);
} else if (sn.equals("float") || sn.equals("Float")) {
arg = Float.parseFloat(property);
} else if (sn.equals("String")) {
arg = property;
} else {
continue;
}
//反射赋值
method.invoke(model, arg);
}
}
}
//输出
System.out.println("model = " + model);
}
}
单元测试与配置加载
本文介绍了一种通过单元测试加载配置文件的方法,并演示了如何利用反射机制为对象属性赋值的过程。具体步骤包括:加载配置文件、解析配置项并根据属性类型转换值,最后通过反射调用setter方法完成赋值。
282

被折叠的 条评论
为什么被折叠?



