spring - @Cacheable 标签在 Spring 上的 JUnit 测试期间似乎被忽略

标签 spring junit jedis spring-data-redis

我在 JUnit 测试场景中获取 @Cacheable 注释时遇到了一些问题。它似乎完全忽略了缓存。它在我的非测试场景中有效,但在测试中没有证据表明它甚至触及缓存;没有新的 key 、哈希值、列表,什么都没有,也没有异常(exception)。

目前,我尝试测试的方法驻留在我的 DAO 中,基本上模拟了慢速连接(一旦将缓存纳入考虑范围,连接就不会很慢):

@Component
public class DAO {
    @Cacheable(value="slowRetrieval", keyGenerator="simpleKeyGenerator", cacheManager="cacheManager")
    public boolean slowRetrievalTestIdExists(long testIdValue, long pauseLength) {
        boolean response = valueExists("id", "test", testIdValue);

        log.info("Pausing for " + pauseLength + "ms as a part of slow DB transaction simulation");
        slowMeDown(pauseLength);

        return response;
    }

    private void slowMeDown(long pause) {
        try {
            Thread.sleep(pause);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

这些是我的测试类的相关部分。它们还没有被注释,但是TL;DR它多次运行slowRetrievalTestIdExists方法,然后使用相同的参数重新运行它(因为它应该忽略带有缓存的方法的主体) 。我已经尝试将这些方法移至测试类中,结果没有变化:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes={ResultsServiceApplication.class, CacheConfig.class })
@DatabaseSetup("TestData.xml")
@Slf4j
public class DAOTest {
    @Autowired
    private DAO dao;

    @Test
    public void cacheTest() {
        log.info("Testing caching. Deliberately slow database simulations ahead! Be patient please :)");
        int maxTests = 5;
        long pause = 5000l,     //5 seconds
                estimate, executionTime = 0;
        List<Map<String, Object>> testIds = getTestData(new String[] {"id"}, "test");
        assertNotNull("No test IDs could be retrieved to test caching", testIds);

        if(testIds.size() < maxTests) maxTests = testIds.size();

        estimate = (long)maxTests * pause;

        log.info("Slow database simulation shouldn't take much more than " + (estimate / 1000) + " seconds to complete");

        for(int i = 0; i < maxTests; i++) {
            Long testId = (Long)testIds.get(i).get("id");

            log.info("Running simulated slow database transaction " + (i + 1) + " of " + maxTests);
            boolean result = dao.slowRetrievalTestIdExists(testId, pause);
        }

        log.info("Slow database simulations complete (hopefully). Now re-running tests but caching should speed it up");

        for(int i = 0; i < maxTests; i++) {
            Long testId = (Long)testIds.get(i).get("id");

            long start = System.currentTimeMillis();

            log.info("Re-running simulated slow database transaction " + (i + 1) + " of " + maxTests);
            boolean result = dao.slowRetrievalTestIdExists(testId, pause);

            long end = System.currentTimeMillis();

            executionTime += (end - start);
        }

        executionTime /= (long)maxTests;

        assertTrue("The second (supposedly cached) run took longer than the initial simulated slow run", 
                Utilities.isGreaterThan(estimate, executionTime));
    }
}

这是缓存配置类(因为我没有使用基于XML的配置):

@Configuration
@EnableCaching
public class CacheConfig { 
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();

        // Defaults
        redisConnectionFactory.setHostName("127.0.0.1");
        redisConnectionFactory.setPort(6379);
        return redisConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
        redisTemplate.setConnectionFactory(cf);

        return redisTemplate;
    }

    @Primary
    @Bean
    public CacheManager cacheManager(RedisTemplate<String, String> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);

        cacheManager.setDefaultExpiration(300l);    //300 seconds = 5 minutes

        return cacheManager;
    }

    @Bean(name="cacheManagerLongExpiry")
    public CacheManager cacheManagerLongExpiry(RedisTemplate<String, String> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);

        cacheManager.setDefaultExpiration(604800l); //604,800 seconds = 1 week

        return cacheManager;
    }

    @Bean(name="cacheManagerShortExpiry")
    public CacheManager cacheManagerShortExpiry(RedisTemplate<String, String> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);

        cacheManager.setDefaultExpiration(43200l);  //43,200 seconds = 12 hours

        return cacheManager;
    }

    @Bean(name="simpleKeyGenerator")
      public KeyGenerator keyGenerator() {
          return new KeyGenerator() {

              @Override
              public Object generate(Object o, Method method, Object... objects)                     {
                // This will generate a unique key of the class name, the method name,
                // and all method parameters appended.
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName());
                sb.append(method.getName());

                for (Object obj : objects) {
                    sb.append(obj.toString());
                }

                return sb.toString();
            }
        };
    }
}

如果您能在这方面提供任何帮助,我将不胜感激,因为我已经在这方面花费了几个小时,而 Google 上也几乎没有任何相关信息。

最佳答案

我也遇到了同样的问题,但对我来说问题是我忘记包含 @EnableCaching

关于spring - @Cacheable 标签在 Spring 上的 JUnit 测试期间似乎被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33527669/

相关文章:

java - 允许在子类中扩展静态方法

java - Jedis - 何时使用 returnBrokenResource()

java - 当没有消费者时,使用 RabbitMQ RPC 不会失败。这是预期的行为吗?

java - 如何在 Zuul 中使用 CORS 作为 API 网关 + AngularJS + 微服务

java - 如何将值或参数从jsp传递到Spring Controller ?

java - @BeforeClass注解: Junit vs TestNG

spring - 在 SpringMVC4 中使用 @RequestMapping(headers = "Accept=application/json")

java - 使用 Mockito 的 GWT MVP 测试用例,其中包含 Activity 和 Places 以及 GIN

Autocloseable 的 Java 代理(Jedis 资源)

java - 考虑重新访问上面的条目或在您的配置中定义类型为 'org.springframework.data.redis.core.RedisTemplate' 的 bean