Video in progress

Strong Middle 🧪 Testing

How do you test that a method marked @Cacheable really answers from the cache, and that the cache is cleared on time?

In a Spring context I call the cached service twice and check that the repository or client underneath was called once; then that it's called again after the operation that does a @CacheEvict. If Redis is used, I test serialization and TTL separately against a real Redis in Testcontainers.

📖 Answer

@Cacheable also works through a proxy, so you can't check it in a unit test (new CourseService(...)). You need a Spring context, but not the full application:

@SpringJUnitConfig
class CourseCacheTest {

    @Configuration
    @EnableCaching
    static class Config {
        @Bean CacheManager cacheManager() { return new ConcurrentMapCacheManager("courses"); }
        @Bean CourseRepository repo() { return mock(CourseRepository.class); }
        @Bean CourseService service(CourseRepository repo) { return new CourseService(repo); }
    }

    @Autowired CourseService service;
    @Autowired CourseRepository repo;

    @Test
    void secondCallComesFromCache_andUpdateEvicts() {
        when(repo.findById(7L)).thenReturn(Optional.of(new Course(7L, "Java")));

        service.get(7L);
        service.get(7L);
        verify(repo, times(1)).findById(7L);

        service.rename(7L, "Java 21");   // @CacheEvict("courses")
        service.get(7L);
        verify(repo, times(2)).findById(7L);
    }
}

Things to be careful about:

  • slice tests like @DataJpaTest put a no-op CacheManager in place of the cache by default through @AutoConfigureCache. Don't be surprised that the cache "isn't working" there;
  • cache state stays between tests: cacheManager.getCache("courses").clear() in @AfterEach;
  • if this.get(id) is called from inside the class, the cache is bypassed, and a separate test shows that too;
  • by default the key is built from all the parameters (SimpleKey): if you add a parameter that changes every time (say, requestId) to the method, the cache effectively stops working, and a two-call test catches this too.

With Redis there are extra bugs: a deserialization error because the DTO has no default constructor or type information, LocalDate serialization, a TTL never being set. Only a real Redis shows these; with RedisTemplate you can read the key's TTL and check it.