Sub topic 14
Testing cached code
This chapter assumes you can write a @SpringBootTest, you know how @Cacheable, @CachePut and @CacheEvict behave, and you have used Mockito. Cached code needs tests because the annotations change behavior without changing the method body. A wrong key, a missing @EnableCaching or a self-invocation can leave the code returning correct values with no caching at all.
What to test
A test of cached code should answer three questions:
- Does a call store a result under the key you expect?
- Does a second call skip the method body?
- Do
@CachePutand@CacheEvictleave the cache in the state you intended?
Unit tests that construct the service with new cannot answer these questions. No proxy exists in that case, so no caching advice runs. Use a Spring context, which creates the proxy and the CacheManager.
Inspecting the cache directly
Inject the CacheManager and look inside the cache after calling the service.
import static org.assertj.core.api.Assertions.assertThat;
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;
@SpringBootTest
class ProductServiceCacheTest {
@Autowired
ProductService service;
@Autowired
CacheManager cacheManager;
@Test
void findByIdPopulatesCache() {
service.update(new Product(1L, "Keyboard", new java.math.BigDecimal("49.90")));
cacheManager.getCache("products").clear();
Product first = service.findById(1L);
assertThat(cacheManager.getCache("products").get(1L)).isNotNull();
assertThat(cacheManager.getCache("products").get(1L).get()).isEqualTo(first);
}
}update is called first to seed the backing store. The test then clears the cache, because @CachePut has already filled it. Without clear(), the assertion would pass even if findById were not cached.
Verifying that the method body is skipped
Checking the cache shows that an entry exists. It does not show that the second call avoided the work. To check that, wrap the bean in a spy and count invocations.
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
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.MockitoSpyBean;
@SpringBootTest
class ProductServiceCallCountTest {
@MockitoSpyBean
ProductService service;
@Autowired
CacheManager cacheManager;
@BeforeEach
void resetCaches() {
cacheManager.getCacheNames()
.forEach(name -> cacheManager.getCache(name).clear());
}
@Test
void secondCallIsServedFromCache() {
service.findById(1L);
service.findById(1L);
verify(service, times(1)).findById(1L);
}
}@MockitoSpyBean needs Spring Boot 3.4 or later. On older versions use @SpyBean. Spring applies the cache proxy and then the spy, so the second call returns from the cache before it reaches the counted method.
Keeping tests independent
The cache lives in the application context, and Spring reuses that context across test classes. An entry created in one test can make another test pass or fail by accident. Use these habits:
- Clear every cache in
@BeforeEach, as shown above. - Use
@DirtiesContextonly when you must, because it forces a slow context rebuild. - Test eviction by asserting that
cacheManager.getCache("products").get(1L)returnsnullafterdelete(1L).
Choosing the provider in tests
Tests run against whichever provider your configuration selects. Caffeine needs no external service, so it suits most tests. If production uses Redis, test serialization and TTL against a real Redis, for example in a Testcontainers container. Do not rely on Caffeine tests for that, because Caffeine never serializes values.
To check that your logic works without caching, set spring.cache.type=none for that test. The annotations stay in place, but nothing is stored.
Exercise
A test calls service.findById(1L) twice and uses assertThat on the returned values. The values are equal, so it passes. Why does this test fail to prove that caching works, and what should you add?
Show answer
Both calls return equal values whether or not the cache is used, because the method returns the same data from the store each time. Add a call-count check, such as verify(service, times(1)).findById(1L) on a @MockitoSpyBean, or assert through the CacheManager that the entry exists after the first call.