实际上,我认为这种情况下最好的解决方案是编写自己的org.junit.Runner
. 它并不像看起来那么复杂。一个简单的示例是:
跑步者:
package foo.bar.test;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.JUnit4;
import org.junit.runners.model.InitializationError;
public class MyRunner extends Runner {
private final Runner runner;
public MyRunner(final Class<?> klass) throws InitializationError {
super();
this.runner = new JUnit4(klass);
}
@Override
public Description getDescription() {
return runner.getDescription();
}
@Override
public void run(final RunNotifier notifier) {
for (Description description : runner.getDescription().getChildren()) {
notifier.fireTestStarted(description);
try {
// here it is possible to get annotation:
// description.getAnnotation(annotationType)
if (MyConfiguration.shallExecute(description.getClassName(), description.getMethodName())) {
runner.run(notifier);
}
} catch (Exception e) {
notifier.fireTestFailure(new Failure(description, e));
}
}
}
}
测试用例:
package foo.bar.test;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(MyRunner.class)
public class TestCase {
@Test
public void myTest() {
System.out.println("executed");
}
}
和配置类:
package foo.bar.test;
public class MyConfiguration {
public static boolean shallExecute(final String className, final String methodName) {
// your configuration logic
System.out.println(className + "." + methodName);
return false;
}
}
这里很酷的是您可以实现自己的注释,例如:@TestKey("testWithDataBase")
,请参阅上面示例源的注释。您的配置对象可以定义测试是否应该运行,因此您可以对测试进行分组,这在您有很多需要分组的测试时非常有用。