Home > Software design >  Why does @Cachable(...) work with @Bean return mock() but not with @MockedBean
Why does @Cachable(...) work with @Bean return mock() but not with @MockedBean

Time:09-23

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");
...
}

CodePudding user response:

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.

  • Related