在最基本的情况下,只有一个测试结果,DelegateRunner 可能是这样的:
public class DelegateRunner extends Runner {
private Description testDescription = Description
.createTestDescription("groupName", "testName");
public DelegateRunner(Class<?> testClass) {
}
@Override
public Description getDescription() {
return testDescription;
}
@Override
public void run(RunNotifier notifier) {
notifier.fireTestStarted(testDescription);
... trigger remote test ...
if (passed)
notifier.fireTestFinished(testDescription);
else
notifier.fireTestFailure(new Failure(testDescription,
new AssertionError("Details of the failure")));
}
}
那么getDescription() 和run() 都需要被包装:
public class FrontRunner extends Runner {
private Runner runner;
public FrontRunner(Class<?> testClass) throws InitializationError {
if (someCondition)
runner = new DelegateRunner(testClass);
else
runner = new JUnit4(testClass);
}
@Override
public Description getDescription() {
return runner.getDescription();
}
@Override
public void run(RunNotifier notifier) {
runner.run(notifier);
}
}
(假设可以预先知道someCondition,并且它只是通常需要的默认JUnit4 runner)。
这如预期的那样通过 Maven 构建:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running ...FrontRunnerTest
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.078 sec <<< FAILURE!
testName(groupName) Time elapsed: 0.015 sec <<< FAILURE!
java.lang.AssertionError: Details of the failure
at so.ownrunner.DelegateRunner.run(DelegateRunner.java:28)
at so.ownrunner.FrontRunner.run(FrontRunner.java:27)
at ...
Results :
Failed tests: testName(groupName): Details of the failure
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
如果需要更结构化的响应,Description.addChild() 可用于嵌套套件和/或测试,例如:
public class NestedDelegateRunner extends Runner {
private Description suiteDescription = Description
.createSuiteDescription("groupName");
private Description test1Description = Description
.createTestDescription("groupName", "test1");
private Description test2Description = Description
.createTestDescription("groupName", "test2");
public NestedDelegateRunner(Class<?> testClass) {
suiteDescription.addChild(test1Description);
suiteDescription.addChild(test2Description);
}
@Override
public Description getDescription() {
return suiteDescription;
}
@Override
public void run(RunNotifier notifier) {
notifier.fireTestStarted(test1Description);
notifier.fireTestStarted(test2Description);
notifier.fireTestFinished(test1Description);
notifier.fireTestFailure(new Failure(test2Description,
new AssertionError("Details of the failure")));
}
}
事实上addChild() 并不重要,但没有它,结构可能不太明显 - 例如像 Eclipse 这样的东西只会显示Unrooted tests。