I had this working in with Spring Boot 1.x and JUnit 4 but after swapping to Spring Boot 2.x and JUnit 5 it no longer works.
Using Caffine for our cache manager.
The test was to ensure that our cache was preloading itself with some constants, nothing complicated.
@ContextConfiguration(classes = CacheConfig.class)
@EnableConfigurationProperties
public class CacheConfigTest {
@Autowired
private CacheManager myCacheManager;
@Test
public void verifyCacheManagerIsInitializedWithCaches() {
CacheConstants.CACHES.forEach(cacheName -> {
assertTrue(myCacheManager.getCacheNames().contains(cacheName)));
}
}
}
When I run it now the myCacheManager is null, causing the rest of the code to throw a null pointer exception unsurprisingly.
Here is the CacheConfig class for reference.
@EnableCaching
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
private static final String CACHE_EXPIRE_ONE_HOUR = "expireAfterAccess=3600s, expireAfterWrite=3600s";
@Bean
@Override
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager(CacheConstants.SOME_CONSTANT);
cacheManager.setCacheSpecification(CACHE_EXPIRE_ONE_HOUR);
return cacheManager;
}
@Bean
public CacheManager myCacheManager() {
return new CaffeineCacheManager(Arrays.stream(CacheConstants.CACHES.toArray()).toArray(String[]::new));
}
}
Since I went from JUnit 4 -> JUnit 5 I had to remove the @RunWith annotation from all my test classes. Which was great, it all ran fine.
Turns out I needed to add the @ExtendWith annotation to the top of the test classes using caching.
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CacheConfig.class)
@EnableConfigurationProperties
public class CacheConfigTest { ...
I'm not exactly sure why it was needed for just those cases, but it must have to do with the way the cache load up. And for some reason spring doesn't know how to load it the right contexts for it without that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With