SpringJUnit4ClassRunner.java 16.8 KB
Newer Older
A
Arjen Poutsma 已提交
1
/*
S
Sam Brannen 已提交
2
 * Copyright 2002-2014 the original author or authors.
A
Arjen Poutsma 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.test.context.junit4;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
23 24 25 26 27 28
import org.junit.Ignore;
import org.junit.Test;
import org.junit.internal.runners.model.ReflectiveCallable;
import org.junit.internal.runners.statements.ExpectException;
import org.junit.internal.runners.statements.Fail;
import org.junit.internal.runners.statements.FailOnTimeout;
A
Arjen Poutsma 已提交
29 30
import org.junit.runner.Description;
import org.junit.runner.notification.RunNotifier;
31 32 33 34
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
35 36
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationAttributes;
37
import org.springframework.core.annotation.AnnotationUtils;
A
Arjen Poutsma 已提交
38
import org.springframework.test.annotation.ProfileValueUtils;
39 40
import org.springframework.test.annotation.Repeat;
import org.springframework.test.annotation.Timed;
A
Arjen Poutsma 已提交
41
import org.springframework.test.context.TestContextManager;
42 43 44 45
import org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks;
import org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks;
import org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks;
import org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks;
46 47
import org.springframework.test.context.junit4.statements.SpringFailOnTimeout;
import org.springframework.test.context.junit4.statements.SpringRepeat;
48
import org.springframework.util.ReflectionUtils;
A
Arjen Poutsma 已提交
49 50

/**
51
 * {@code SpringJUnit4ClassRunner} is a custom extension of JUnit's
52
 * {@link BlockJUnit4ClassRunner} which provides functionality of the
53 54
 * <em>Spring TestContext Framework</em> to standard JUnit tests by means of the
 * {@link TestContextManager} and associated support classes and annotations.
55 56
 *
 * <p>The following list constitutes all annotations currently supported directly
57 58 59 60 61
 * or indirectly by {@code SpringJUnit4ClassRunner}. <em>(Note that additional
 * annotations may be supported by various
 * {@link org.springframework.test.context.TestExecutionListener TestExecutionListener}
 * or {@link org.springframework.test.context.TestContextBootstrapper TestContextBootstrapper}
 * implementations.)</em>
62
 *
A
Arjen Poutsma 已提交
63
 * <ul>
64 65 66 67 68 69 70
 * <li>{@link Test#expected() @Test(expected=...)}</li>
 * <li>{@link Test#timeout() @Test(timeout=...)}</li>
 * <li>{@link Timed @Timed}</li>
 * <li>{@link Repeat @Repeat}</li>
 * <li>{@link Ignore @Ignore}</li>
 * <li>{@link org.springframework.test.annotation.ProfileValueSourceConfiguration @ProfileValueSourceConfiguration}</li>
 * <li>{@link org.springframework.test.annotation.IfProfileValue @IfProfileValue}</li>
A
Arjen Poutsma 已提交
71
 * </ul>
72
 *
73 74
 * <p><strong>NOTE:</strong> As of Spring 4.1, {@code SpringJUnit4ClassRunner}
 * requires JUnit 4.9 or higher.
75
 *
A
Arjen Poutsma 已提交
76 77 78 79 80
 * @author Sam Brannen
 * @author Juergen Hoeller
 * @since 2.5
 * @see TestContextManager
 */
81
@SuppressWarnings("deprecation")
82
public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
A
Arjen Poutsma 已提交
83 84 85

	private static final Log logger = LogFactory.getLog(SpringJUnit4ClassRunner.class);

86 87 88 89 90 91 92 93 94 95 96 97
	private static final Method withRulesMethod;

	static {
		withRulesMethod = ReflectionUtils.findMethod(SpringJUnit4ClassRunner.class, "withRules", FrameworkMethod.class,
			Object.class, Statement.class);
		if (withRulesMethod == null) {
			throw new IllegalStateException(
				"Failed to find withRules() method: SpringJUnit4ClassRunner requires JUnit 4.9 or higher.");
		}
		ReflectionUtils.makeAccessible(withRulesMethod);
	}

