9

我对 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
            ....
    }
}

我的应用程序有许多我正在测试的外部依赖项,所有这些依赖项都有通过加载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);
    }

}

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

@RunWith(MyCustomRunner)

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

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

只有当我在每个测试类上指定 @ContextConfiguration 注释时,上下文才能正确加载——理想情况下,我希望这个注释与它负责加载的资源的处理程序代码一起使用。这引出了我的问题——是否可以从自定义运行器类中加载 Spring 上下文信息?

4

1 回答 1

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 { ... }
于 2011-04-20T17:08:36.140 回答