I want to test a service level method that is cached by the @Cacheable
annotation. I am mocking the service using Mockito. Below is my cache config and actual test
The cache has not been used and the Mockito verify fails with the method being called twice (instead of once)
My cache config:
@Configuration
@EnableCaching
public class CacheConfiguration implements CachingConfigurer {
private static final Log LOG = LogFactory.getLog(CacheConfiguration.class);
@Override
@Bean
public CaffeineCacheManager cacheManager() {
CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager(
"sample-cache");
caffeineCacheManager.setCaffeine(caffeineCacheBuilder());
caffeineCacheManager.setAllowNullValues(false);
return caffeineCacheManager;
}
Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder().maximumSize(50)
.expireAfterAccess(30, TimeUnit.MINUTES).softValues();
}
Test:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = *Application.class)
@AutoConfigureMockMvc
public class CachingIntegrationTest {
@MockBean
private Service service;
@Before
public void setUp() throws {
Mockito.reset(service);
String eg = "eg"''
Mockito.when(service.serviceMethod(argument))
.thenReturn(eg);
}
@Test
public void verifyCache() throws {
service.serviceMethod(argument);
service.serviceMethod(argument);
Mockito.verify(service, Mockito.times(1)).serviceMethod(argument);
}
I don't know for sure, but I'd be surprised if @Cacheable
annotations still work even if don't actually use the annotated object but instead a Mockito mock of it. The reason is that both techniques (ie the aspect-oriented programming annotation @Cacheable
and mocking) are implemented with Java dynamic proxies (or equivalent bytecode generation), so they are likely to get in each other's way.
What you should do instead is mock the collaborators of your service, and then check the number of invocations on these.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.