Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does @Cachable(...) work with @Bean return mock() but not with @MockedBean

Why does the cache get filled with Values when using

@Autowired
ServiceXY serviceXY

@TestConfiguration
static class AppDefCachingTestConfiguration {
    @Bean
    public ServiceXY ServiceXYMock() {
        return mock(ServiceXY.class);
    }
}

But not with

@MockBean
ServiceXY serviceXY

When using @MockBean i get a NullPointerException when accessing the cache values like that in my test:

@Autowired
ConcurrentMapCacheManager cmcm; 

@Test
void anTest(){
when(serviceXY.methodThatFillsCache(anyString()).thenReturn("ABC");

serviceXY.methodThatFillsCache("TEST1");

cmcm.getCache("Cachename").get("TEST1",String.class).equals("ABC");
...
}
like image 603
Nico S. Avatar asked Oct 22 '25 16:10

Nico S.


1 Answers

Caching is implemented using a proxy that intercepts calls to the cacheable method. When you use @MockBean, Spring Boot intentionally disables proxying. One consequence of this is that no caching is performed. Someone recently made the point that this isn't very well documented so we may update the docs in the future.

If you're want to test that caching is working as expected, you should either use a genuine implementation of your service, or create the mock yourself via a @Bean method as you have done in the first example in your question.

like image 138
Andy Wilkinson Avatar answered Oct 24 '25 21:10

Andy Wilkinson