在使用cache2k的maven内置spring cache项目中,使用@springboottest的多个测试失败

nnsrf1az  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(413)

我有一个spring boot rest项目,其中包含多个@springboottest junit测试用例。
该项目使用带cache2k的spring缓存。有一个工厂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>
ddhy6vgd

ddhy6vgd1#

这个问题是由于maven surefire测试并行运行造成的。这个答案提供了解决问题的办法。
这个项目是使用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>

如果有更好的解决方案,请贴出来。

相关问题