Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
JUnit Test Rule example that starts and stops a Spring Context between each test method. This class was written by @alexec.
package com.alexecollins.testsupport.rules;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import java.lang.reflect.Field;
* Creates a context for tests that use Spring.
* <p/>
* Public fields in the test annotated {@link Autowired} are auto-wired from the context.
* @author alexec (
public class SpringContextRule implements TestRule {
/** A list of class-path contexts. */
private final String[] locations;
/** The target test. */
private final Object target;
public SpringContextRule(String[] locations, Object target) {
this.locations = locations; = target;
public Statement apply(final Statement base, Description description) {
return new Statement() {
public void evaluate() throws Throwable {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
AutowireCapableBeanFactory beanFactory = context
/* As this is an example of @Rule, this is a rough hand-rolled injector,
* not suitable for production.
* More capable ones, that support @Inject, @Qualifier etc. probably exist. */
for (Field f : target.getClass().getFields()) {
if (f.isAnnotationPresent(Autowired.class)) {
f.set(target, context.getBean(f.getName(), f.getType()));
try {
} finally {

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.