GuavaCacheBasedPredicateMemoizer extends AbstractGuavaCacheBasedMemoizer<KEY, Boolean> implements Predicate<INPUT> { @Override public boolean test(final INPUT input) { final KEY key = keyFunction.apply(input); return get(key, givenKey -> Boolean.valueOf(predicate.test(input))).booleanValue(); } GuavaCacheBasedPredicateMemoizer(
            final Cache<KEY, Boolean> cache,
            final Function<INPUT, KEY> keyFunction,
            final Predicate<INPUT> predicate); @Override boolean test(final INPUT input);  }
@Test @SuppressWarnings(CompilerWarnings.UNCHECKED) public void shouldTestGivenValue() { final Predicate<String> predicate = Mockito.mock(Predicate.class); final Function<String, String> keyFunction = Function.identity(); final Cache<String, Boolean> cache = CacheBuilder.newBuilder().build(); final GuavaCacheBasedPredicateMemoizer<String, String> memoizer = new GuavaCacheBasedPredicateMemoizer<>(cache, keyFunction, predicate); memoizer.test("value"); Mockito.verify(predicate).test("value"); }
@Test @SuppressWarnings(CompilerWarnings.UNCHECKED) public void shouldWrapExecutionExceptionInMemoizationException() throws ExecutionException { final Predicate<String> predicate = a -> true; final Function<String, String> keyFunction = Function.identity(); final Cache<String, Boolean> cache = Mockito.mock(Cache.class); given(cache.get(any(), any())).willThrow(ExecutionException.class); final GuavaCacheBasedPredicateMemoizer<String, String> memoizer = new GuavaCacheBasedPredicateMemoizer<>(cache, keyFunction, predicate); thrown.expect(MemoizationException.class); memoizer.test("test"); }
@Test public void shouldMemoizeResult() { final Predicate<String> predicate = a -> true; final Function<String, String> keyFunction = Function.identity(); final Cache<String, Boolean> cache = CacheBuilder.newBuilder().build(); final GuavaCacheBasedPredicateMemoizer<String, String> memoizer = new GuavaCacheBasedPredicateMemoizer<>(cache, keyFunction, predicate); Assert.assertTrue(memoizer.test("value")); }