Sub topic 14
Testing cached code
Cache bugs rarely crash anything. They return stale data, call a database more often than expected, or silently never cache at all. Tests catch these problems early. This chapter shows how to prove that a cache is populated, hit, refreshed and emptied. It assumes you know JUnit 5, AssertJ and Mockito basics, and that you have read the earlier chapters on @Cacheable, @CachePut, @CacheEvict and the proxy limits.
What a cache test should prove
A cache changes behavior in two ways you can observe: a second call skips the real work, and the Cache holds an entry under a known key. A good test checks one or both.
| Question | How to check it |
|---|---|
| Was the real method skipped on a hit? | Mock the collaborator and use `verify(..., times(1))` |
| Is the entry stored under the right key? | `cacheManager.getCache(name).get(key)` |
| Did `unless` or `condition` block caching? | Call twice and verify the collaborator ran twice |
| Did an eviction or update take effect? | Call, evict or update, call again, and count |
| Is caching active at all? | `AopUtils.isAopProxy(service)` is true |
Counting calls on a mocked collaborator is more reliable than timing a slow method. Timing tests are flaky and say nothing about why a call was fast.
A service that is easy to test
The ProductService from earlier chapters keeps its data in a map, so there is nothing to mock. For testing, put the slow part behind a collaborator. Here ProductRepository stands in for a database, and Product is the record from earlier chapters.
public interface ProductRepository {
java.util.Optional<Product> findById(Long id);
}
@Service
public class CatalogService {
private final ProductRepository repository;
public CatalogService(ProductRepository repository) {
this.repository = repository;
}
@Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
public Product find(Long id) {
return repository.findById(id).orElse(null);
}
@CacheEvict(cacheNames = "products", key = "#id")
public void evict(Long id) {
}
}Testing with the full application context
@SpringBootTest loads your real configuration, including @EnableCaching and the configured provider. The test below replaces the repository with a Mockito mock and clears every cache before each test.
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
@SpringBootTest
class CatalogServiceCacheTest {
@Autowired CatalogService service;
@Autowired CacheManager cacheManager;
@MockitoBean ProductRepository repository;
private final Product keyboard =
new Product(1L, "Keyboard", new BigDecimal("49.90"));
@BeforeEach
void clearCaches() {
cacheManager.getCacheNames()
.forEach(name -> cacheManager.getCache(name).clear());
}
@Test
void secondCallIsServedFromCache() {
when(repository.findById(1L)).thenReturn(Optional.of(keyboard));
Product first = service.find(1L);
Product second = service.find(1L);
assertThat(second).isEqualTo(first);
verify(repository, times(1)).findById(1L);
assertThat(cacheManager.getCache("products").get(1L)).isNotNull();
}
@Test
void nullResultsAreNotCached() {
when(repository.findById(2L)).thenReturn(Optional.empty());
service.find(2L);
service.find(2L);
verify(repository, times(2)).findById(2L);
assertThat(cacheManager.getCache("products").get(2L)).isNull();
}
@Test
void evictForcesANewLookup() {
when(repository.findById(1L)).thenReturn(Optional.of(keyboard));
service.find(1L);
service.evict(1L);
service.find(1L);
verify(repository, times(2)).findById(1L);
}
}Three details matter here.
- Clear caches yourself. Spring reuses one application context across test classes, so cache contents survive from one test to the next. Without
clearCaches(), a test can pass or fail depending on execution order. Mockito mocks declared with@MockitoBeanare reset after each test, but caches are not. - Use the right key type.
get(1L)finds the entry because the key is aLong.get(1)uses anInteger, which does not equal1L, and returnsnull. Anullhere may mean a wrong key type and not a missing entry. - Spring version.
@MockitoBeanneeds Spring Framework 6.2 or Spring Boot 3.4. On older versions use@MockBeanfromorg.springframework.boot.test.mock.mockito.
A lighter test without Spring Boot
A full context is slow if you only need to test annotations. A small Spring test configuration with an in-memory ConcurrentMapCacheManager starts quickly and has no dependence on application.properties.
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig
class CatalogServiceProxyTest {
@Configuration
@EnableCaching
static class Config {
@Bean CacheManager cacheManager() {
return new ConcurrentMapCacheManager("products");
}
@Bean ProductRepository repository() {
return mock(ProductRepository.class);
}
@Bean CatalogService catalogService(ProductRepository repository) {
return new CatalogService(repository);
}
}
@Autowired CatalogService service;
@Autowired ProductRepository repository;
@Autowired CacheManager cacheManager;
@BeforeEach
void reset() {
cacheManager.getCache("products").clear();
org.mockito.Mockito.reset(repository);
}
@Test
void cachingIsActive() {
assertThat(AopUtils.isAopProxy(service)).isTrue();
}
@Test
void hitSkipsRepository() {
when(repository.findById(1L)).thenReturn(
Optional.of(new Product(1L, "Keyboard", new BigDecimal("49.90"))));
service.find(1L);
service.find(1L);
verify(repository, times(1)).findById(1L);
}
}The isAopProxy assertion is a cheap guard. If someone removes @EnableCaching or makes the class final, no proxy exists, the annotations do nothing, and this test fails with a clear message.
Test slices turn caching off
Slice annotations such as @WebMvcTest, @DataJpaTest and @JsonTest include @AutoConfigureCache. By default it replaces your cache provider with a no-op cache manager. Your @Cacheable methods still run, but nothing is stored. A test that expects a hit fails mysteriously.
If a slice test needs real caching, add @AutoConfigureCache(cacheProvider = CacheType.SIMPLE). CacheType is in org.springframework.boot.autoconfigure.cache, and SIMPLE is the in-memory map provider. Alternatively, test caching in a @SpringBootTest as shown above.
Edge cases to cover
- Self-invocation. Call the cached method from another method in the same class and verify the collaborator ran on every call. This test documents the proxy limit and fails if someone fixes it by moving the method to another bean.
- Mutable values. Local providers return the same object instance each time. Assert
isSameAsto see this. If callers modify a cached object, every later caller sees the change. Return immutable values such as records. - Expiration. Do not call
Thread.sleepfor a 10-minute TTL. Test your TTL configuration by reading it, or give the test profile a very short expiry and use Awaitility to wait for the entry to disappear. - Concurrent misses. To test
sync=true, start several threads on the same key with aCountDownLatchand verify the collaborator ran once. Run it many times, because a concurrency bug may pass on a single attempt.
Exercise
Your test calls service.find(1L) twice and uses verify(repository, times(1)). It passes alone but fails when the whole class runs. What is the likely cause, and what is the fix?
Show answer
The cache keeps entries between tests because Spring reuses the application context, so an earlier test already cached key 1L. The first call in this test becomes a hit and findById is never called, or the counts are off. Clear all caches in a @BeforeEach method with cacheManager.getCacheNames().forEach(n -> cacheManager.getCache(n).clear()).
Exercise
A @WebMvcTest controller test expects a second request to be served from the cache, but the service method runs both times. The same code is cached correctly in production. Why, and how do you restore caching in the test?
Show answer
Test slices apply @AutoConfigureCache, which swaps the cache provider for a no-op manager. Add @AutoConfigureCache(cacheProvider = CacheType.SIMPLE) to the test class, or use @SpringBootTest.