A
Arjen Poutsma 已提交
98 99 100 101
	private final TestContextManager testContextManager;


	/**
102
	 * Constructs a new {@code SpringJUnit4ClassRunner} and initializes a
A
Arjen Poutsma 已提交
103 104
	 * {@link TestContextManager} to provide Spring testing functionality to
	 * standard JUnit tests.
105
	 * @param clazz the test class to be run
A
Arjen Poutsma 已提交
106 107 108 109 110 111 112 113 114 115
	 * @see #createTestContextManager(Class)
	 */
	public SpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
		super(clazz);
		if (logger.isDebugEnabled()) {
			logger.debug("SpringJUnit4ClassRunner constructor called with [" + clazz + "].");
		}
		this.testContextManager = createTestContextManager(clazz);
	}

116
	/**
117 118
	 * Creates a new {@link TestContextManager} for the supplied test class.
	 * <p>Can be overridden by subclasses.
119
	 * @param clazz the test class to be managed
120 121
	 */
	protected TestContextManager createTestContextManager(Class<?> clazz) {
122
		return new TestContextManager(clazz);
123 124 125 126 127 128 129 130 131 132 133
	}

	/**
	 * Get the {@link TestContextManager} associated with this runner.
	 */
	protected final TestContextManager getTestContextManager() {
		return this.testContextManager;
	}

	/**
	 * Returns a description suitable for an ignored test class if the test is
S
Sam Brannen 已提交
134
	 * disabled via {@code @IfProfileValue} at the class-level, and
135 136 137 138 139 140 141 142 143 144 145
	 * otherwise delegates to the parent implementation.
	 * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Class)
	 */
	@Override
	public Description getDescription() {
		if (!ProfileValueUtils.isTestEnabledInThisEnvironment(getTestClass().getJavaClass())) {
			return Description.createSuiteDescription(getTestClass().getJavaClass());
		}
		return super.getDescription();
	}

A
Arjen Poutsma 已提交
146
	/**
147
	 * Check whether the test is enabled in the first place. This prevents
148 149 150
	 * classes with a non-matching {@code @IfProfileValue} annotation from
	 * running altogether, even skipping the execution of
	 * {@code prepareTestInstance()} {@code TestExecutionListener} methods.
151
	 * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Class)
A
Arjen Poutsma 已提交
152 153 154
	 * @see org.springframework.test.annotation.IfProfileValue
	 * @see org.springframework.test.context.TestExecutionListener
	 */
155
	@Override
A
Arjen Poutsma 已提交
156 157 158 159 160 161 162 163
	public void run(RunNotifier notifier) {
		if (!ProfileValueUtils.isTestEnabledInThisEnvironment(getTestClass().getJavaClass())) {
			notifier.fireTestIgnored(getDescription());
			return;
		}
		super.run(notifier);
	}

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
	/**
	 * Wraps the {@link Statement} returned by the parent implementation with a
	 * {@link RunBeforeTestClassCallbacks} statement, thus preserving the
	 * default functionality but adding support for the Spring TestContext
	 * Framework.
	 * @see RunBeforeTestClassCallbacks
	 */
	@Override
	protected Statement withBeforeClasses(Statement statement) {
		Statement junitBeforeClasses = super.withBeforeClasses(statement);
		return new RunBeforeTestClassCallbacks(junitBeforeClasses, getTestContextManager());
	}

	/**
	 * Wraps the {@link Statement} returned by the parent implementation with a
	 * {@link RunAfterTestClassCallbacks} statement, thus preserving the default
	 * functionality but adding support for the Spring TestContext Framework.
	 * @see RunAfterTestClassCallbacks
	 */
	@Override
	protected Statement withAfterClasses(Statement statement) {
		Statement junitAfterClasses = super.withAfterClasses(statement);
		return new RunAfterTestClassCallbacks(junitAfterClasses, getTestContextManager());
	}

	/**
	 * Delegates to the parent implementation for creating the test instance and
	 * then allows the {@link #getTestContextManager() TestContextManager} to
	 * prepare the test instance before returning it.
	 * @see TestContextManager#prepareTestInstance(Object)
	 */
	@Override
	protected Object createTest() throws Exception {
		Object testInstance = super.createTest();
		getTestContextManager().prepareTestInstance(testInstance);
		return testInstance;
	}

