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

beg*_*er_ 6 ehcache spring-test

在将此标记为重复之前,请先阅读问题.我已经阅读了有关此异常的所有内容,但它并没有为我解决问题.而且我确实得到了一个略有不同的异常,例如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"/>
Run Code Online (Sandbox Code Playgroud)

的Ehcache

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

</ehcache>
Run Code Online (Sandbox Code Playgroud)

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

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:ApplicationContext.xml")
Run Code Online (Sandbox Code Playgroud)

然而导致问题的类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:ApplicationContext.xml",
    "classpath:SecurityContext.xml"
})
Run Code Online (Sandbox Code Playgroud)

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

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

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

kho*_*g07 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}"/>
Run Code Online (Sandbox Code Playgroud)

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

ehcacheManager.acceptExisting=true
ehcacheManager.shared=false
Run Code Online (Sandbox Code Playgroud)

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

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

如果您使用Spring 4和EhCache:2.5+,则适用。在Spring 3中,必须扩展EhCacheManagerFactoryBean才能添加这两个属性。

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


jeh*_*eha 5

@DirtiesContext向测试类添加注释:

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

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