在每个测试类中

时间:2015-04-25 23:51:51

标签: spring-boot spring-test spring-cache

在我的Spring-Boot Web应用程序项目中,我使用Spring Cache来实现缓存。可以通过application.yml中定义的配置键启用/禁用缓存。我已经有了现有的测试用例,假设没有缓存,就会编写测试。因此,默认情况下,我的integration-test配置文件缓存已禁用,我初始化NoOpCacheManager并且我的所有测试都有效。

@Profile(value = { "default", "production", "integration-test" })
@Configuration
@EnableCaching(mode = AdviceMode.ASPECTJ)
public class CacheBeanConfig extends CachingConfigurerSupport {

    @Autowired
    private CacheConfig cacheConfig;

    @Bean
    @Override
    public CacheManager cacheManager() {
        if (cacheConfig.isEnabled()) {
            System.out.println("****************Couchbase CacheBeanTestsConfig cache init.**********************");
            Map<String, DeclaraCouchbaseTemplate> cacheCouchTemplateMap = Maps.newHashMap();
            Map<String, Integer> cacheTtlMap = Maps.newHashMap();

            for (CacheConfig.CacheConfigParam cacheParam : cacheConfig.getCaches()) {
                try {
                    cacheCouchTemplateMap.put(cacheParam.getName(),
                        couchbaseManager.getCouchbaseTemplate(cacheParam.getName()));
                    cacheTtlMap.put(cacheParam.getName(), cacheParam.getTtl());
                } catch (IOException | URISyntaxException e) {
                    throw new FaultException("Unable to get couchbase template.");
                }
            }

            return new CouchbaseCacheManager(cacheCouchTemplateMap, cacheTtlMap, metricRegistry);
        } else {
            System.out.println("****************NoOp CacheBeanTestsConfig cache init.**********************");
            NoOpCacheManager noopCacheManager = new NoOpCacheManager();
            return noopCacheManager;
        }
    }

}

我还想编写用于验证缓存功能的测试。我创建了一个CachedControllerTest类,其中编写了所有缓存特定的测试。

我跑的时候出现问题

mvn test -Dtest=CachedControllersTest -Dspring.profiles.active=integration-test

CachedControllerTest类中的所有测试都失败了,因为缓存管理器初始化为NoOpCacheManager,即使我在bean函数中启用了缓存。

我尝试为CachedControllerTest创建一个单独的配置文件但它仍然失败,因为一旦初始化了cacheManager bean,它就不会被重置。

mvn test -Dtest=CachedControllersTest -Dspring.profiles.active=integration-test,integration-cache-test

这是我的CachedControllerTest类

@ActiveProfiles("integration-cache-test")
@DirtiesContext
public class CachedControllersTest extends AbstractRestControllerTest {

    @Configuration
    @EnableCaching(mode = AdviceMode.ASPECTJ)
    @Profile("integration-cache-test")
    public static class CachedControllerTestsBeanConfig {

        @Autowired
        private CouchbaseManager couchbaseManager;

        @Autowired
        private CacheConfig cacheConfig;

        @Autowired
        private MetricRegistry metricRegistry;

        @Autowired
        GlobalApplicationConfig globalAppConfig;

        @Bean
        public CacheManager cacheManager() {
            System.out.println("**************** CachedControllerTestsBeanConfig EnabledCaching**********************");
            cacheConfig.setEnabled(true);
            if (cacheConfig.isEnabled()) {
                System.out.println("****************Couchbase CachedControllerTestsBeanConfig cache init.**********************");
                Map<String, DeclaraCouchbaseTemplate> cacheCouchTemplateMap = Maps.newHashMap();
                Map<String, Integer> cacheTtlMap = Maps.newHashMap();

                for (CacheConfig.CacheConfigParam cacheParam : cacheConfig.getCaches()) {
                    try {
                        cacheCouchTemplateMap.put(cacheParam.getName(),
                            couchbaseManager.getCouchbaseTemplate(cacheParam.getName()));
                        cacheTtlMap.put(cacheParam.getName(), cacheParam.getTtl());
                    } catch (IOException | URISyntaxException e) {
                        throw new FaultException("Unable to get couchbase template.");
                    }
                }

                return new CouchbaseCacheManager(cacheCouchTemplateMap, cacheTtlMap, metricRegistry);
            } else {
                System.out.println("****************NoOp CachedControllerTestsBeanConfig cache init.**********************");
                NoOpCacheManager noopCacheManager = new NoOpCacheManager();
                return noopCacheManager;
            }
        }

        @Bean(name = "mtlKeyGenerator")
        public KeyGenerator keyGenerator() {
            System.out.println("****************CachedControllerTestsBeanConfig mtlKeyGenerator.**********************");
            return new MultiTenantKeyGenerator(globalAppConfig.getTenantId());
        }

        @Bean(name = CacheManagementConfigUtils.CACHE_ASPECT_BEAN_NAME)
        @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
        public AnnotationGroupCacheAspect cacheAspect() {
            AnnotationGroupCacheAspect cacheAspect = AnnotationGroupCacheAspect.aspectOf();
            CacheManager cacheManager = (CacheManager) StaticContextHolder.getApplicationContext().getBean("cacheManager");
            cacheAspect.setCacheManager(cacheManager);

            KeyGenerator keyGenerator = (KeyGenerator) StaticContextHolder.getApplicationContext().getBean("mtlKeyGenerator");
            cacheAspect.setKeyGenerator(keyGenerator);
            return cacheAspect;
        }
    }

    @Component
    public static class StaticContextHolder implements ApplicationContextAware {

        private static ApplicationContext appContext;

        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            appContext = applicationContext;
        }

        public static ApplicationContext getApplicationContext() {
            return appContext;
        }
    }
}

application.yml

spring:
    profiles: integration-test

cache:
    enabled: false
---
spring:
    profiles: integration-cache-test

cache:
    enabled: false 

我的要求是为每个Test Class重新初始化cacheManage,而CacheConfig是我想在运行时修改的bean,以便初始化适当的CacheManager

如果我运行CachedControllerTest类测试,它们都会被隔离,因为在没有其他测试类运行之前,它会将cacheManager初始化为NoOpCacheManager。

提前感谢任何帮助/建议,以使这种情况有效。

修改1

根据Sam的建议,添加了@ActiveProfiles

修改2

AbstractRestControllerTest类定义

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class AbstractRestControllerTest {
}

1 个答案:

答案 0 :(得分:1)

@Profile对测试类有效果。

要为集成测试设置活动Bean定义配置文件,您需要使用@ActiveProfiles模块中的spring-test

有关详细信息,请参阅Spring参考手册的Context configuration with environment profiles部分。

此外,CachedControllerTestsBeanConfig必须使用@Configuration 而不是 @Component进行注释。

此致

Sam( Spring TestContext Framework的作者