ConcurrentMapBasedIntUnaryOperatorMemoizer extends ConcurrentMapBasedMemoizer<KEY, Integer> implements IntUnaryOperator { @Override public int applyAsInt(final int operand) { final KEY key = keyFunction.apply(operand); return computeIfAbsent(key, givenKey -> Integer.valueOf(operator.applyAsInt(operand))) .intValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedIntUnaryOperatorMemoizer(
            final ConcurrentMap<KEY, Integer> cache,
            final IntFunction<KEY> keyFunction,
            final IntUnaryOperator operator); @Override int applyAsInt(final int operand);  }
@Test public void shouldMemoizeOperator() { final ConcurrentMap<Integer, Integer> cache = new ConcurrentHashMap<>(); final IntUnaryOperator operator = input -> input; final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntUnaryOperatorMemoizer<Integer> memoizer = new ConcurrentMapBasedIntUnaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsInt(123); }
@Test public void shouldUseSetCacheKeyAndValue() { final ConcurrentMap<Integer, Integer> cache = new ConcurrentHashMap<>(); final IntUnaryOperator operator = input -> input; final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntUnaryOperatorMemoizer<Integer> memoizer = new ConcurrentMapBasedIntUnaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsInt(123); Assert.assertFalse("Cache is still empty after memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoization key does not match expectations", 123, memoizer.viewCacheForTest().keySet().iterator().next().intValue()); Assert.assertEquals("Memoization value does not match expectations", 123, memoizer.viewCacheForTest().values().iterator().next().intValue()); }
@Test public void shouldUseCallWrappedOperator() { final ConcurrentMap<Integer, Integer> cache = new ConcurrentHashMap<>(); final IntUnaryOperator operator = Mockito.mock(IntUnaryOperator.class); final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntUnaryOperatorMemoizer<Integer> memoizer = new ConcurrentMapBasedIntUnaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsInt(123); Mockito.verify(operator).applyAsInt(123); }
@Test public void shouldUseReturnOperatorResult() { final ConcurrentMap<Integer, Integer> cache = new ConcurrentHashMap<>(); final IntUnaryOperator operator = input -> input; final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntUnaryOperatorMemoizer<Integer> memoizer = new ConcurrentMapBasedIntUnaryOperatorMemoizer<>( cache, keyFunction, operator); Assert.assertEquals(123, memoizer.applyAsInt(123)); }