A
Arjen Poutsma 已提交
202
	/**
203 204 205 206 207 208 209
	 * Performs the same logic as
	 * {@link BlockJUnit4ClassRunner#runChild(FrameworkMethod, RunNotifier)},
	 * except that tests are determined to be <em>ignored</em> by
	 * {@link #isTestMethodIgnored(FrameworkMethod)}.
	 */
	@Override
	protected void runChild(FrameworkMethod frameworkMethod, RunNotifier notifier) {
210
		Description description = describeChild(frameworkMethod);
211
		if (isTestMethodIgnored(frameworkMethod)) {
212
			notifier.fireTestIgnored(description);
213
		}
214 215
		else {
			runLeaf(methodBlock(frameworkMethod), description, notifier);
216
		}
S
Sam Brannen 已提交
217 218
	}

219 220 221 222
	/**
	 * Augments the default JUnit behavior
	 * {@link #withPotentialRepeat(FrameworkMethod, Object, Statement) with
	 * potential repeats} of the entire execution chain.
J
Juergen Hoeller 已提交
223
	 * <p>Furthermore, support for timeouts has been moved down the execution chain
224 225
	 * in order to include execution of {@link org.junit.Before @Before}
	 * and {@link org.junit.After @After} methods within the timed
226
	 * execution. Note that this differs from the default JUnit behavior of
S
Sam Brannen 已提交
227
	 * executing {@code @Before} and {@code @After} methods
228
	 * in the main thread while executing the actual test method in a separate
S
Sam Brannen 已提交
229 230
	 * thread. Thus, the end effect is that {@code @Before} and
	 * {@code @After} methods will be executed in the same thread as
231 232 233 234 235 236 237 238 239
	 * the test method. As a consequence, JUnit-specified timeouts will work
	 * fine in combination with Spring transactions. Note that JUnit-specific
	 * timeouts still differ from Spring-specific timeouts in that the former
	 * execute in a separate thread while the latter simply execute in the main
	 * thread (like regular tests).
	 * @see #possiblyExpectingExceptions(FrameworkMethod, Object, Statement)
	 * @see #withBefores(FrameworkMethod, Object, Statement)
	 * @see #withAfters(FrameworkMethod, Object, Statement)
	 * @see #withPotentialRepeat(FrameworkMethod, Object, Statement)
240
	 * @see #withPotentialTimeout(FrameworkMethod, Object, Statement)
A
Arjen Poutsma 已提交
241 242
	 */
	@Override
243 244 245 246
	protected Statement methodBlock(FrameworkMethod frameworkMethod) {
		Object testInstance;
		try {
			testInstance = new ReflectiveCallable() {
247

248 249 250 251 252 253
				@Override
				protected Object runReflectiveCall() throws Throwable {
					return createTest();
				}
			}.run();
		}
J
Juergen Hoeller 已提交
254 255
		catch (Throwable ex) {
			return new Fail(ex);
256 257 258 259 260 261
		}

		Statement statement = methodInvoker(frameworkMethod, testInstance);
		statement = possiblyExpectingExceptions(frameworkMethod, testInstance, statement);
		statement = withBefores(frameworkMethod, testInstance, statement);
		statement = withAfters(frameworkMethod, testInstance, statement);
D
David Syer 已提交
262
		statement = withRulesReflectively(frameworkMethod, testInstance, statement);
263
		statement = withPotentialRepeat(frameworkMethod, testInstance, statement);
264
		statement = withPotentialTimeout(frameworkMethod, testInstance, statement);
265 266

		return statement;
A
Arjen Poutsma 已提交
267 268
	}

