I am trying to unit test my redis map cache, the class has the following implementation:
public class ProductCacheTemplate extends CacheTemplate<Integer, Product> {
private RMapReactive<Integer, Product> map;
public ProductCacheTemplate(RedissonReactiveClient client) {
this.map = client.getMap("product", new TypedJsonJacksonCodec(Integer.class, Product.class));
}
@Override
protected Mono<Product> getFromCache(Integer id) {
return this.map.get(id);
}
@Override
protected Mono<Product> updateCache(Integer id, Product product) {
return this.map.fastPut(id, product).thenReturn(product);
}
@Override
protected Mono<Void> deleteFromCache(Integer id) {
return this.map.fastRemove(id).then();
}
}
I am wondering how do I mock the RMapReactive<Integer, Product> map
in this case?
I have tried the following approach but it doesn't work.
I still get NullPointerException when trying to get from cache.
@ExtendWith(MockitoExtension.class) class ProductCacheTemplateTest {
private ProductCacheTemplate productCache;
@Mock
private RedissonReactiveClient client;
@BeforeEach
public void setUp() {
this.client = Mockito.mock(RedissonReactiveClient.class);
this.redisCacheProperties = getRedisCacheProperties();
when(this.client.getMapCache(redisCacheProperties.getBadgeCache().getName(),
new TypedJsonJacksonCodec(Integer.class, Product.class)))
.thenAnswer(
invocation -> {
Integer key = invocation.getArgument(0);
if (key.equals(TEST_KEY)) {
return Mono.empty();
}
return null;
});
this.productCache = Mockito.spy(new ProductCache(client));
}
@Test
void testGetFromCache() {
Mono<Product> result = productCache.get(TEST_KEY);
StepVerifier.create(result)
.verifyComplete();
}
@Test
void putIntoCache() {
Mono<Product> result = productCache.put(TEST_KEY, TEST_VALUE);
StepVerifier.create(result)
.verifyComplete();
}
@Test
void deleteFromCache() {
Mono<Void> result = productCache.delete(TEST_KEY);
StepVerifier.create(result)
.verifyComplete();
}
private static final Integer TEST_KEY = 1;
private static final Product TEST_VALUE = new Product();
}