我正在尝试测试 RedisTemplate 中的过期方法。例如,我将会话存储在 redis 中,然后尝试检索会话并检查值是否相同。对于过期会话,我使用 redisTemplate 的 expire() 方法,对于获取过期会话,我使用 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:
预计:16 实际:0
UPDATE:我想, getExpire() 方法不起作用,但实际上 expire() 方法不起作用。它返回错误。 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));
)以确保到期有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)