spring test:同一个VM中已存在另一个同名为“myCacheManager”的CacheManager

问题描述 投票:6回答:3

在将此标记为重复之前,请先阅读问题。我已经阅读了有关此异常的所有内容,但它并没有为我解决问题。我确实得到了一个略有不同的例外,例如Another CacheManager with same name 'myCacheManager' already exists而不是Another unnamed CacheManager already exists

Spring配置:

<cache:annotation-driven cache-manager="cacheManager"/>

<bean id="cacheManager"
      class="org.springframework.cache.ehcache.EhCacheCacheManager"
      p:cacheManager-ref="ehcache"/>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
      p:configLocation="ehcache.xml"
      p:cacheManagerName="myCacheManager"
      p:shared="true"/>

的Ehcache

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
        updateCheck="false" name="myCacheManager">

</ehcache>

问题是我有1个(将来更多)测试安全性的测试类。这些类还加载了SecurityContext.xml

所以大多数测试类都有这样的注释:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:ApplicationContext.xml")

然而导致问题的类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:ApplicationContext.xml",
    "classpath:SecurityContext.xml"
})

似乎由于位置不同,上下文再次加载,但ehcacheManager仍然在以前的测试中处于活动状态。

注意:这只在运行多个测试时发生(例如,像clean + build)。分别运行此测试类非常正常。

问题是什么?我该如何解决?

ehcache spring-test
3个回答
5
投票

@DirtiesContext注释添加到测试类:

@ContextConfiguration(...)
@RunWith(...)
@DirtiesContext // <== add e.g. on class level
public class MyTest {
    // ...
}

此注释指示与测试关联的应用程序上下文是脏的,应该关闭。随后的测试将提供一个新的背景。适用于类级和方法级。


6
投票

我不知道问题/问题是否仍然相关,但这是一个简单/适当的解决方案(不需要在所有测试中添加@DirtiesContext)。避免@DirtiesContext允许您只为所有集成测试提供一个共享上下文(例如,通过maven运行,或者在IDE中运行所有测试)。这避免了由同一时间开始的多个上下文引起的多个问题。

<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
  p:configLocation="ehcache.xml"
  p:cacheManagerName="myCacheManager"
  p:shared="${ehcacheManager.shared:true}"
  p:acceptExisting:"${ehcacheManager.acceptExisting:false}"/>

在测试(集成测试)中,设置这些属性

ehcacheManager.acceptExisting=true
ehcacheManager.shared=false

它允许Spring为每个测试创建一个EhcacheManager(ehcache),但是如果存在一个具有相同名称的EhcacheManager,Spring将只重用它。 Spring也不会在使用@DirtiesContext注释的上下文中销毁/关闭它。

这个想法很简单,在使用@DirtiesContext时可以防止EhcacheManager的破坏。

如果你使用Spring 4和EhCache:2.5+,这是适用的。使用Spring 3,您必须扩展EhCacheManagerFactoryBean以添加这两个属性。

不要忘记在每次测试前清除缓存:)


3
投票

即使您的代码具有带@Cacheable注释的方法,也可以在禁用缓存的情况下运行测试。

这样,您就不必通过使用@DirtiesContext标记所有测试来减慢测试速度。

将缓存相关的Spring配置放在他们自己的Spring配置文件中,例如。 applicationContext-cache.xml文件。

仅在运行应用程序时才包含applicationContext-cache.xml文件,但不在测试中。

如果您特别想测试缓存,则需要@DirtiesContext注释。

© www.soinside.com 2019 - 2024. All rights reserved.