我正在代码中使用 java bean 来创建一个类对象。然后我调用该类 obj 的特定方法
public static void runUnitTest(String className, String methodName, List<Object> inputParams, Object expectedReturnValue){
try {
// Make the class object to be tested on
Object classObj = Class.forName(className).newInstance();
Method calledMethod = classObj.getClass().getMethod(methodName,inputParams.get(0).getClass());
Object returnVal = calledMethod.invoke(classObj,inputParams.get(0));
}catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
我这样调用它:
public static void main(String[] args) throws IOException {
List<Object> inputParams = new ArrayList<Object>();
inputParams.add(new BigDecimal(1234));
runUnitTest("NumberTest","getOutputNumber",inputParams,new BigDecimal(5678));
}
NumberTest的代码:
public class NumberTest{
public BigDecimal getOutputNumber(BigDecimal numberId) {
if(numberId.intValue() == 1234)
{
return new BigDecimal(5678);
}else
return new BigDecimal(0);
}
public BigDecimal getAdditionalOutputNumber(BigDecimal numberId, String additionalInfo) {
if(numberId.intValue() == 1234 && "Pass".equals(additionalInfo))
{
return new BigDecimal(5678);
}else
return new BigDecimal(0);
}
}
这工作得很好,因为我知道方法 getOutputNumber
只有一个参数。但是,当我必须为参数数量不同的多个方法(例如 getAdditionalOutputNumber
)调用相同的代码时,我无法使用相同的代码。我不想根据 inputParams 的大小使用多个 if else 或 case block 。
是否有调用以下内容的通用方法:
Method calledMethod = classObj.getClass().getMethod(methodName,**?? What to pass here ??**);
Object returnVal = calledMethod.invoke(classObj,**?? What to pass here ??**);
最佳答案
您只需从参数列表中构建合适的数组即可调用反射 API。
Class[] types = new Class[inputParams.size()];
int i = 0;
for(Object param:inputParams) {
types[i++] = param.getClass();
}
Method calledMethod = classObj.getClass().getMethod(methodName,types);
Object returnVal = calledMethod.invoke(classObj,inputParams.toArray());
原始类型和空值可能存在一些问题。
关于java - 通过将运行时参数传递给 java Reflect 方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27026413/