Video in progress

How do you test code that depends on Redis: caches, locks, Lua scripts?

Mocking RedisTemplate doesn't verify Redis semantics. I start a real Redis of the same version as prod with Testcontainers and, in an integration test, check cache hit/miss, TTL, key format, concurrent calls, and the behavior when Redis is missing.

📖 Answer

A test written with mocks only says "we called opsForValue().set". A bug in a Lua script, a wrong serializer, or allEntries using KEYS won't show up in that kind of test.

In Spring Boot 3.1+ wiring up a container is easy:

@SpringBootTest
@Testcontainers
class PriceCacheIT {

    @Container
    @ServiceConnection(name = "redis")
    static GenericContainer<?> redis =
            new GenericContainer<>("redis:7.4-alpine").withExposedPorts(6379);

    @Autowired PriceService service;
    @Autowired StringRedisTemplate template;
    @MockitoBean PriceRepository repo;    // before Boot 3.4: @MockBean

    @BeforeEach
    void clean() {
        template.execute((RedisCallback<Void>) c -> { c.serverCommands().flushAll(); return null; });
    }

    @Test
    void secondCallComesFromCache() {
        when(repo.loadPrice(7)).thenReturn(new BigDecimal("12.50"));
        service.findById(7);
        service.findById(7);
        verify(repo, times(1)).loadPrice(7);
        assertThat(template.getExpire("prices::7")).isBetween(1L, 600L);   // was a TTL set?
    }
}

What I always check:

  • Key format and TTL: if someone later changes the prefix or the serializer, the test fails.
  • Invalidation: after an update, does the next read return the new value?
  • Serialization compatibility: put a JSON sample written by the previous version into Redis and check that the new code can read it. This protects you from SerializationExceptions during a deploy.
  • Concurrency: for a lock or Lua, call it simultaneously from an ExecutorService with 50 threads and check the invariant (for example, the ticket count never went negative).
  • Redis missing: stop the container, or add latency with Toxiproxy, and see that the API keeps working without the cache and that the timeouts are short.

If you reuse one container for the whole test suite instead of one per test class, CI time drops noticeably.