JCacheBasedConsumerMemoizer extends AbstractJCacheBasedMemoizer<KEY, INPUT> implements Consumer<INPUT> { @Override public void accept(final INPUT input) { final KEY key = keyFunction.apply(input); invoke(key, givenKey -> { consumer.accept(input); return input; }); } JCacheBasedConsumerMemoizer(
            final Cache<KEY, INPUT> cache,
            final Function<INPUT, KEY> keyFunction,
            final Consumer<INPUT> consumer); @Override void accept(final INPUT input);  }
@Test public void shouldMemoizeConsumerOnce() { final Consumer<String> consumer = Mockito.mock(Consumer.class); final Function<String, String> keyFunction = Function.identity(); try (final Cache<String, String> cache = JCacheMemoize.createCache(Consumer.class)) { final JCacheBasedConsumerMemoizer<String, String> loader = new JCacheBasedConsumerMemoizer<>(cache, keyFunction, consumer); loader.accept("test"); loader.accept("test"); Mockito.verify(consumer).accept("test"); } }
@Test public void shouldWrapRuntimeExceptionInMemoizationException() { final Function<String, String> keyFunction = Function.identity(); try (final Cache<String, String> cache = Mockito.mock(Cache.class)) { final JCacheBasedConsumerMemoizer<String, String> loader = new JCacheBasedConsumerMemoizer<>(cache, keyFunction, null); given(cache.invoke(any(), any())).willThrow(RuntimeException.class); thrown.expect(MemoizationException.class); loader.accept("test"); } }
@Test public void shouldMemoizeConsumer() { final Consumer<String> consumer = Mockito.mock(Consumer.class); final Function<String, String> keyFunction = Function.identity(); try (final Cache<String, String> cache = JCacheMemoize.createCache(Consumer.class)) { final JCacheBasedConsumerMemoizer<String, String> loader = new JCacheBasedConsumerMemoizer<>(cache, keyFunction, consumer); loader.accept("test"); Mockito.verify(consumer).accept("test"); } }