本文介绍了春季测试上下文最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过集成测试涵盖一个庞大的Spring Boot应用程序.应用程序中有很多Spring bean.加载Spring上下文需要一段时间.

I'm trying to cover a huge Spring Boot application with integration tests. There are lots of Spring beans within the app. It takes a while to load the Spring context.

所以我想知道-

  • Spring是否足够聪明,可以在位于不同类中的多个集成测试之间共享相同的上下文?我的意思是避免为每个测试类初始化繁重的上下文.
  • 当测试1,2,4使用TestContextOne而测试3,5使用TestContextTwo时会发生什么? Spring是否以1,2,4,3,5顺序启动它们?还是Spring会在内存中保留两个上下文?
  • Is Spring clever enough to share the same context between multiple integration tests located in different classes? I mean to avoid initializing the heavy-weight context for each test class.
  • What happens when tests 1,2,4 use TestContextOne and tests 3,5 use TestContextTwo? Does Spring launch them in 1,2,4,3,5 order? Or does Spring keep two contexts in memory?

PS 换句话说,是对所有集成测试使用单个完整" Spring Context的惯例,而不是为每个集成测试编写单独的测试?

推荐答案

spring框架提供的用于测试应用程序的主要功能之一是上下文缓存机制,它可以避免您所说的负载开销.春天的文档说:

One of the main features provided by spring framework for testing an application is the context caching mechanism to avoid exactly what you mention about the load overhead. The spring documentation says that:

记住这一点,您必须了解缓存机制如何工作,以确定构建测试的最佳策略.这里的问题是:When spring caches the context, it stores this context in memory using what key?.根据文档,密钥基于容器的某些参数:

With this affirmation in mind you have to understand how the cache mechanism works to determine the best strategy on build your tests. The question here is: When spring caches the context, it stores this context in memory using what key?. According to documentation, the key is based on some parameters of the container:

locations(来自@ContextConfiguration)
classes(来自@ContextConfiguration)
contextInitializerClasses(来自@ContextConfiguration)
contextCustomizers(来自ContextCustomizerFactory)
contextLoader(来自@ContextConfiguration)
parent(来自@ContextHierarchy)
activeProfiles(来自@ActiveProfiles)
propertySourceLocations(来自@TestPropertySource)
propertySourceProperties(来自@TestPropertySource)
resourceBasePath(来自@WebAppConfiguration)

locations (from @ContextConfiguration)
classes (from @ContextConfiguration)
contextInitializerClasses (from @ContextConfiguration)
contextCustomizers (from ContextCustomizerFactory)
contextLoader (from @ContextConfiguration)
parent (from @ContextHierarchy)
activeProfiles (from @ActiveProfiles)
propertySourceLocations (from @TestPropertySource)
propertySourceProperties (from @TestPropertySource)
resourceBasePath (from @WebAppConfiguration)

基于此信息,我可能建议您最佳实践是组织测试,使它们使用相同的上下文参数集(即,相同的缓存键)来受益于缓存机制并避免使用其他上下文来被加载. Spring文档也给出了一个示例:

Based on this information I may suggest you that the best practice is organize your tests in a way that they use the same set of context parameters (that is, the same cache key) to benefit from cache mechanism and avoid another context to be loaded. Spring documentation also gives an example:

这篇关于春季测试上下文最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:41