I'm trying to test my cache layer with mockito.
I'm using Caffeine as described here
Basically, I have this...
@Service
class Catalog {
@Autowired
Db db;
@Cachable
public List<Item> getItems() {
// fetch from db
db.someDbMethod();
}
}
@Configuration
@EnableCaching
class CatalogConfig {
@Bean
public CacheManager cacheManager() {
return new CaffeineCacheManager();
}
@Bean
public Db db() {
return new Db();
}
}
// properties as in documentation etc
That works perfectly, the method is cached and works fine.
I want to add a test to verify the DB call is invoked only once, I have something like this but it's not working:
public class CatalogTest {
@Mock
Db db;
@InjectMocks
Catalog catalog;
// init etc
@Test
void cache() {
catalog.getItems();
catalog.getItems();
verify(db, times(1)).someDbMethod(); // fails... expected 1 got 2
}
// Some other passing tests below
@Test
void getItems() {
assertNotNull(catalog.getItems()); // passes
}
}
I've tried several combinations of @Profile/@ActiveProfile
, Config/ContextConfiguration
etc.