spring-bootehcachespring-testterracotta

@SpringBootTest tries to connect to actual Ehcache instance


Our Spring Boot application shall be able to fetch data from a remote Ehcache instance. For this, the following configuration has been added.

@Configuration
@EnableCaching
public class EhcacheManager {

    private static final String TERRACOTTA_LINK = "terracotta://";

    private final EhcacheConfiguration ehcacheConfiguration;

    public EhcacheManager(EhcacheConfiguration ehcacheConfiguration) {
        this.ehcacheConfiguration = ehcacheConfiguration;
    }

    @Bean
    PersistentCacheManager persistentCacheManager() {
        return ehCacheManager();
    }

    private PersistentCacheManager ehCacheManager() {
        final String ehcacheURI = TERRACOTTA_LINK + ehcacheConfiguration.getHost() + ":" + ehcacheConfiguration.getPort() + "/" + ehcacheConfiguration.getResource();

        PersistentCacheManager cacheManager = newCacheManagerBuilder()
                .with(cluster(create(ehcacheURI)).autoCreate())
                .build(true);

        CacheConfiguration<String, String> myCache = newCacheConfigurationBuilder(String.class, String.class,
                newResourcePoolsBuilder().with(clusteredDedicated("offheap-1", 50, MB)))
                .withService(withConsistency(EVENTUAL))
                .withDefaultResilienceStrategy()
                .build();
        cacheManager.createCache("someCacheKey", myCache);
        return cacheManager;
    }
}

However, there is a problem with all our integration tests which are annotated with @SpringBootTest. These tests will spin up the application context and with this are trying to connect to a remote Ehcache instance; which is nto available.

Is there any way to disable this instantiation? Or do I need to spin up something like an embedded Ehcache server for the integration tests to start the application context?


Solution

  • If your application can run with EhCache disabled, you can simply edit the @SpringBootTest annotation to disable EhCache, eg.: @SpringBootTest(properties = {"property.to.disable.ehcache=true"}), guaranteeing EhCache will be disabled only during the test phase.

    If your application requires EhCache to be enabled, your best bet is to add a src/test/resources/application.properties file, containing properties (eg. host, port etc.) pointing to a local, possibly test-embedded, instance of EhCache.