【问题标题】:@Cacheable tag seems to be being ignored during JUnit testing on Spring在 Spring 上的 JUnit 测试期间,@Cacheable 标记似乎被忽略了
【发布时间】:2015-11-04 16:59:25
【问题描述】:

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

【问题讨论】:

  • 仔细检查:Utilities.isGreaterThan(estimate, executionTime) 的工作方式与您预期的一样。
  • 谢谢,我刚刚拥有,它肯定按预期工作。但是,我认为它并没有真正参与缓存过程。我在测试过程中一直使用 Redis 控制台监控关键生产,整个过程中没有出现任何内容

标签: spring junit jedis spring-data-redis


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2016-09-30
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多