2

我在 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 上也几乎没有任何关于它的内容。

4

2 回答 2

3

我有同样的问题,但对我来说,问题是我忘记包含@EnableCaching.

于 2019-03-29T18:58:14.840 回答
2

所以我找到了我的问题的答案。问题是我忽略了我的setUp()方法重写了@AutowiredDAO 的部分代码。现在已经排序了,它就像一个魅力。

于 2015-11-05T11:49:51.310 回答