3

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");
...
}
Nico S.
  • 77
  • 1
  • 1
  • 9

1 Answers1

5

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.

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • Thank you andy. I look in the javadocs that would be a greate place to point that out or maby i just oversaw it. I did know how to solve this problem already but i wanted to understand what happens in the background that made it much clearer. – Nico S. Sep 22 '21 at 13:56