我正在尝试测试RedisTemplate中的expire方法。例如,我将 session 存储在redis中,然后尝试检索 session 并检查值是否相同。对于过期 session ,我使用redisTemplate的expire()方法,对于过期 session ,我使用getExpire()方法。但这是行不通的。我如何测试存储在Redis中的值?

//without import and fields
public class Cache() {

    private StringRedisTemplate redisTemplate;

    public boolean expireSession(String session, int duration) {
      return redisTemplate.expire(session, duration, TimeUnit.MINUTES);
    }
}

//Test class without imports and fields
public class TestCache() {

    private Cache cache = new Cache();
    @Test
    public void testExpireSession() {
        Integer duration = 16;
        String session = "SESSION_123";
        cache.expireSession(session, duration);
        assertEquals(redisTemplate.getExpire(session, TimeUnit.MINUTES), Long.valueOf(duration));
    }
}

但是测试失败并显示AssertionError:



更新:
我以为getExpire()方法不起作用,但实际上expire()方法不起作用。返回false。 redisTemplate是一个自动连接到测试类的spring Bean。 TestCache类中还有许多其他测试方法可以正常工作。

最佳答案

我设置了以下代码以对getExpire()(jedis 2.5.2,spring-data-redis 1.4.2.RELEASE)进行测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
public class DemoApplicationTests {

    @Autowired
    private RedisTemplate<String, String> template;

    @Test
    public void contextLoads() {

        template.getConnectionFactory().getConnection().flushAll();

        assertFalse(template.hasKey("key"));
        assertFalse(template.expire("key", 10, TimeUnit.MINUTES));
        assertEquals(0, template.getExpire("key", TimeUnit.MINUTES).longValue());

        template.opsForHash().put("key", "hashkey", "hashvalue");

        assertTrue(template.hasKey("key"));
        assertTrue(template.expire("key", 10, TimeUnit.MINUTES));
        assertTrue(template.getExpire("key", TimeUnit.MINUTES) > 8);
    }

}

根据您的Redis配置,如果重新启动Redis实例,则所有Redis数据都会消失。

您还应该在expireSession(assertTrue(cache.expireSession(session, duration));)中添加一个断言,以确保到期有效。

10-07 19:28
查看更多