Skip to content

Instantly share code, notes, and snippets.

Created March 20, 2013 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rponte/5201829 to your computer and use it in GitHub Desktop.
Save rponte/5201829 to your computer and use it in GitHub Desktop.
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 {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment