您的位置:首页 > 其它

junit源码学习--运行测试的过程

2010-05-24 17:45 489 查看
找到textui/TestRunner.java,看到了阔别很久的main方法,OK,开始运行测试。

TestRunner.java

/**
* 运行自身的start方法,并将返回结果提交给容器

*/

public static void main(String args[]) {
TestRunner aTestRunner= new TestRunner();
try {
TestResult r= aTestRunner.start(args);
if (!r.wasSuccessful())
System.exit(FAILURE_EXIT);
System.exit(SUCCESS_EXIT);
} catch(Exception e) {
System.err.println(e.getMessage());
System.exit(EXCEPTION_EXIT);
}
}

/**
* Starts a test run. Analyzes the command line arguments and runs the given
* test suite.解析传入参数,并根据参数运行对应的方法
*/

public TestResult start(String args[]) throws Exception {
String testCase= "";
String method= "";
boolean wait= false;

for (int i= 0; i < args.length; i++) {

//以下这一段if else看着真扎眼,不过考虑到这一段基本不扩展,而且也不会复用,也就这样吧

//根据传入参数获取运行的testCase类名和method方法名
if (args[i].equals("-wait"))
wait= true;
else if (args[i].equals("-c"))
testCase= extractClassName(args[++i]);
else if (args[i].equals("-m")) {
String arg= args[++i];
int lastIndex= arg.lastIndexOf('.');
testCase= arg.substring(0, lastIndex);
method= arg.substring(lastIndex + 1);
} else if (args[i].equals("-v"))
System.err.println("JUnit " + Version.id() + " by Kent Beck and Erich Gamma");
else
testCase= args[i];
}

if (testCase.equals(""))
throw new Exception("Usage: TestRunner [-wait] testCaseName, where name is the name of the TestCase class");

try {
if (!method.equals("")) //方法名不为空
return runSingleMethod(testCase, method, wait);
Test suite= getTest(testCase);//方法名为空
return doRun(suite, wait);
} catch (Exception e) {
throw new Exception("Could not create and run test suite: " + e);
}
}

当方法名不为空时,进入runSingleMethod方法

protected TestResult runSingleMethod(String testCase, String method, boolean wait) throws Exception {
Class<? extends TestCase> testClass= loadSuiteClass(testCase);//根据类名获取具体类,如果不是TestCase的子类,则抛

//出ClassNotFoundException
Test test= TestSuite.createTest(testClass, method);//在TestSuite中通过反射获取到对应的类实例
return doRun(test, wait);//运行本地doRun()方法,将获取的类实例作为参数传入
}

进入doRun(Test suite,boolean wait)方法,实际运行测试方法

public TestResult doRun(Test suite, boolean wait) {
TestResult result= createTestResult();//获取新的TestResult实例
result.addListener(fPrinter);
long startTime= System.currentTimeMillis();
suite.run(result);//实际运行测试方法
long endTime= System.currentTimeMillis();
long runTime= endTime-startTime;
fPrinter.print(result, runTime);

pause(wait);
return result;
}

OK,运行至此,实际的测试方法已经运行完成了。其中,最关键的点就是判断类是否为TestCase的子类,然后通过反射获取类的实例,保证了运行方法绝对是TestCase的run。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: