JUnit4.8.2源代码分析-3.2 Computer

本系列文章,记录yqj2065阅读JUnit源代码的过程,很多时候在阅读过程中有许多不理解的地方,例如某某类是干什么的,为什么需要它,为什么不这样设计……等等。

org.junit.runner是JUnit最核心的包,其中的Computer/计算机(是这样翻译么),它是个什么意思呢?刚开始读JUnitCore的时候,我就很不明白。

package org.junit.runner;

import org.junit.runners.Suite;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerBuilder;
import org.junit.runner.Runner;

/**
 * Represents a strategy for computing runners and suites.
 * WARNING: this class is very likely to undergo serious changes in version 4.8 and
 * beyond.
 */
public class Computer {
	/**
	 * Returns a new default computer, which runs tests in serial order
	 */
	public static Computer serial() {
		return new Computer();
	}

	/**
	 * Create a suite for {@code classes}, building Runners with {@code builder}.
	 * Throws an InitializationError if Runner construction fails
	 */
	public Runner getSuite(final RunnerBuilder builder,
			Class<?>[] classes) throws InitializationError {
		return new Suite(new RunnerBuilder() {
			@Override
			public Runner runnerForClass(Class<?> testClass) throws Throwable {
				return getRunner(builder, testClass);
			}
		}, classes);
	}

	/**
	 * Create a single-class runner for {@code testClass}, using {@code builder}
	 */
	protected Runner getRunner(RunnerBuilder builder, Class<?> testClass) throws Throwable {
		return builder.runnerForClass(testClass);
	}
}
其实,如果把它叫作 RunnerFactory,我就会秒懂。

更进一步,如果不考虑它的子类org.junit.experimental.ParallelComputer,可以将Computer的两个方法定义为static。

多么标准的静态工厂。

又一个问题,Computer与org.junit.runners.model.RunnerBuilder为什么是使用关系而非继承关系?Computer仅仅作为RunnerBuilder的前台?


总之,在目前阶段,我把Computer看成一个工厂。




你可能感兴趣的:(JUnit4.8.2源代码分析-3.2 Computer)