问题描述
我有一个包含多个 @SpringBoottest JUnit 测试用例的 Spring Boot REST 项目。
该项目使用带有 Cache2K 的 Spring Cache。有一个工厂 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>
解决方法
该问题是由于 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>
如果有更好的解决方案,请留言。