我创建了两个Runner,他们都是从BlockJUnit4ClassRunner继承的。 一种是根据条件过滤一些测试。另一种是同时运行多个方法。我想同时应用这两个运行器,以便根据条件同时运行测试。
根据Multiple RunWith Statements in jUnit,问题是我们无法将多个@RunWith注释到相同的测试。
我的问题是,由于这两个运行器都是从同一个基类BlockJUnit4ClassRunner继承而来,我可以将这两个运行器组合成一个,以便RunWith这个运行器,我可以根据条件运行测试方法并使用并发方式吗?怎么做?
以下是我创建的两名选手:
1)此运行器根据FunctionalTestFilter中定义的某些条件运行测试方法:
public class FilterRunner extends BlockJUnit4ClassRunner {
public FilterRunner(Class<?> clazz) throws InitializationError {
super(clazz);
Filter f = new FunctionalTestFilter();
try {
f.apply(this);
} catch (NoTestsRemainException ex) {
System.out.println("Warning! No method run in " + clazz.getName());
}
}
2)该跑步者使用多线程同时运行测试方法:
public static class ConcurrentJunitMethodRunner extends BlockJUnit4ClassRunner {
public ConcurrentJunitMethodRunner(final Class<?> testclass) throws InitializationError {
super(testclass);
setScheduler(new RunnerScheduler() {
ExecutorService executorService = Executors.newFixedThreadPool(5);
CompletionService<Void> completionService = new ExecutorCompletionService<Void>(executorService);
Queue<Future<Void>> tasks = new LinkedList<Future<Void>>();
@Override
public void schedule(Runnable childStatement) {
tasks.offer(completionService.submit(childStatement, null));
}
@Override
public void finished() {
try {
while (!tasks.isEmpty())
tasks.remove(completionService.take());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
while (!tasks.isEmpty())
tasks.poll().cancel(true);
executorService.shutdownNow();
}
}
});
}
}