由于IgnoredBuilder中是通过读取类注解的方法,我们不妨类似定义自己的Ignore注解:
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface MyIgnore {
String value() default "";
}
然后,新建与JUnit源码中同名的包org.junit.internal.builders,并在其中新建同名文件AllDefaultPossibilitiesBuilder,拷贝进来JUnit同名文件的源码,并修改/添加其中如下部分:
@Override
public Runner runnerForClass(Class<?> testClass) throws Throwable {
List<RunnerBuilder> builders= Arrays.asList(
ignoredBuilder(),
myBuilder(),
annotatedBuilder(),
suiteMethodBuilder(),
junit3Builder(),
junit4Builder());
for (RunnerBuilder each : builders) {
Runner runner= each.safeRunnerForClass(testClass);
if (runner != null)
return runner;
}
return null;
}
protected MyBuilder myBuilder() {
return new MyBuilder();
}
并在这个包下,定义自己的Builder:
public class MyBuilder extends RunnerBuilder {
@Override
public Runner runnerForClass(Class<?> testClass) throws Throwable {
if (testClass.getAnnotation(MyIgnore.class) != null) {
if (...) //自定义过滤条件
return new IgnoredClassRunner(testClass);
}
return new BlockJUnit4ClassRunner(testClass);
}
}
这样,只要在测试类上添加自定义注解@MyIgnore,即可根据自定义过滤条件决定该类运行与否。