Reputation: 2432
I'm trying to test expire method in RedisTemplate. For example, I store session in redis, and than try to retrieve session and check that values are the same. For expire session I use expire() method of redisTemplate and for getting expired session I use getExpire() method. But it doesn't work. How can I test value, that stored in 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));
}
}
but test fails with AssertionError:
Expected :16 Actual :0
UPDATE: I thought, that getExpire() method doesn't work, but in fact expire() method doesn't work. It returns false. redisTemplate is a spring Bean that autowired to test class. There are many other test methods in TestCache class that work correctly.
Upvotes: 3
Views: 21896
Reputation: 18119
I set up following code to perform a test on 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);
}
}
Depending on your Redis configuration, all Redis data is gone if you restart your Redis instance.
You should also add an assertion to expireSession
(assertTrue(cache.expireSession(session, duration));
) to make sure, the expiry worked.
Upvotes: 6