我正在编写一套方法,使我能够为单元测试提供格式正确的输出。我的想法是我可以调用一个测试方法,传入一个参数值和预期返回结果的数组。然后,测试方法对被测试方法执行连续调用,并报告返回值是否与预期结果匹配。
// Example to test a method with 2 int parameters returning boolean
public boolean executeUnitTest(Class<?> theClass, String methodName,
int[] p1, int[] p2, boolean[] expected)
{
try {
boolean hasFail = false;
numTests = p1.length;
Class[] types = { int.class, int.class };
// Get access to the method to test
Method method = theClass.getMethod(methodName, types);
String summary = ""; // To summarize the results
// Loop on each test case
for (int testIndex = 0; testIndex < numTests; testIndex++)
{
int param1 = p1[testIndex];
int param2 = p2[testIndex];
// invoke the method to test
Object o = method.invoke(null, param1, param2);
// save the run result as the expected return type
boolean run = (boolean)o;
// build a String with the method call and params
// for reporting the results
String params = param1 + "," + param2;
summary += methodName + "(" + params + ")" + "\n";
String expectedS = expected[testIndex] + "";
String runS = run + "";
summary += "\tExpected:\t" + expectedS +"\n\tRun:\t\t" +
runS + "\n";
// Check if the test passed or failed
boolean result = expected.equals(run);
if (!result) {
summary += "\tFAIL\n";
hasFail = true;
} else {
summary += "\tPASS\n";
}
}
System.out.println(summary);
return hasFail;
}
catch(Exception e)
{
System.out.println(e);
}
return true;
}
这是执行此测试用例的示例。 被测试的方法在示例类中,并且具有方法标头:
public static boolean methodToTest(int a, int b)
public void testExample()
{
int[] p1 = { 2,1,1,2,5 }; // parameter 1
int[] p2 = { 2,1,2,1,6 }; // parameter 2
boolean[] expected = { true, true, false, false, false };
executeUnitTest(Examples.class, "methodToTest",
p1, p2, expected));
}
上面的方法非常完美,可以满足我的要求。
问题:我必须为参数和返回类型的每种可能组合编写一个executeUnitTest版本。
我正在尝试提出一种通用化executeUnitTest代码的方法,以便它可以与任何参数集和返回类型一起使用。有什么想法吗?
这是我到目前为止所处的位置以及被绊倒的地方。
public boolean executeUnitTest(Class<?> theClass, String methodName,
Class[] paramTypes, // pass list of param types
Object[][] params, // param packaged as 2D array
Class returnType, Object[] returnVals)
{
try {
Method method = theClass.getMethod(methodName, paramTypes);
// Loop on each test case
for (int testIndex = 0;
testIndex < params[0].length;
testIndex++)
{
// HOW TO INVOKE THE METHOD WITHOUT INDIVIDUAL PARAMS???
Object o = method.invoke(null, ????);
// ETC...
}
}
注意:我无法在该项目中使用junit功能