Как проверить Spring's Cacheable на методе? - PullRequest
1 голос
/ 09 октября 2019

Недавно в моем проекте меня попросили использовать аннотацию Spring @Cacheable для одного из методов, который возвращает статические referenceData из базы данных. Я следил за этим блогом https://medium.com/@d.lopez.j/configuring-multiple-ttl-caches-in-spring-boot-dinamically-75f4aa6809f3, который ведет к динамическому созданию кэшей. Я пытаюсь проверить эту реализацию, следуя этому SO-ответу Как проверить поддержку декларативного кэширования Spring в репозиториях Spring Data? , и у меня возникли проблемы. Я не могу загрузить свойства из application-test.properties в мой тестовый класс.

Мой класс CachingConfig

package org.vinodh.testing;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.benmanes.caffeine.cache.Caffeine;

import lombok.Data;

@Configuration
@ConfigurationProperties(prefix = "caching")
@Data
public class CachingConfig {

    private Map<String, CacheSpec> specs;

    @Data
    public static class CacheSpec {
        private int minutesToExpire;
        private int maximumSize;

        public int getMaximumSize() {
            return maximumSize;
        }

        public void setMaximumSize(int maximumSize) {
            this.maximumSize = maximumSize;
        }

        public int getMinutesToExpire() {
            return minutesToExpire;
        }

        public void setMinutesToExpire(int minutesToExpire) {
            this.minutesToExpire = minutesToExpire;
        }

    }

    public Map<String, CacheSpec> getSpecs() {
        return specs;
    }

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        if (specs != null) {
            List<CaffeineCache> caches = specs.entrySet().stream()
                    .map(entry -> buildCache(entry.getKey(), entry.getValue())).collect(Collectors.toList());
            cacheManager.setCaches(caches);
        }
        return cacheManager;
    }

    private CaffeineCache buildCache(String name, CacheSpec specs) {
        Caffeine<Object, Object> caffeineBuilder = Caffeine.newBuilder()
                .expireAfterWrite(specs.getMinutesToExpire(), TimeUnit.MINUTES).maximumSize(specs.getMaximumSize());
        return new CaffeineCache(name, caffeineBuilder.build());
    }
}

Мой тестовый класс

package org.vinodh.testing;

import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@ConfigurationProperties(prefix = "caching")
@ActiveProfiles("test")
@Profile("test")
public class CachingConfigTest {

    @Configuration
    @EnableCaching
    static class NestedCacheConfiguration {

    static class CacheSpec {
            @SuppressWarnings("unused")
            private int minutesToExpire;
            @SuppressWarnings("unused")
            private int maximumSize;
        }

        private Map<String, CacheSpec> specs;

        public Map<String, CacheSpec> getSpecs() {
            return specs;
        }

        @Bean
        public CacheManager cacheManager() {
            SimpleCacheManager cacheManager = new SimpleCacheManager();
            System.out.println(getSpecs()); // Is null
            return cacheManager;
        }

    }

    @Test
    public void test() {
        System.out.println("Inside Test");
    }     
}

application-test.properties

caching.specs.test.minutesToExpire=10
caching.specs.test.maximumSize=10
...