1

I am using EhCache 3 with Spring and I want to do unit tests on this configuration class.

@Configuration
@EnableCaching
public class EhCacheConfiguration {

    @Bean
    public JCacheManagerCustomizer cacheManagerCustomizer() {
        return cacheManager -> {
            Cache<SimpleKey, Try.Success<Person>> cache = cacheManager .getCache("cache");
            if (cache == null) {
                cacheManager .createCache("cache", jcacheConfiguration());
            }
        };
    }

    private javax.cache.configuration.Configuration<SimpleKey, Try.Success> jcacheConfiguration() {
        return Eh107Configuration.fromEhcacheCacheConfiguration(
                CacheConfigurationBuilder
                        .newCacheConfigurationBuilder(
                                SimpleKey.class,
                                Try.Success.class,
                                ResourcePoolsBuilder.heap(2000).offheap(25, MemoryUnit.MB)
                        )
                        .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofHours(timeToLive)))
                        .build()
        );
    }
}   

I tried with this test class, but I can't mock the cacheManager inside the bean cacheManagerCustomizer. I tried with MockBean, Mock, InjectMocks but I'm lost

@ExtendWith(MockitoExtension.class)
class EhCacheConfigurationTest {

    private EhCacheConfiguration cut;

    @MockBean
    private CacheManager cacheManager;

    @BeforeEach
    void setUp() {
        cut = new EhCacheConfiguration();
        MockitoAnnotations.initMocks(this);
    }

    @Test
    void checkIfCacheIsCalled() {
        assertThat(cut.cacheManagerCustomizer()).isInstanceOf(JCacheManagerCustomizer.class);

        verify(cacheManager).getCache("cache");
    }
}

I have this error message:

org.mockito.exceptions.misusing.NullInsteadOfMockException: 
Argument passed to verify() should be a mock but is null!

How I can mock the CacheManager bean inside the cacheManagerCustomizer bean ?

CedricM
  • 11
  • 3

0 Answers0