269
	/**
270
	 * Invoke JUnit's private {@code withRules()} method using reflection.
271 272
	 */
	private Statement withRulesReflectively(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) {
273
		return (Statement) ReflectionUtils.invokeMethod(withRulesMethod, this, frameworkMethod, testInstance, statement);
274 275
	}

A
Arjen Poutsma 已提交
276
	/**
277 278 279
	 * Returns {@code true} if {@link Ignore @Ignore} is present for the supplied
	 * {@link FrameworkMethod test method} or if the test method is disabled via
	 * {@code @IfProfileValue}.
280
	 * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Method, Class)
A
Arjen Poutsma 已提交
281
	 */
282 283 284 285
	protected boolean isTestMethodIgnored(FrameworkMethod frameworkMethod) {
		Method method = frameworkMethod.getMethod();
		return (method.isAnnotationPresent(Ignore.class) || !ProfileValueUtils.isTestEnabledInThisEnvironment(method,
			getTestClass().getJavaClass()));
A
Arjen Poutsma 已提交
286 287 288
	}

	/**
289 290 291 292
	 * Performs the same logic as
	 * {@link BlockJUnit4ClassRunner#possiblyExpectingExceptions(FrameworkMethod, Object, Statement)}
	 * except that the <em>expected exception</em> is retrieved using
	 * {@link #getExpectedException(FrameworkMethod)}.
A
Arjen Poutsma 已提交
293
	 */
294 295 296 297
	@Override
	protected Statement possiblyExpectingExceptions(FrameworkMethod frameworkMethod, Object testInstance, Statement next) {
		Class<? extends Throwable> expectedException = getExpectedException(frameworkMethod);
		return expectedException != null ? new ExpectException(next, expectedException) : next;
A
Arjen Poutsma 已提交
298 299 300
	}

	/**
301
	 * Get the {@code exception} that the supplied {@link FrameworkMethod
302
	 * test method} is expected to throw.
303
	 * <p>Supports JUnit's {@link Test#expected() @Test(expected=...)} annotation.
304
	 * @return the expected exception, or {@code null} if none was specified
A
Arjen Poutsma 已提交
305
	 */
306 307
	protected Class<? extends Throwable> getExpectedException(FrameworkMethod frameworkMethod) {
		Test testAnnotation = frameworkMethod.getAnnotation(Test.class);
308 309
		Class<? extends Throwable> junitExpectedException = (testAnnotation != null
				&& testAnnotation.expected() != Test.None.class ? testAnnotation.expected() : null);
310

311
		return junitExpectedException;
312
	}
A
Arjen Poutsma 已提交
313

