2011-04-20 46 views
8

我是相当新的春天,我正在与一套Web应用程序的JUnit 4.7集成测试。我有很多的形式工作的测试用例:JUnit自定义亚军与春季应用上下文

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装载初始化豆。其中一些外部依赖需要自定义代码来初始化和拆除必要的资源。

与其在每个需要它的测试类中复制此代码,我都想将其封装到一个公共位置。我的想法是创建一个单独的上下文定义,以及扩展基于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上下文信息?

回答

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 { ... } 
+0

咩,在测试类的继承..:/ 现在是否有,在2017年,一种正确的做法? – maricn 2017-10-06 11:22:13