2011-12-14 97 views
54

我们有许多JUnit测试用例(集成测试),它们在逻辑上分组到不同的测试类中。在junit测试类中重复使用spring应用上下文

我们能够为每个测试类一旦加载Spring应用程序上下文,并在http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html

但提到重新使用它的所有测试用例在JUnit测试类,我们只是不知道是否有办法为一堆JUnit测试类加载Spring应用程序上下文一次。

FWIW,我们使用Spring 3.0.5,JUnit 4.5并使用Maven构建项目。

+0

以下所有的答案都是伟大的,但我没有一个context.xml的。我注意到我的方式被遗忘了吗?任何不使用context.xml的方法? – markthegrea 2018-02-07 21:12:44

回答

67

是的,这是完全可能的。所有你需要做的是使用相同的locations属性,在测试类:由locations属性

@ContextConfiguration(locations = "classpath:test-context.xml") 

春缓存应用程序上下文所以如果同一locations出现第二次,Spring使用同样的背景下,而不是创建一个新的。

我写了一篇关于此功能的文章:Speeding up Spring integration tests。另外它在Spring文档中有详细描述:9.3.2.1 Context management and caching

这有一个有趣的含义。因为Spring不知道JUnit何时完成,所以它永远缓存所有上下文并使用JVM关闭挂钩关闭它们。这种行为(尤其是当你有很多不同的测试类时)可能导致内存使用过多,内存泄漏等。缓存上下文的另一个优势。

+0

啊!没有意识到这一点。我们一直沿用这种方法很长一段时间,并且(错误地)将测试执行的持续时间归因于每个测试类的春季上下文加载。现在仔细检查。谢谢。 – Ramesh 2011-12-14 10:18:54

+0

我宁愿说,那个春天并不了解你的测试用例的执行顺序。由于这个原因,它不能分辨上下文是否需要,或者可以处置。 – philnate 2015-04-17 11:11:58

22

要添加到Tomasz Nurkiewicz's answer,自Spring 3.2.2开始@ContextHierarchy注释可用于具有单独的,关联的多个上下文结构。当多个测试类想要共享(例如)内存数据库设置(数据源,EntityManagerFactory,tx管理器等)时,这很有用。

例如:

@ContextHierarchy({ 
    @ContextConfiguration("/test-db-setup-context.xml"), 
    @ContextConfiguration("FirstTest-context.xml") 
}) 
@RunWith(SpringJUnit4ClassRunner.class) 
public class FirstTest { 
... 
} 

@ContextHierarchy({ 
    @ContextConfiguration("/test-db-setup-context.xml"), 
    @ContextConfiguration("SecondTest-context.xml") 
}) 
@RunWith(SpringJUnit4ClassRunner.class) 
public class SecondTest { 
... 
} 

有了这个设置一个使用“测试DB-设置-context.xml的”只会创建一次,但豆类里面可以插入到各个单元测试的上下文背景

更多的手册:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#testcontext-ctx-management(搜索“context hierarchy”)

相关问题