314
	/**
315 316
	 * Supports both Spring's {@link Timed @Timed} and JUnit's
	 * {@link Test#timeout() @Test(timeout=...)} annotations, but not both
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
	 * simultaneously. Returns either a {@link SpringFailOnTimeout}, a
	 * {@link FailOnTimeout}, or the unmodified, supplied {@link Statement} as
	 * appropriate.
	 * @see #getSpringTimeout(FrameworkMethod)
	 * @see #getJUnitTimeout(FrameworkMethod)
	 */
	@Override
	protected Statement withPotentialTimeout(FrameworkMethod frameworkMethod, Object testInstance, Statement next) {
		Statement statement = null;
		long springTimeout = getSpringTimeout(frameworkMethod);
		long junitTimeout = getJUnitTimeout(frameworkMethod);
		if (springTimeout > 0 && junitTimeout > 0) {
			String msg = "Test method [" + frameworkMethod.getMethod()
					+ "] has been configured with Spring's @Timed(millis=" + springTimeout
					+ ") and JUnit's @Test(timeout=" + junitTimeout
					+ ") annotations. Only one declaration of a 'timeout' is permitted per test method.";
			logger.error(msg);
			throw new IllegalStateException(msg);
A
Arjen Poutsma 已提交
335
		}
336 337
		else if (springTimeout > 0) {
			statement = new SpringFailOnTimeout(next, springTimeout);
A
Arjen Poutsma 已提交
338
		}
339 340 341 342 343
		else if (junitTimeout > 0) {
			statement = new FailOnTimeout(next, junitTimeout);
		}
		else {
			statement = next;
A
Arjen Poutsma 已提交
344 345
		}

346 347 348 349
		return statement;
	}

	/**
350 351
	 * Retrieves the configured JUnit {@code timeout} from the {@link Test @Test}
	 * annotation on the supplied {@link FrameworkMethod test method}.
352
	 * @return the timeout, or {@code 0} if none was specified.
353 354 355 356 357 358 359
	 */
	protected long getJUnitTimeout(FrameworkMethod frameworkMethod) {
		Test testAnnotation = frameworkMethod.getAnnotation(Test.class);
		return (testAnnotation != null && testAnnotation.timeout() > 0 ? testAnnotation.timeout() : 0);
	}

	/**
360
	 * Retrieves the configured Spring-specific {@code timeout} from the
361
	 * {@link Timed @Timed} annotation on the supplied
362
	 * {@link FrameworkMethod test method}.
363
	 * @return the timeout, or {@code 0} if none was specified.
364 365
	 */
	protected long getSpringTimeout(FrameworkMethod frameworkMethod) {
366 367 368 369 370 371 372 373 374
		AnnotationAttributes annAttrs = AnnotatedElementUtils.getAnnotationAttributes(frameworkMethod.getMethod(),
			Timed.class.getName());
		if (annAttrs == null) {
			return 0;
		}
		else {
			long millis = annAttrs.<Long> getNumber("millis").longValue();
			return millis > 0 ? millis : 0;
		}
375 376 377 378
	}

	/**
	 * Wraps the {@link Statement} returned by the parent implementation with a
379
	 * {@link RunBeforeTestMethodCallbacks} statement, thus preserving the
380 381
	 * default functionality but adding support for the Spring TestContext
	 * Framework.
382
	 * @see RunBeforeTestMethodCallbacks
383 384 385 386
	 */
	@Override
	protected Statement withBefores(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) {
		Statement junitBefores = super.withBefores(frameworkMethod, testInstance, statement);
387
		return new RunBeforeTestMethodCallbacks(junitBefores, testInstance, frameworkMethod.getMethod(),
388 389 390 391 392
			getTestContextManager());
	}

	/**
	 * Wraps the {@link Statement} returned by the parent implementation with a
393 394 395 396
	 * {@link RunAfterTestMethodCallbacks} statement, thus preserving the
	 * default functionality but adding support for the Spring TestContext
	 * Framework.
	 * @see RunAfterTestMethodCallbacks
397 398 399 400
	 */
	@Override
	protected Statement withAfters(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) {
		Statement junitAfters = super.withAfters(frameworkMethod, testInstance, statement);
401
		return new RunAfterTestMethodCallbacks(junitAfters, testInstance, frameworkMethod.getMethod(),
402 403 404 405
			getTestContextManager());
	}

	/**
406
	 * Supports Spring's {@link Repeat @Repeat} annotation by returning a
407
	 * {@link SpringRepeat} statement initialized with the configured repeat
408
	 * count or {@code 1} if no repeat count is configured.
409 410 411
	 * @see SpringRepeat
	 */
	protected Statement withPotentialRepeat(FrameworkMethod frameworkMethod, Object testInstance, Statement next) {
412
		Repeat repeatAnnotation = AnnotationUtils.getAnnotation(frameworkMethod.getMethod(), Repeat.class);
413 414
		int repeat = (repeatAnnotation != null ? repeatAnnotation.value() : 1);
		return new SpringRepeat(next, frameworkMethod.getMethod(), repeat);
A
Arjen Poutsma 已提交
415 416 417
	}

}