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

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

问题描述

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

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

我们能够为每个测试类加载一次 Spring 应用程序上下文,并将其重用于 JUnit 测试类中的所有测试用例,如 http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html

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 关闭钩子关闭它们.这种行为(尤其是当您有许多具有不同位置的测试类时)可能会导致内存使用过多、内存泄漏等.缓存上下文的另一个优点.

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天全站免登陆