JUnit自定义运行器与Spring应用程序上下文

Dre*_*wCo 9 junit spring integration-testing applicationcontext

我是Spring的新手,我正在使用一套针对Web应用程序的JUnit 4.7集成测试.我有一些工作测试用例的形式:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/META-INF/spring/testContext.xml" })

public class myTest {
    @Test
    public void testCreate() {
            //execute tests
            ....
    }
}
Run Code Online (Sandbox Code Playgroud)

我的应用程序有许多我正在测试的外部依赖项,所有这些都有通过加载testContext.xml初始化的bean .其中一些外部依赖项需要自定义代码来初始化和拆除必要的资源.

我不想在每个需要它的测试类中复制此代码,而是将其封装到一个公共位置.我的想法是创建一个单独的上下文定义以及一个自定义运行器,它扩展SpringJUnit4ClassRunner并包含@ContextConfiguration注释和相关的自定义代码,如下所示:

import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//load the context applicable to this runner
@ContextConfiguration(locations = { "/META-INF/spring/testContext.xml" })

public class MyCustomRunner extends SpringJUnit4ClassRunner {

    public MyCustomRunner(Class<?> clazz) throws InitializationError {
        super(clazz);           
    }

    @Override
    protected Statement withBeforeClasses(Statement statement) {
        // custom initialization code for resources loaded by testContext.xml
                ...

        return super.withBeforeClasses(statement);
    }

    @Override
    protected Statement withAfterClasses(Statement statement) {
        // custom cleanup code for resources loaded by testContext.xml
                ....

        return super.withAfterClasses(statement);
    }

}
Run Code Online (Sandbox Code Playgroud)

然后,我可以让每个测试类指定其适用的运行程序:

@RunWith(MyCustomRunner)
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我的测试运行并执行正确的withBeforeClasseswithAfterClasses方法.但是,没有将applicationContext提供回测试类,并且我的所有测试都失败了:

java.lang.IllegalArgumentException:无法使用NULL"contextLoader"加载ApplicationContext.考虑使用@ContextConfiguration注释您的测试类.

如果我在每个测试类上指定@ContextConfiguration批注,则只能正确加载上下文 - 理想情况下,我希望此批注与其负责加载的资源的处理程序代码一起使用.这引出了我的问题 - 是否可以从自定义运行程序类加载Spring上下文信息?

axt*_*avt 13

您可以创建基础测试类 - @ContextConfiguration可以继承,也可以@Before,@After等等:

@ContextConfiguration(locations = { "/META-INF/spring/testContext.xml" }) 
public abstract class myBaseTest { 
    @Before
    public void init() {
        // custom initialization code for resources loaded by testContext.xml 
    }

    @After
    public void cleanup() {
        // custom cleanup code for resources loaded by testContext.xml
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
public class myTest extends myBaseTest { ... }
Run Code Online (Sandbox Code Playgroud)