JUnit是常用单元测试工具,如果希望跳过某个测试类,一般在类上面添加@Ignore注解。实际情况下,经常遇到某些测试类在符合某些条件时需要运行、不符合时又不需要运行的情况,频繁加减@Ignore注解的话相当繁琐。有没有办法,能根据自己的配置文件,灵活决定是否运行某些测试类呢?
首先来分析一下JUnit源码(以4.10版本为例)。在org.junit.runner包下,有个JUnitCore.class,其中的main方法就是JUnit入口函数。经过runMainAndExit->runMain->run的多次调用,发现在run之中通过Request.classes方法构建了AllDefaultPossibilitiesBuilder对象,该对象用于选择RunnerBuilder,继而选择Runner执行测试用例。源码如下:
public static Request classes(Computer computer, Class<?>... classes) {
try {
AllDefaultPossibilitiesBuilder builder= new AllDefaultPossibilitiesBuilder(true);
Runner suite= computer.getSuite(builder, classes);
return runner(suite);
} catch (InitializationError e) {
throw new RuntimeException(
"Bug in saff's brain: Suite constructor, called as above, should always complete");
}
}
在AllDefaultPossibilitiesBuilder中有个runnerForClass方法,就是该方法选择了RunnerBuilder,并通过调用RunnerBuilder的runnerForClass方法,最终决定了Runner:
@Override
public Runner runnerForClass(Class