在Spring上的JUnit测试期间,似乎忽略了@Cacheable标记

时间:2015-11-04 16:59:26

标签: spring junit jedis spring-data-redis

我在JUnit测试场景中获取@Cacheable注释时遇到了一些麻烦。它似乎完全忽略了缓存。它适用于我的非测试场景,但在测试中没有证据表明它甚至触及了缓存;没有新的密钥,哈希,列表,没有任何例外,也没有例外。

目前我尝试在我的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也没有任何关于它的事情。

2 个答案:

答案 0 :(得分:2)

所以我找到了问题的答案。问题是,我过度查看了我的代码的一部分,我的int_variable方法覆盖了setUp() DAO。现在它已被分类,它就像一个魅力。

答案 1 :(得分:0)

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