我有一个包含多个@SpringBootTest JUnit测试用例的Spring Boot REST项目。
该项目使用Spring Cache和Cache2K。有一个工厂bean,它创建一个带有缓存的CacheManager。
@Bean
public CacheManager cache2kCacheManager() {
SpringCache2kCacheManager cache2kCacheManager = new SpringCache2kCacheManager()
.defaultSetup(b -> b.entryCapacity(3).expireAfterWrite(3, TimeUnit.SECONDS).disableMonitoring(false));
Function<Cache2kBuilder<?, ?>, Cache2kBuilder<?, ?>> campaignCacheBuilder;
campaignCacheBuilder = x -> x.name("campaigns-cache")
.entryCapacity(5));
cache2kCacheManager.addCaches(campaignCacheBuilder);
return cache2kCacheManager;
}当在IDE中运行时,所有的测试用例都能成功运行。应用程序在IDE中启动时也会运行。然而,当我在项目上运行mvn clean install时,测试用例由于缓存对象创建错误而失败。
[ERROR] testCacheReadAndWrite Time elapsed: 0 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cache2kCacheManager' defined in class path resource [com/demos/cachedemo/cache/configuration/Cache2KConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cache.CacheManager]: Factory method 'cache2kCacheManager' threw exception; nested exception is java.lang.IllegalStateException: Cache already created: 'campaigns-cache'
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cache.CacheManager]: Factory method 'cache2kCacheManager' threw exception; nested exception is java.lang.IllegalStateException: Cache already created: 'campaigns-cache'
Caused by: java.lang.IllegalStateException: Cache already created: 'campaigns-cache'我尝试删除出现错误的测试用例,但其他测试用例开始失败,并出现相同的异常。该上下文似乎正在被重用/共享。我已经将@DirtiesContext添加到测试用例中,但这并不能解决问题。
有人能帮我解决这个问题吗?
更新1:该项目是使用start.spring.io创建的,并且在pom.xml中具有默认的构建插件。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>发布于 2021-04-03 10:43:55
该问题是由于Maven的Surefire测试并行运行造成的。This answer提供了一个解决方案,解决了这个问题。
这个项目是使用start.spring.io创建的,并且有默认的构建插件(我已经用之前的构建配置编辑了问题)。
我添加了以下Surefire配置来限制并行运行。
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<reuseForks>false</reuseForks>
<forkCount>1</forkCount>
</configuration>
</plugin>
</plugins>
</build>如果有更好的解决方案,请张贴。
https://stackoverflow.com/questions/66927208
复制相似问题