在junit测试类中重用spring应用程序上下文 [英] Reuse spring application context across junit test classes

查看:345
本文介绍了在junit测试类中重用spring应用程序上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一堆JUnit测试用例(集成测试),它们在逻辑上分为不同的测试类.

We've a bunch of JUnit test cases (Integration tests) and they are logically grouped into different test classes.

我们能够为每个测试类加载一次Spring应用程序上下文,并将其重新用于JUnit测试类中的所有测试用例,如

We are able to load Spring application context once per test class and re-use it for all test cases in a JUnit test class as mentioned in http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html

但是,我们只是想知道是否有一种方法可以对一堆JUnit测试类仅加载一次Spring应用程序上下文.

However, we were just wondering if there is a way to load Spring application context only once for a bunch of JUnit test classes.

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

FWIW, we use Spring 3.0.5, JUnit 4.5 and use Maven to build the project.

推荐答案

是的,这完全有可能.您要做的就是在测试类中使用相同的locations属性:

Yes, this is perfectly possible. All you have to do is to use the same locations attribute in your test classes:

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

Spring通过locations属性缓存应用程序上下文,因此,如果第二次出现相同的locations,则Spring将使用相同的上下文,而不是创建新的上下文.

Spring caches application contexts by locations attribute so if the same locations appears for the second time, Spring uses the same context rather than creating a new one.

我写了一篇有关此功能的文章:加快Spring集成测试一个>. Spring文档中也对此进行了详细描述: 9.3.2.1上下文管理和缓存.

I wrote an article about this feature: Speeding up Spring integration tests. Also it is described in details in Spring documentation: 9.3.2.1 Context management and caching.

这有一个有趣的含义.由于Spring不知道JUnit何时完成,因此它将永久缓存所有上下文 并使用JVM shutdown挂钩将其关闭.此行为(尤其是当您有很多具有不同locations的测试类时)可能导致过多的内存使用,内存泄漏等.缓存上下文的另一个优点.

This has an interesting implication. Because Spring does not know when JUnit is done, it caches all context forever and closes them using JVM shutdown hook. This behavior (especially when you have a lot of test classes with different locations) might lead to excessive memory usage, memory leaks, etc. Another advantage of caching context.

这篇关于在junit测试类中重用spring应用程序上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