From 03e9926f34481ce4a97d3b29d9bfa35ef0c61c25 Mon Sep 17 00:00:00 2001 From: Ben Manes Date: Sun, 26 Feb 2023 23:08:52 -0800 Subject: [PATCH] Prefer assertThrows to TestNG's expected exception or try-catch blocks. This narrows the amount of code that the exception can cover and makes the test's expectations more explicit. It also allowed for resolving most CheckReturnValue suppressions, so cases of FutureReturnValueIgnored were also handled when feasible. --- build.gradle | 8 +- .../caffeine/cache/BoundedLocalCache.java | 10 +- .../benmanes/caffeine/cache/AsMapTest.java | 294 ++++++------ .../caffeine/cache/AsyncAsMapTest.java | 358 ++++++++------- .../caffeine/cache/AsyncCacheTest.java | 213 ++++----- .../caffeine/cache/AsyncLoadingCacheTest.java | 180 +++----- .../caffeine/cache/BoundedBufferTest.java | 9 +- .../caffeine/cache/BoundedLocalCacheTest.java | 273 ++++++----- .../benmanes/caffeine/cache/CacheTest.java | 190 ++++---- .../caffeine/cache/CaffeineSpecGuavaTest.java | 17 +- .../caffeine/cache/CaffeineSpecTest.java | 16 +- .../benmanes/caffeine/cache/CaffeineTest.java | 357 ++++++++------- .../benmanes/caffeine/cache/EvictionTest.java | 335 +++++++------- .../caffeine/cache/ExpirationTest.java | 23 +- .../caffeine/cache/ExpireAfterAccessTest.java | 95 ++-- .../caffeine/cache/ExpireAfterVarTest.java | 431 ++++++++---------- .../caffeine/cache/ExpireAfterWriteTest.java | 125 ++--- .../caffeine/cache/FrequencySketchTest.java | 5 +- .../benmanes/caffeine/cache/InternerTest.java | 6 +- .../caffeine/cache/LinkedDequeTest.java | 60 +-- .../caffeine/cache/LoadingCacheTest.java | 231 ++++------ .../cache/MpscGrowableArrayQueueTest.java | 24 +- .../caffeine/cache/ReferenceTest.java | 86 ++-- .../caffeine/cache/RefreshAfterWriteTest.java | 14 +- .../caffeine/cache/SchedulerTest.java | 11 +- .../caffeine/cache/StripedBufferTest.java | 12 +- .../caffeine/cache/TimerWheelTest.java | 29 +- .../caffeine/cache/stats/CacheStatsTest.java | 10 +- .../cache/testing/GuavaCacheFromContext.java | 2 +- gradle/dependencies.gradle | 16 +- gradle/jmh.gradle | 4 - gradle/wrapper/gradle-wrapper.properties | 2 +- .../caffeine/guava/CaffeinatedGuavaTest.java | 167 +++---- .../compatibility/LocalLoadingCacheTest.java | 3 +- .../caffeine/jcache/CacheProxyTest.java | 75 ++- .../caffeine/jcache/JCacheProfiler.java | 8 +- .../JCacheConfigurationTest.java | 8 +- .../TypesafeConfigurationTest.java | 7 +- .../copy/JavaSerializationCopierTest.java | 39 +- .../jcache/event/JCacheEntryEventTest.java | 6 +- .../jcache/expiry/JCacheExpiryPolicyTest.java | 3 +- .../jcache/integration/CacheLoaderTest.java | 59 +-- .../jcache/integration/CacheWriterTest.java | 30 +- .../management/JmxRegistrationTest.java | 14 +- .../processor/EntryProcessorEntryTest.java | 6 +- .../jcache/processor/EntryProcessorTest.java | 19 +- .../spi/CaffeineCachingProviderTest.java | 7 +- 47 files changed, 1827 insertions(+), 2070 deletions(-) diff --git a/build.gradle b/build.gradle index 1d83802e9b..e7fe08c9ca 100644 --- a/build.gradle +++ b/build.gradle @@ -12,13 +12,7 @@ buildscript { repositories { mavenCentral() - gradlePluginPortal { - metadataSources { - ignoreGradleMetadataRedirection() - mavenPom() - artifact() - } - } + gradlePluginPortal() } dependencies { diff --git a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java index 7821ce0010..9fdebce672 100644 --- a/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java +++ b/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.java @@ -2065,14 +2065,16 @@ public void clear() { } // Remove any stragglers if released early to more aggressively flush incoming writes - while (!entries.isEmpty()) { - var node = entries.poll(); + boolean cleanUp = false; + for (var node : entries) { var key = node.getKey(); - if (key != null) { + if (key == null) { + cleanUp = true; + } else { remove(key); } } - if (collectKeys()) { + if (collectKeys() && cleanUp) { cleanUp(); } } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsMapTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsMapTest.java index cfeb7493c8..14fb7d925a 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsMapTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsMapTest.java @@ -29,6 +29,7 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static java.util.function.Function.identity; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -123,11 +124,10 @@ public void clear(Map map, CacheContext context) { /* --------------- contains --------------- */ @CheckNoStats - @SuppressWarnings("ReturnValueIgnored") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void containsKey_null(Map map, CacheContext context) { - map.containsKey(null); + assertThrows(NullPointerException.class, () -> map.containsKey(null)); } @CheckNoStats @@ -148,11 +148,10 @@ public void containsKey_absent(Map map, CacheContext context) { } @CheckNoStats - @SuppressWarnings("ReturnValueIgnored") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void containsValue_null(Map map, CacheContext context) { - map.containsValue(null); + assertThrows(NullPointerException.class, () -> map.containsValue(null)); } @CheckNoStats @@ -175,10 +174,10 @@ public void containsValue_absent(Map map, CacheContext context) { /* --------------- get --------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_null(Map map, CacheContext context) { - map.get(null); + assertThrows(NullPointerException.class, () -> map.get(null)); } @CheckNoStats @@ -201,10 +200,10 @@ public void get_present(Map map, CacheContext context) { /* --------------- getOrDefault --------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getOrDefault_nullKey(Map map, CacheContext context) { - map.getOrDefault(null, Int.valueOf(1)); + assertThrows(NullPointerException.class, () -> map.getOrDefault(null, Int.valueOf(1))); } @CheckNoStats @@ -229,10 +228,10 @@ public void getOrDefault_present(Map map, CacheContext context) { /* --------------- forEach --------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void forEach_null(Map map, CacheContext context) { - map.forEach(null); + assertThrows(NullPointerException.class, () -> map.forEach(null)); } @CheckNoStats @@ -263,24 +262,24 @@ public void forEach_modify(Map map, CacheContext context) { /* --------------- put --------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void put_nullKey(Map map, CacheContext context) { - map.put(null, Int.valueOf(1)); + assertThrows(NullPointerException.class, () -> map.put(null, Int.valueOf(1))); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void put_nullValue(Map map, CacheContext context) { - map.put(Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> map.put(Int.valueOf(1), null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void put_nullKeyAndValue(Map map, CacheContext context) { - map.put(null, null); + assertThrows(NullPointerException.class, () -> map.put(null, null)); } @CheckNoStats @@ -388,10 +387,10 @@ public void put_async_null(AsyncCache cache, CacheContext context) { /* --------------- putAll --------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void putAll_null(Map map, CacheContext context) { - map.putAll(null); + assertThrows(NullPointerException.class, () -> map.putAll(null)); } @CheckNoStats @@ -454,24 +453,24 @@ public void putAll_mixed(Map map, CacheContext context) { /* --------------- putIfAbsent --------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void putIfAbsent_nullKey(Map map, CacheContext context) { - map.putIfAbsent(null, Int.valueOf(2)); + assertThrows(NullPointerException.class, () -> map.putIfAbsent(null, Int.valueOf(2))); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void putIfAbsent_nullValue(Map map, CacheContext context) { - map.putIfAbsent(Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> map.putIfAbsent(Int.valueOf(1), null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void putIfAbsent_nullKeyAndValue(Map map, CacheContext context) { - map.putIfAbsent(null, null); + assertThrows(NullPointerException.class, () -> map.putIfAbsent(null, null)); } @CheckNoStats @@ -524,10 +523,10 @@ public void putIfAbsent_async_null(AsyncCache cache, CacheContext cont /* --------------- remove --------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void remove_nullKey(Map map, CacheContext context) { - map.remove(null); + assertThrows(NullPointerException.class, () -> map.remove(null)); } @CheckNoStats @@ -581,10 +580,10 @@ public void remove_async_null(AsyncCache cache, CacheContext context) /* --------------- remove conditionally --------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void removeConditionally_nullKey(Map map, CacheContext context) { - map.remove(null, context.absentValue()); + assertThrows(NullPointerException.class, () -> map.remove(null, context.absentValue())); } @CheckNoStats @@ -595,10 +594,10 @@ public void removeConditionally_nullValue(Map map, CacheContext contex } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void removeConditionally_nullKeyAndValue(Map map, CacheContext context) { - map.remove(null, null); + assertThrows(NullPointerException.class, () -> map.remove(null, null)); } @CheckNoStats @@ -664,24 +663,24 @@ public void removeConditionally_async_null( /* --------------- replace --------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replace_null(Map map, CacheContext context) { - map.replace(null, Int.valueOf(1)); + assertThrows(NullPointerException.class, () -> map.replace(null, Int.valueOf(1))); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replace_nullValue(Map map, CacheContext context) { - map.replace(Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> map.replace(Int.valueOf(1), null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replace_nullKeyAndValue(Map map, CacheContext context) { - map.replace(null, null); + assertThrows(NullPointerException.class, () -> map.replace(null, null)); } @CheckNoStats @@ -772,52 +771,55 @@ public void replace_async_null(AsyncCache cache, CacheContext context) /* --------------- replace conditionally --------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullKey(Map map, CacheContext context) { - map.replace(null, Int.valueOf(1), Int.valueOf(1)); + assertThrows(NullPointerException.class, () -> + map.replace(null, Int.valueOf(1), Int.valueOf(1))); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullOldValue(Map map, CacheContext context) { - map.replace(Int.valueOf(1), null, Int.valueOf(1)); + assertThrows(NullPointerException.class, () -> + map.replace(Int.valueOf(1), null, Int.valueOf(1))); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullNewValue(Map map, CacheContext context) { - map.replace(Int.valueOf(1), Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> + map.replace(Int.valueOf(1), Int.valueOf(1), null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullKeyAndOldValue(Map map, CacheContext context) { - map.replace(null, null, Int.valueOf(1)); + assertThrows(NullPointerException.class, () -> map.replace(null, null, Int.valueOf(1))); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullKeyAndNewValue(Map map, CacheContext context) { - map.replace(null, Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> map.replace(null, Int.valueOf(1), null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullOldAndNewValue(Map map, CacheContext context) { - map.replace(Int.valueOf(1), null, null); + assertThrows(NullPointerException.class, () -> map.replace(Int.valueOf(1), null, null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullKeyAndValues(Map map, CacheContext context) { - map.replace(null, null, null); + assertThrows(NullPointerException.class, () -> map.replace(null, null, null)); } @CheckNoStats @@ -923,18 +925,18 @@ public void replaceConditionally_async_null( /* --------------- replaceAll --------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void replaceAll_null(Map map, CacheContext context) { - map.replaceAll(null); + assertThrows(NullPointerException.class, () -> map.replaceAll(null)); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void replaceAll_nullValue(Map map, CacheContext context) { - map.replaceAll((key, value) -> null); + assertThrows(NullPointerException.class, () -> map.replaceAll((key, value) -> null)); } @CacheSpec @@ -967,17 +969,17 @@ public void replaceAll_differentValue(Map map, CacheContext context) { /* --------------- computeIfAbsent --------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void computeIfAbsent_nullKey(Map map, CacheContext context) { - map.computeIfAbsent(null, Int::negate); + assertThrows(NullPointerException.class, () -> map.computeIfAbsent(null, Int::negate)); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void computeIfAbsent_nullMappingFunction(Map map, CacheContext context) { - map.computeIfAbsent(context.absentKey(), null); + assertThrows(NullPointerException.class, () -> map.computeIfAbsent(context.absentKey(), null)); } @Test(dataProvider = "caches") @@ -1078,17 +1080,18 @@ public void computeIfAbsent_async_null(AsyncCache cache, CacheContext /* --------------- computeIfPresent --------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void computeIfPresent_nullKey(Map map, CacheContext context) { - map.computeIfPresent(null, (key, value) -> key.negate()); + assertThrows(NullPointerException.class, () -> + map.computeIfPresent(null, (key, value) -> key.negate())); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void computeIfPresent_nullMappingFunction(Map map, CacheContext context) { - map.computeIfPresent(Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> map.computeIfPresent(Int.valueOf(1), null)); } @Test(dataProvider = "caches") @@ -1107,9 +1110,9 @@ public void computeIfPresent_nullValue(Map map, CacheContext context) .contains(removed).exclusively(); } + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = StackOverflowError.class) public void computeIfPresent_recursive(Map map, CacheContext context) { // As we cannot provide immediate checking without an expensive solution, e.g. ThreadLocal, // instead we assert that a stack overflow error will occur to inform the developer (vs @@ -1125,12 +1128,13 @@ public void computeIfPresent_recursive(Map map, CacheContext context) return map.computeIfPresent(key, this); } }; - map.computeIfPresent(context.firstKey(), mappingFunction); + assertThrows(StackOverflowError.class, () -> + map.computeIfPresent(context.firstKey(), mappingFunction)); } + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = StackOverflowError.class) public void computeIfPresent_pingpong(Map map, CacheContext context) { // As we cannot provide immediate checking without an expensive solution, e.g. ThreadLocal, // instead we assert that a stack overflow error will occur to inform the developer (vs @@ -1145,7 +1149,8 @@ public void computeIfPresent_pingpong(Map map, CacheContext context) { return map.computeIfPresent(context.lastKey(), this); } }; - map.computeIfPresent(context.firstKey(), mappingFunction); + assertThrows(StackOverflowError.class, () -> + map.computeIfPresent(context.firstKey(), mappingFunction)); } @Test(dataProvider = "caches") @@ -1257,17 +1262,17 @@ public void computeIfPresent_async_null(AsyncCache cache, CacheContext /* --------------- compute --------------- */ + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void compute_nullKey(Map map, CacheContext context) { - map.compute(null, (key, value) -> key.negate()); + assertThrows(NullPointerException.class, () -> map.compute(null, (key, value) -> key.negate())); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void compute_nullMappingFunction(Map map, CacheContext context) { - map.compute(Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> map.compute(Int.valueOf(1), null)); } @Test(dataProvider = "caches") @@ -1440,24 +1445,26 @@ public void compute_async_null( /* --------------- merge --------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void merge_nullKey(Map map, CacheContext context) { - map.merge(null, Int.valueOf(1), (oldValue, value) -> oldValue.negate()); + assertThrows(NullPointerException.class, () -> + map.merge(null, Int.valueOf(1), (oldValue, value) -> oldValue.negate())); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void merge_nullValue(Map map, CacheContext context) { - map.merge(Int.valueOf(1), null, (oldValue, value) -> oldValue.negate()); + assertThrows(NullPointerException.class, () -> + map.merge(Int.valueOf(1), null, (oldValue, value) -> oldValue.negate())); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void merge_nullMappingFunction(Map map, CacheContext context) { - map.merge(Int.valueOf(1), Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> map.merge(Int.valueOf(1), Int.valueOf(1), null)); } @Test(dataProvider = "caches") @@ -1490,9 +1497,9 @@ public void merge_recursive(Map map, CacheContext context) { assertThat(value).isEqualTo(firstValue); } + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = StackOverflowError.class) public void merge_pingpong(Map map, CacheContext context) { // As we cannot provide immediate checking without an expensive solution, e.g. ThreadLocal, // instead we assert that a stack overflow error will occur to inform the developer (vs @@ -1507,7 +1514,8 @@ public void merge_pingpong(Map map, CacheContext context) { return map.merge(context.lastKey(), context.original().get(context.lastKey()), this); } }; - map.merge(context.firstKey(), context.original().get(context.firstKey()), mappingFunction); + assertThrows(StackOverflowError.class, () -> + map.merge(context.firstKey(), context.original().get(context.firstKey()), mappingFunction)); } @Test(dataProvider = "caches") @@ -1723,10 +1731,10 @@ private static Map parseToString(Map map) { /* --------------- Key Set --------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void keySet_toArray_null(Map map, CacheContext context) { - map.keySet().toArray((Int[]) null); + assertThrows(NullPointerException.class, () -> map.keySet().toArray((Int[]) null)); } @CheckNoStats @@ -1768,9 +1776,9 @@ public void keySet_whenEmpty(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void keySet_addNotSupported(Map map, CacheContext context) { - map.keySet().add(Int.valueOf(1)); + assertThrows(UnsupportedOperationException.class, () -> map.keySet().add(Int.valueOf(1))); } @CacheSpec @@ -1785,9 +1793,9 @@ public void keySet_clear(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySet_removeAll_null(Map map, CacheContext context) { - map.keySet().removeAll(null); + assertThrows(NullPointerException.class, () -> map.keySet().removeAll(null)); } @CacheSpec @@ -1879,9 +1887,9 @@ public void keySet_removeAll_bySet(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySet_remove_null(Map map, CacheContext context) { - map.keySet().remove(null); + assertThrows(NullPointerException.class, () -> map.keySet().remove(null)); } @CacheSpec @@ -1908,9 +1916,9 @@ public void keySet_remove(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySet_removeIf_null(Map map, CacheContext context) { - map.keySet().removeIf(null); + assertThrows(NullPointerException.class, () -> map.keySet().removeIf(null)); } @CacheSpec @@ -1954,9 +1962,9 @@ public void keySet_removeIf_all(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySet_retainAll_null(Map map, CacheContext context) { - map.keySet().retainAll(null); + assertThrows(NullPointerException.class, () -> map.keySet().retainAll(null)); } @CacheSpec @@ -2058,26 +2066,27 @@ public void keySet_iterator(Map map, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void keyIterator_noElement(Map map, CacheContext context) { - map.keySet().iterator().remove(); + assertThrows(IllegalStateException.class, () -> map.keySet().iterator().remove()); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NoSuchElementException.class) public void keyIterator_noMoreElements(Map map, CacheContext context) { - map.keySet().iterator().next(); + assertThrows(NoSuchElementException.class, () -> map.keySet().iterator().next()); } @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySpliterator_forEachRemaining_null(Map map, CacheContext context) { - map.keySet().spliterator().forEachRemaining(null); + assertThrows(NullPointerException.class, () -> + map.keySet().spliterator().forEachRemaining(null)); } @CacheSpec @@ -2091,9 +2100,9 @@ public void keySpliterator_forEachRemaining(Map map, CacheContext cont @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySpliterator_tryAdvance_null(Map map, CacheContext context) { - map.keySet().spliterator().tryAdvance(null); + assertThrows(NullPointerException.class, () -> map.keySet().spliterator().tryAdvance(null)); } @CacheSpec @@ -2133,10 +2142,10 @@ public void keySpliterator_estimateSize(Map map, CacheContext context) /* --------------- Values --------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void values_toArray_null(Map map, CacheContext context) { - map.values().toArray((Int[]) null); + assertThrows(NullPointerException.class, () -> map.values().toArray((Int[]) null)); } @CheckNoStats @@ -2177,11 +2186,11 @@ public void values_empty(Map map, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void values_addNotSupported(Map map, CacheContext context) { - map.values().add(Int.valueOf(1)); + assertThrows(UnsupportedOperationException.class, () -> map.values().add(Int.valueOf(1))); } @CacheSpec @@ -2196,9 +2205,9 @@ public void values_clear(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void values_removeAll_null(Map map, CacheContext context) { - map.values().removeAll(null); + assertThrows(NullPointerException.class, () -> map.values().removeAll(null)); } @CacheSpec @@ -2311,9 +2320,9 @@ public void values_remove_once(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void values_removeIf_null(Map map, CacheContext context) { - map.values().removeIf(null); + assertThrows(NullPointerException.class, () -> map.values().removeIf(null)); } @CacheSpec @@ -2357,9 +2366,9 @@ public void values_removeIf_all(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void values_retainAll_null(Map map, CacheContext context) { - map.values().retainAll(null); + assertThrows(NullPointerException.class, () -> map.values().retainAll(null)); } @CacheSpec @@ -2465,26 +2474,27 @@ public void valueIterator(Map map, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void valueIterator_noElement(Map map, CacheContext context) { - map.values().iterator().remove(); + assertThrows(IllegalStateException.class, () -> map.values().iterator().remove()); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NoSuchElementException.class) public void valueIterator_noMoreElements(Map map, CacheContext context) { - map.values().iterator().next(); + assertThrows(NoSuchElementException.class, () -> map.values().iterator().next()); } @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void valueSpliterator_forEachRemaining_null(Map map, CacheContext context) { - map.values().spliterator().forEachRemaining(null); + assertThrows(NullPointerException.class, () -> + map.values().spliterator().forEachRemaining(null)); } @CacheSpec @@ -2498,9 +2508,9 @@ public void valueSpliterator_forEachRemaining(Map map, CacheContext co @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void valueSpliterator_tryAdvance_null(Map map, CacheContext context) { - map.values().spliterator().tryAdvance(null); + assertThrows(NullPointerException.class, () -> map.values().spliterator().tryAdvance(null)); } @CacheSpec @@ -2540,10 +2550,11 @@ public void valueSpliterator_estimateSize(Map map, CacheContext contex /* --------------- Entry Set --------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void entrySet_toArray_null(Map map, CacheContext context) { - map.entrySet().toArray((Map.Entry[]) null); + assertThrows(NullPointerException.class, () -> + map.entrySet().toArray((Map.Entry[]) null)); } @CheckNoStats @@ -2604,14 +2615,12 @@ public void entrySet_empty(Map map, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = Listener.DISABLED) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void entrySet_addIsNotSupported(Map map, CacheContext context) { - try { - map.entrySet().add(Map.entry(Int.valueOf(1), Int.valueOf(2))); - } finally { - assertThat(map).isExhaustivelyEmpty(); - } + assertThrows(UnsupportedOperationException.class, () -> + map.entrySet().add(Map.entry(Int.valueOf(1), Int.valueOf(2)))); + assertThat(map).isExhaustivelyEmpty(); } @CacheSpec @@ -2626,9 +2635,9 @@ public void entrySet_clear(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void entrySet_removeAll_null(Map map, CacheContext context) { - map.entrySet().removeAll(null); + assertThrows(NullPointerException.class, () -> map.entrySet().removeAll(null)); } @CacheSpec @@ -2780,9 +2789,9 @@ public void entrySet_remove(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void entrySet_removeIf_null(Map map, CacheContext context) { - map.entrySet().removeIf(null); + assertThrows(NullPointerException.class, () -> map.entrySet().removeIf(null)); } @CacheSpec @@ -2826,9 +2835,9 @@ public void entrySet_removeIf_all(Map map, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void entrySet_retainAll_null(Map map, CacheContext context) { - map.entrySet().retainAll(null); + assertThrows(NullPointerException.class, () -> map.entrySet().retainAll(null)); } @CacheSpec @@ -2936,26 +2945,27 @@ public void entryIterator(Map map, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void entryIterator_noElement(Map map, CacheContext context) { - map.entrySet().iterator().remove(); + assertThrows(IllegalStateException.class, () -> map.entrySet().iterator().remove()); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NoSuchElementException.class) public void entryIterator_noMoreElements(Map map, CacheContext context) { - map.entrySet().iterator().next(); + assertThrows(NoSuchElementException.class, () -> map.entrySet().iterator().next()); } @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void entrySpliterator_forEachRemaining_null(Map map, CacheContext context) { - map.entrySet().spliterator().forEachRemaining(null); + assertThrows(NullPointerException.class, () -> + map.entrySet().spliterator().forEachRemaining(null)); } @CacheSpec @@ -2975,9 +2985,9 @@ public void entrySpliterator_forEachRemaining(Map map, CacheContext co @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void entrySpliterator_tryAdvance_null(Map map, CacheContext context) { - map.entrySet().spliterator().tryAdvance(null); + assertThrows(NullPointerException.class, () -> map.entrySet().spliterator().tryAdvance(null)); } @CacheSpec @@ -3036,10 +3046,10 @@ public void writeThroughEntry(Map map, CacheContext context) { } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }) public void writeThroughEntry_null(Map map, CacheContext context) { - map.entrySet().iterator().next().setValue(null); + assertThrows(NullPointerException.class, () -> map.entrySet().iterator().next().setValue(null)); } @CheckNoStats diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncAsMapTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncAsMapTest.java index 6e234cabc8..d3b3bbfe8a 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncAsMapTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncAsMapTest.java @@ -29,6 +29,7 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static java.util.function.Function.identity; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -115,11 +116,10 @@ public void clear(AsyncCache cache, CacheContext context) { /* ---------------- contains -------------- */ @CheckNoStats - @SuppressWarnings("ReturnValueIgnored") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void containsKey_null(AsyncCache cache, CacheContext context) { - cache.asMap().containsKey(null); + assertThrows(NullPointerException.class, () -> cache.asMap().containsKey(null)); } @CheckNoStats @@ -140,11 +140,10 @@ public void containsKey_absent(AsyncCache cache, CacheContext context) } @CheckNoStats - @SuppressWarnings("ReturnValueIgnored") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void containsValue_null(AsyncCache cache, CacheContext context) { - cache.asMap().containsValue(null); + assertThrows(NullPointerException.class, () -> cache.asMap().containsValue(null)); } @CheckNoStats @@ -167,10 +166,10 @@ public void containsValue_absent(AsyncCache cache, CacheContext contex /* ---------------- get -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_null(AsyncCache cache, CacheContext context) { - cache.asMap().get(null); + assertThrows(NullPointerException.class, () -> cache.asMap().get(null)); } @CheckNoStats @@ -193,10 +192,11 @@ public void get_present(AsyncCache cache, CacheContext context) { /* ---------------- getOrDefault -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getOrDefault_nullKey(AsyncCache cache, CacheContext context) { - cache.asMap().getOrDefault(null, Int.valueOf(1).asFuture()); + assertThrows(NullPointerException.class, () -> + cache.asMap().getOrDefault(null, Int.valueOf(1).asFuture())); } @CheckNoStats @@ -222,10 +222,10 @@ public void getOrDefault_present(AsyncCache cache, CacheContext contex /* ---------------- forEach -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void forEach_null(AsyncCache cache, CacheContext context) { - cache.asMap().forEach(null); + assertThrows(NullPointerException.class, () -> cache.asMap().forEach(null)); } @CheckNoStats @@ -257,24 +257,26 @@ public void forEach_modify(AsyncCache cache, CacheContext context) { /* ---------------- put -------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void put_nullKey(AsyncCache cache, CacheContext context) { - cache.asMap().put(null, Int.valueOf(1).asFuture()); + assertThrows(NullPointerException.class, () -> + cache.asMap().put(null, Int.valueOf(1).asFuture())); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void put_nullValue(AsyncCache cache, CacheContext context) { - cache.asMap().put(Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> + cache.asMap().put(Int.valueOf(1), null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void put_nullKeyAndValue(AsyncCache cache, CacheContext context) { - cache.asMap().put(null, null); + assertThrows(NullPointerException.class, () -> cache.asMap().put(null, null)); } @Test(dataProvider = "caches") @@ -347,10 +349,10 @@ public void put_recursiveUpdate(AsyncCache cache, CacheContext context /* ---------------- putAll -------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void putAll_null(AsyncCache cache, CacheContext context) { - cache.asMap().putAll(null); + assertThrows(NullPointerException.class, () -> cache.asMap().putAll(null)); } @CheckNoStats @@ -407,24 +409,26 @@ public void putAll_mixed(AsyncCache cache, CacheContext context) { /* ---------------- putIfAbsent -------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void putIfAbsent_nullKey(AsyncCache cache, CacheContext context) { - cache.asMap().putIfAbsent(null, Int.valueOf(2).asFuture()); + assertThrows(NullPointerException.class, () -> + cache.asMap().putIfAbsent(null, Int.valueOf(2).asFuture())); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void putIfAbsent_nullValue(AsyncCache cache, CacheContext context) { - cache.asMap().putIfAbsent(Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> + cache.asMap().putIfAbsent(Int.valueOf(1), null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void putIfAbsent_nullKeyAndValue(AsyncCache cache, CacheContext context) { - cache.asMap().putIfAbsent(null, null); + assertThrows(NullPointerException.class, () -> cache.asMap().putIfAbsent(null, null)); } @CheckNoStats @@ -452,10 +456,10 @@ public void putIfAbsent_insert(AsyncCache cache, CacheContext context) /* ---------------- remove -------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void remove_nullKey(AsyncCache cache, CacheContext context) { - cache.asMap().remove(null); + assertThrows(NullPointerException.class, () -> cache.asMap().remove(null)); } @CheckNoStats @@ -483,10 +487,11 @@ public void remove_present(AsyncCache cache, CacheContext context) { /* ---------------- remove conditionally -------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void removeConditionally_nullKey(AsyncCache cache, CacheContext context) { - cache.asMap().remove(null, context.absentValue().asFuture()); + assertThrows(NullPointerException.class, () -> + cache.asMap().remove(null, context.absentValue().asFuture())); } @CheckNoStats @@ -497,11 +502,11 @@ public void removeConditionally_nullValue(AsyncCache cache, CacheConte } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void removeConditionally_nullKeyAndValue( AsyncCache cache, CacheContext context) { - cache.asMap().remove(null, null); + assertThrows(NullPointerException.class, () -> cache.asMap().remove(null, null)); } @CheckNoStats @@ -543,24 +548,25 @@ public void removeConditionally_presentKeyAndValue( /* ---------------- replace -------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replace_null(AsyncCache cache, CacheContext context) { - cache.asMap().replace(null, Int.valueOf(1).asFuture()); + assertThrows(NullPointerException.class, () -> + cache.asMap().replace(null, Int.valueOf(1).asFuture())); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replace_nullValue(AsyncCache cache, CacheContext context) { - cache.asMap().replace(Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> cache.asMap().replace(Int.valueOf(1), null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replace_nullKeyAndValue(AsyncCache cache, CacheContext context) { - cache.asMap().replace(null, null); + assertThrows(NullPointerException.class, () -> cache.asMap().replace(null, null)); } @CheckNoStats @@ -627,61 +633,64 @@ public void replace_differentValue(AsyncCache cache, CacheContext cont /* ---------------- replace conditionally -------------- */ @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullKey(AsyncCache cache, CacheContext context) { var value = Int.valueOf(1).asFuture(); - cache.asMap().replace(null, value, value); + assertThrows(NullPointerException.class, () -> cache.asMap().replace(null, value, value)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullOldValue(AsyncCache cache, CacheContext context) { var value = Int.valueOf(1).asFuture(); - cache.asMap().replace(Int.valueOf(1), null, value); + assertThrows(NullPointerException.class, () -> + cache.asMap().replace(Int.valueOf(1), null, value)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullNewValue(AsyncCache cache, CacheContext context) { var value = Int.futureOf(1); - cache.asMap().replace(Int.valueOf(1), value, null); + assertThrows(NullPointerException.class, () -> + cache.asMap().replace(Int.valueOf(1), value, null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullKeyAndOldValue( AsyncCache cache, CacheContext context) { var value = Int.futureOf(1); - cache.asMap().replace(null, null, value); + assertThrows(NullPointerException.class, () -> cache.asMap().replace(null, null, value)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullKeyAndNewValue( AsyncCache cache, CacheContext context) { var value = Int.futureOf(1); - cache.asMap().replace(null, value, null); + assertThrows(NullPointerException.class, () -> cache.asMap().replace(null, value, null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullOldAndNewValue( AsyncCache cache, CacheContext context) { - cache.asMap().replace(Int.valueOf(1), null, null); + assertThrows(NullPointerException.class, () -> + cache.asMap().replace(Int.valueOf(1), null, null)); } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void replaceConditionally_nullKeyAndValues( AsyncCache cache, CacheContext context) { - cache.asMap().replace(null, null, null); + assertThrows(NullPointerException.class, () -> cache.asMap().replace(null, null, null)); } @CheckNoStats @@ -754,18 +763,18 @@ public void replaceConditionally_differentValue( /* ---------------- replaceAll -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void replaceAll_null(AsyncCache cache, CacheContext context) { - cache.asMap().replaceAll(null); + assertThrows(NullPointerException.class, () -> cache.asMap().replaceAll(null)); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void replaceAll_nullValue(AsyncCache cache, CacheContext context) { - cache.asMap().replaceAll((key, value) -> null); + assertThrows(NullPointerException.class, () -> cache.asMap().replaceAll((key, value) -> null)); } @CacheSpec @@ -790,18 +799,20 @@ public void replaceAll_differentValue(AsyncCache cache, CacheContext c /* ---------------- computeIfAbsent -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void computeIfAbsent_nullKey(AsyncCache cache, CacheContext context) { - cache.asMap().computeIfAbsent(null, key -> key.negate().asFuture()); + assertThrows(NullPointerException.class, () -> + cache.asMap().computeIfAbsent(null, key -> key.negate().asFuture())); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void computeIfAbsent_nullMappingFunction( AsyncCache cache, CacheContext context) { - cache.asMap().computeIfAbsent(context.absentKey(), null); + assertThrows(NullPointerException.class, () -> + cache.asMap().computeIfAbsent(context.absentKey(), null)); } @CheckNoStats @@ -843,12 +854,11 @@ public void computeIfAbsent_pingpong(AsyncCache cache, CacheContext co @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void computeIfAbsent_error(AsyncCache cache, CacheContext context) { - try { - cache.asMap().computeIfAbsent(context.absentKey(), - key -> { throw new IllegalStateException(); }); - Assert.fail(); - } catch (IllegalStateException expected) {} + var expected = new IllegalStateException(); + var actual = assertThrows(IllegalStateException.class, () -> + cache.asMap().computeIfAbsent(context.absentKey(), key -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); assertThat(cache).containsExactlyEntriesIn(context.original()); assertThat(context).stats().hits(0).misses(0).success(0).failures(0); var future = cache.asMap().computeIfAbsent(context.absentKey(), Int::asFuture); @@ -883,18 +893,20 @@ public void computeIfAbsent_absent(AsyncCache cache, CacheContext cont /* ---------------- computeIfPresent -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void computeIfPresent_nullKey(AsyncCache cache, CacheContext context) { - cache.asMap().computeIfPresent(null, (key, value) -> key.negate().asFuture()); + assertThrows(NullPointerException.class, () -> + cache.asMap().computeIfPresent(null, (key, value) -> key.negate().asFuture())); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void computeIfPresent_nullMappingFunction( AsyncCache cache, CacheContext context) { - cache.asMap().computeIfPresent(Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> + cache.asMap().computeIfPresent(Int.valueOf(1), null)); } @CheckNoStats @@ -913,9 +925,9 @@ public void computeIfPresent_nullValue(AsyncCache cache, CacheContext .contains(removed).exclusively(); } + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = StackOverflowError.class) public void computeIfPresent_recursive(AsyncCache cache, CacheContext context) { // As we cannot provide immediate checking without an expensive solution, e.g. ThreadLocal, // instead we assert that a stack overflow error will occur to inform the developer (vs @@ -931,12 +943,13 @@ public void computeIfPresent_recursive(AsyncCache cache, CacheContext return cache.asMap().computeIfPresent(key, this); } }; - cache.asMap().computeIfPresent(context.firstKey(), mappingFunction); + assertThrows(StackOverflowError.class, () -> + cache.asMap().computeIfPresent(context.firstKey(), mappingFunction)); } + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = StackOverflowError.class) public void computeIfPresent_pingpong(AsyncCache cache, CacheContext context) { // As we cannot provide immediate checking without an expensive solution, e.g. ThreadLocal, // instead we assert that a stack overflow error will occur to inform the developer (vs @@ -951,17 +964,17 @@ public void computeIfPresent_pingpong(AsyncCache cache, CacheContext c return cache.asMap().computeIfPresent(context.lastKey(), this); } }; - cache.asMap().computeIfPresent(context.firstKey(), mappingFunction); + assertThrows(StackOverflowError.class, () -> + cache.asMap().computeIfPresent(context.firstKey(), mappingFunction)); } @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }) public void computeIfPresent_error(AsyncCache cache, CacheContext context) { - try { - cache.asMap().computeIfPresent(context.firstKey(), - (key, value) -> { throw new IllegalStateException(); }); - Assert.fail(); - } catch (IllegalStateException expected) {} + var expected = new IllegalStateException(); + var actual = assertThrows(IllegalStateException.class, () -> + cache.asMap().computeIfPresent(context.firstKey(), (key, value) -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); assertThat(cache).containsExactlyEntriesIn(context.original()); assertThat(context).stats().hits(0).misses(0).success(0).failures(0); @@ -1036,17 +1049,18 @@ public void computeIfPresent_present_differentValue( /* ---------------- compute -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void compute_nullKey(AsyncCache cache, CacheContext context) { - cache.asMap().compute(null, (key, value) -> key.negate().asFuture()); + assertThrows(NullPointerException.class, () -> + cache.asMap().compute(null, (key, value) -> key.negate().asFuture())); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void compute_nullMappingFunction(AsyncCache cache, CacheContext context) { - cache.asMap().compute(Int.valueOf(1), null); + assertThrows(NullPointerException.class, () -> cache.asMap().compute(Int.valueOf(1), null)); } @CheckNoStats @@ -1098,11 +1112,11 @@ public void compute_pingpong(AsyncCache cache, CacheContext context) { @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void compute_error(AsyncCache cache, CacheContext context) { - try { - cache.asMap().compute(context.absentKey(), - (key, value) -> { throw new IllegalStateException(); }); - Assert.fail(); - } catch (IllegalStateException expected) {} + var expected = new IllegalStateException(); + var actual = assertThrows(IllegalStateException.class, () -> + cache.asMap().compute(context.absentKey(), (key, value) -> { throw expected; })); + + assertThat(expected).isSameInstanceAs(actual); assertThat(cache).containsExactlyEntriesIn(context.original()); assertThat(context).stats().hits(0).misses(0).success(0).failures(0); @@ -1189,24 +1203,27 @@ public void compute_differentValue(AsyncCache cache, CacheContext cont /* ---------------- merge -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void merge_nullKey(AsyncCache cache, CacheContext context) { - cache.asMap().merge(null, Int.valueOf(-1).asFuture(), (oldValue, value) -> value); + assertThrows(NullPointerException.class, () -> + cache.asMap().merge(null, Int.valueOf(-1).asFuture(), (oldValue, value) -> value)); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void merge_nullValue(AsyncCache cache, CacheContext context) { - cache.asMap().merge(Int.valueOf(1), null, (oldValue, value) -> null); + assertThrows(NullPointerException.class, () -> + cache.asMap().merge(Int.valueOf(1), null, (oldValue, value) -> null)); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void merge_nullMappingFunction(AsyncCache cache, CacheContext context) { - cache.asMap().merge(Int.valueOf(1), Int.valueOf(1).asFuture(), null); + assertThrows(NullPointerException.class, () -> + cache.asMap().merge(Int.valueOf(1), Int.valueOf(1).asFuture(), null)); } @CheckNoStats @@ -1225,9 +1242,9 @@ public void merge_remove(AsyncCache cache, CacheContext context) { .contains(removed).exclusively(); } + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches") public void merge_recursive(AsyncCache cache, CacheContext context) { var mappingFunction = new BiFunction, CompletableFuture, CompletableFuture>() { @@ -1241,9 +1258,9 @@ public void merge_recursive(AsyncCache cache, CacheContext context) { assertThat(value).isEqualTo(firstValue); } + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = StackOverflowError.class) public void merge_pingpong(AsyncCache cache, CacheContext context) { // As we cannot provide immediate checking without an expensive solution, e.g. ThreadLocal, // instead we assert that a stack overflow error will occur to inform the developer (vs @@ -1261,22 +1278,26 @@ public void merge_pingpong(AsyncCache cache, CacheContext context) { return cache.asMap().merge(context.lastKey(), lastValue, this); } }; - cache.asMap().merge(context.firstKey(), cache.asMap().get(context.firstKey()), mappingFunction); + assertThrows(StackOverflowError.class, () -> { + cache.asMap().merge(context.firstKey(), + cache.asMap().get(context.firstKey()), mappingFunction); + }); } @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }, removalListener = { Listener.DISABLED, Listener.REJECTING }) public void merge_error(AsyncCache cache, CacheContext context) { - try { - cache.asMap().merge(context.firstKey(), cache.asMap().get(context.firstKey()), - (oldValue, value) -> { throw new IllegalStateException(); }); - Assert.fail(); - } catch (IllegalStateException expected) {} + var key = context.firstKey(); + var future = key.asFuture(); + var expected = new IllegalStateException(); + var actual = assertThrows(IllegalStateException.class, () -> + cache.asMap().merge(key, future, (oldValue, value) -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); assertThat(cache).containsExactlyEntriesIn(context.original()); assertThat(context).stats().hits(0).misses(0).success(0).failures(0); - var result = cache.asMap().merge(context.firstKey(), cache.asMap().get(context.firstKey()), + var result = cache.asMap().merge(context.firstKey(), future, (oldValue, value) -> context.absentValue().asFuture()); assertThat(result).succeedsWith(context.absentValue()); } @@ -1449,10 +1470,10 @@ private static Map parseToString(Map /* ---------------- Key Set -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void keySet_toArray_null(AsyncCache cache, CacheContext context) { - cache.asMap().keySet().toArray((Int[]) null); + assertThrows(NullPointerException.class, () -> cache.asMap().keySet().toArray((Int[]) null)); } @CheckNoStats @@ -1494,9 +1515,10 @@ public void keySet_whenEmpty(AsyncCache cache, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void keySet_addNotSupported(AsyncCache cache, CacheContext context) { - cache.asMap().keySet().add(Int.valueOf(1)); + assertThrows(UnsupportedOperationException.class, () -> + cache.asMap().keySet().add(Int.valueOf(1))); } @CacheSpec @@ -1511,9 +1533,9 @@ public void keySet_clear(AsyncCache cache, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySet_removeAll_null(AsyncCache cache, CacheContext context) { - cache.asMap().keySet().removeAll(null); + assertThrows(NullPointerException.class, () -> cache.asMap().keySet().removeAll(null)); } @CacheSpec @@ -1605,9 +1627,9 @@ public void keySet_removeAll_bySet(AsyncCache cache, CacheContext cont @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySet_remove_null(AsyncCache cache, CacheContext context) { - cache.asMap().keySet().remove(null); + assertThrows(NullPointerException.class, () -> cache.asMap().keySet().remove(null)); } @CacheSpec @@ -1630,9 +1652,9 @@ public void keySet_remove(AsyncCache cache, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySet_removeIf_null(AsyncCache cache, CacheContext context) { - cache.asMap().keySet().removeIf(null); + assertThrows(NullPointerException.class, () -> cache.asMap().keySet().removeIf(null)); } @CacheSpec @@ -1676,9 +1698,9 @@ public void keySet_removeIf_all(AsyncCache cache, CacheContext context @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySet_retainAll_null(AsyncCache cache, CacheContext context) { - cache.asMap().keySet().retainAll(null); + assertThrows(NullPointerException.class, () -> cache.asMap().keySet().retainAll(null)); } @CacheSpec @@ -1780,27 +1802,28 @@ public void keySet_iterator(AsyncCache cache, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void keyIterator_noElement(AsyncCache cache, CacheContext context) { - cache.asMap().keySet().iterator().remove(); + assertThrows(IllegalStateException.class, () -> cache.asMap().keySet().iterator().remove()); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NoSuchElementException.class) public void keyIterator_noMoreElements(AsyncCache cache, CacheContext context) { - cache.asMap().keySet().iterator().next(); + assertThrows(NoSuchElementException.class, () -> cache.asMap().keySet().iterator().next()); } @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySpliterator_forEachRemaining_null( AsyncCache cache, CacheContext context) { - cache.asMap().keySet().spliterator().forEachRemaining(null); + assertThrows(NullPointerException.class, () -> + cache.asMap().keySet().spliterator().forEachRemaining(null)); } @CacheSpec @@ -1814,9 +1837,10 @@ public void keySpliterator_forEachRemaining(AsyncCache cache, CacheCon @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void keySpliterator_tryAdvance_null(AsyncCache cache, CacheContext context) { - cache.asMap().keySet().spliterator().tryAdvance(null); + assertThrows(NullPointerException.class, () -> + cache.asMap().keySet().spliterator().tryAdvance(null)); } @CacheSpec @@ -1856,10 +1880,11 @@ public void keySpliterator_estimateSize(AsyncCache cache, CacheContext /* ---------------- Values -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void values_toArray_null(AsyncCache cache, CacheContext context) { - cache.asMap().values().toArray((CompletableFuture[]) null); + assertThrows(NullPointerException.class, () -> + cache.asMap().values().toArray((CompletableFuture[]) null)); } @CheckNoStats @@ -1903,11 +1928,12 @@ public void values_empty(AsyncCache cache, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void values_addNotSupported(AsyncCache cache, CacheContext context) { - cache.asMap().values().add(Int.valueOf(1).asFuture()); + assertThrows(UnsupportedOperationException.class, () -> + cache.asMap().values().add(Int.valueOf(1).asFuture())); } @CacheSpec @@ -1922,9 +1948,9 @@ public void values_clear(AsyncCache cache, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void values_removeAll_null(AsyncCache cache, CacheContext context) { - cache.asMap().values().removeAll(null); + assertThrows(NullPointerException.class, () -> cache.asMap().values().removeAll(null)); } @CacheSpec @@ -2040,9 +2066,9 @@ public void values_remove_once(AsyncCache cache, CacheContext context) @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void values_removeIf_null(AsyncCache cache, CacheContext context) { - cache.asMap().values().removeIf(null); + assertThrows(NullPointerException.class, () -> cache.asMap().values().removeIf(null)); } @CacheSpec @@ -2100,9 +2126,9 @@ public void values_removeIf(AsyncCache cache, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void values_retainAll_null(AsyncCache cache, CacheContext context) { - cache.asMap().values().retainAll(null); + assertThrows(NullPointerException.class, () -> cache.asMap().values().retainAll(null)); } @CacheSpec @@ -2206,27 +2232,28 @@ public void valueIterator(AsyncCache cache, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void valueIterator_noElement(AsyncCache cache, CacheContext context) { - cache.asMap().values().iterator().remove(); + assertThrows(IllegalStateException.class, () -> cache.asMap().values().iterator().remove()); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NoSuchElementException.class) public void valueIterator_noMoreElements(AsyncCache cache, CacheContext context) { - cache.asMap().values().iterator().next(); + assertThrows(NoSuchElementException.class, () -> cache.asMap().values().iterator().next()); } @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void valueSpliterator_forEachRemaining_null( AsyncCache cache, CacheContext context) { - cache.asMap().values().spliterator().forEachRemaining(null); + assertThrows(NullPointerException.class, () -> + cache.asMap().values().spliterator().forEachRemaining(null)); } @CacheSpec @@ -2240,9 +2267,10 @@ public void valueSpliterator_forEachRemaining(AsyncCache cache, CacheC @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void valueSpliterator_tryAdvance_null(AsyncCache cache, CacheContext context) { - cache.asMap().values().spliterator().tryAdvance(null); + assertThrows(NullPointerException.class, () -> + cache.asMap().values().spliterator().tryAdvance(null)); } @CacheSpec @@ -2282,10 +2310,11 @@ public void valueSpliterator_estimateSize(AsyncCache cache, CacheConte /* ---------------- Entry Set -------------- */ @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void entrySet_toArray_null(AsyncCache cache, CacheContext context) { - cache.asMap().entrySet().toArray((Map.Entry[]) null); + assertThrows(NullPointerException.class, () -> + cache.asMap().entrySet().toArray((Map.Entry[]) null)); } @CheckNoStats @@ -2361,14 +2390,12 @@ public void entrySet_contains_present(AsyncCache cache, CacheContext c } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = Listener.DISABLED) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void entrySet_addIsNotSupported(AsyncCache cache, CacheContext context) { - try { - cache.asMap().entrySet().add(Map.entry(Int.valueOf(1), Int.valueOf(2).asFuture())); - } finally { - assertThat(cache).isEmpty(); - } + assertThrows(UnsupportedOperationException.class, () -> + cache.asMap().entrySet().add(Map.entry(Int.valueOf(1), Int.valueOf(2).asFuture()))); + assertThat(cache).isEmpty(); } @CacheSpec @@ -2383,9 +2410,9 @@ public void entrySet_clear(AsyncCache cache, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void entrySet_removeAll_null(AsyncCache cache, CacheContext context) { - cache.asMap().entrySet().removeAll(null); + assertThrows(NullPointerException.class, () -> cache.asMap().entrySet().removeAll(null)); } @CacheSpec @@ -2539,9 +2566,9 @@ public void entrySet_remove(AsyncCache cache, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void entrySet_removeIf_null(AsyncCache cache, CacheContext context) { - cache.asMap().entrySet().removeIf(null); + assertThrows(NullPointerException.class, () -> cache.asMap().entrySet().removeIf(null)); } @CacheSpec @@ -2601,9 +2628,9 @@ public void entrySet_removeIf(AsyncCache cache, CacheContext context) @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void entrySet_retainAll_null(AsyncCache cache, CacheContext context) { - cache.asMap().entrySet().retainAll(null); + assertThrows(NullPointerException.class, () -> cache.asMap().entrySet().retainAll(null)); } @CacheSpec @@ -2711,27 +2738,28 @@ public void entryIterator(AsyncCache cache, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void entryIterator_noElement(AsyncCache cache, CacheContext context) { - cache.asMap().entrySet().iterator().remove(); + assertThrows(IllegalStateException.class, () -> cache.asMap().entrySet().iterator().remove()); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NoSuchElementException.class) public void entryIterator_noMoreElements(AsyncCache cache, CacheContext context) { - cache.asMap().entrySet().iterator().next(); + assertThrows(NoSuchElementException.class, () -> cache.asMap().entrySet().iterator().next()); } @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void entrySpliterator_forEachRemaining_null( AsyncCache cache, CacheContext context) { - cache.asMap().entrySet().spliterator().forEachRemaining(null); + assertThrows(NullPointerException.class, () -> + cache.asMap().entrySet().spliterator().forEachRemaining(null)); } @CacheSpec @@ -2751,9 +2779,10 @@ public void entrySpliterator_forEachRemaining(AsyncCache cache, CacheC @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void entrySpliterator_tryAdvance_null(AsyncCache cache, CacheContext context) { - cache.asMap().entrySet().spliterator().tryAdvance(null); + assertThrows(NullPointerException.class, () -> + cache.asMap().entrySet().spliterator().tryAdvance(null)); } @CacheSpec @@ -2814,10 +2843,11 @@ public void writeThroughEntry(AsyncCache cache, CacheContext context) } @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL }) public void writeThroughEntry_null(AsyncCache cache, CacheContext context) { - cache.asMap().entrySet().iterator().next().setValue(null); + assertThrows(NullPointerException.class, () -> + cache.asMap().entrySet().iterator().next().setValue(null)); } // writeThroughEntry_serialize() - CompletableFuture is not serializable diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncCacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncCacheTest.java index 716ba10271..9f96b8f66e 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncCacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncCacheTest.java @@ -27,6 +27,7 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static java.util.function.Function.identity; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -46,7 +47,6 @@ import java.util.function.BiFunction; import java.util.function.Function; -import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -76,16 +76,14 @@ @CheckNoEvictions @CheckMaxLogLevel(WARN) @Listeners(CacheValidationListener.class) @Test(dataProviderClass = CacheProvider.class) -@SuppressWarnings("FutureReturnValueIgnored") public final class AsyncCacheTest { /* --------------- getIfPresent --------------- */ - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getIfPresent_nullKey(AsyncCache cache, CacheContext context) { - cache.getIfPresent(null); + assertThrows(NullPointerException.class, () -> cache.getIfPresent(null)); } @Test(dataProvider = "caches") @@ -108,24 +106,22 @@ public void getIfPresent_present(AsyncCache cache, CacheContext contex /* --------------- getFunc --------------- */ @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void getFunc_nullKey(AsyncCache cache, CacheContext context) { - cache.get(null, key -> null); + assertThrows(NullPointerException.class, () -> cache.get(null, key -> null)); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void getFunc_nullLoader(AsyncCache cache, CacheContext context) { - cache.get(context.absentKey(), (Function) null); + Function mappingFunction = null; + assertThrows(NullPointerException.class, () -> cache.get(context.absentKey(), mappingFunction)); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void getFunc_nullKeyAndLoader(AsyncCache cache, CacheContext context) { - cache.get(null, (Function) null); + assertThrows(NullPointerException.class, () -> cache.get(null, (Function) null)); } @CacheSpec @@ -149,13 +145,14 @@ public void getFunc_absent_null_async(AsyncCache cache, CacheContext c await().untilTrue(ready); return null; }); - valueFuture.whenComplete((r, e) -> done.set(true)); + var completed = valueFuture.whenComplete((r, e) -> done.set(true)); ready.set(true); await().untilTrue(done); await().untilAsserted(() -> assertThat(cache).doesNotContainKey(context.absentKey())); assertThat(context).stats().hits(0).misses(1).success(0).failures(1); + assertThat(completed).isDone(); assertThat(valueFuture).isDone(); assertThat(cache).doesNotContainKey(key); } @@ -178,12 +175,13 @@ public void getFunc_absent_failure_async(AsyncCache cache, CacheContex var valueFuture = cache.get(key, k -> { throw new IllegalStateException(); }); - valueFuture.whenComplete((r, e) -> done.set(true)); + var completed = valueFuture.whenComplete((r, e) -> done.set(true)); await().untilTrue(done); await().untilAsserted(() -> assertThat(cache).doesNotContainKey(key)); await().untilAsserted(() -> assertThat(cache).hasSize(context.initialSize())); + assertThat(completed).isDone(); assertThat(valueFuture).hasCompletedExceptionally(); assertThat(context).stats().hits(0).misses(1).success(0).failures(1); } @@ -196,12 +194,13 @@ public void getFunc_absent_cancelled(AsyncCache cache, CacheContext co await().until(done::get); return null; }); - valueFuture.whenComplete((r, e) -> done.set(true)); + var completed = valueFuture.whenComplete((r, e) -> done.set(true)); valueFuture.cancel(true); await().untilTrue(done); assertThat(context).stats().hits(0).misses(1).success(0).failures(1); + assertThat(completed).isDone(); assertThat(valueFuture).isDone(); await().untilAsserted(() -> assertThat(cache).doesNotContainKey(context.absentKey())); } @@ -231,57 +230,49 @@ public void getFunc_present(AsyncCache cache, CacheContext context) { /* --------------- getBiFunc --------------- */ @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void getBiFunc_nullKey(AsyncCache cache, CacheContext context) { - cache.get(null, (key, executor) -> CompletableFuture.completedFuture(null)); + assertThrows(NullPointerException.class, () -> + cache.get(null, (key, executor) -> CompletableFuture.completedFuture(null))); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void getBiFunc_nullLoader(AsyncCache cache, CacheContext context) { BiFunction> mappingFunction = null; - cache.get(context.absentKey(), mappingFunction); + assertThrows(NullPointerException.class, () -> cache.get(context.absentKey(), mappingFunction)); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void getBiFunc_nullKeyAndLoader(AsyncCache cache, CacheContext context) { BiFunction> mappingFunction = null; - cache.get(null, mappingFunction); + assertThrows(NullPointerException.class, () -> cache.get(null, mappingFunction)); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) + @Test(dataProvider = "caches") public void getBiFunc_throwsException(AsyncCache cache, CacheContext context) { - try { - cache.get(context.absentKey(), (key, executor) -> { throw new IllegalStateException(); }); - } finally { - assertThat(context).stats().hits(0).misses(1).success(0).failures(1); - assertThat(cache).doesNotContainKey(context.absentKey()); - } + assertThrows(IllegalStateException.class, () -> + cache.get(context.absentKey(), (key, executor) -> { throw new IllegalStateException(); })); + assertThat(context).stats().hits(0).misses(1).success(0).failures(1); + assertThat(cache).doesNotContainKey(context.absentKey()); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = UnknownError.class) + @Test(dataProvider = "caches") public void getBiFunc_throwsError(AsyncCache cache, CacheContext context) { - try { - cache.get(context.absentKey(), (key, executor) -> { throw new UnknownError(); }); - } finally { - assertThat(context).stats().hits(0).misses(1).success(0).failures(1); - assertThat(cache).doesNotContainKey(context.absentKey()); - } + assertThrows(UnknownError.class, () -> + cache.get(context.absentKey(), (key, executor) -> { throw new UnknownError(); })); + assertThat(context).stats().hits(0).misses(1).success(0).failures(1); + assertThat(cache).doesNotContainKey(context.absentKey()); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void getBiFunc_absent_null(AsyncCache cache, CacheContext context) { - cache.get(context.absentKey(), (k, executor) -> null); + assertThrows(NullPointerException.class, () -> + cache.get(context.absentKey(), (k, executor) -> null)); } @CacheSpec @@ -314,10 +305,9 @@ public void getBiFunc_absent_failure_after(AsyncCache cache, CacheCont @CacheSpec @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") public void getBiFunc_absent_cancelled(AsyncCache cache, CacheContext context) { - var cancelledFuture = new CompletableFuture(); - cache.get(context.absentKey(), (k, executor) -> cancelledFuture); + var cancelledFuture = cache.get(context.absentKey(), + (k, executor) -> new CompletableFuture<>()); cancelledFuture.cancel(true); assertThat(context).stats().hits(0).misses(1).success(0).failures(1); @@ -350,36 +340,37 @@ public void getBiFunc_present(AsyncCache cache, CacheContext context) /* --------------- getAllFunc --------------- */ @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllFunction_nullKeys(AsyncCache cache, CacheContext context) { - cache.getAll(null, keys -> { throw new AssertionError(); }); + assertThrows(NullPointerException.class, () -> + cache.getAll(null, keys -> { throw new AssertionError(); })); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllFunction_nullKeys_nullFunction( AsyncCache cache, CacheContext context) { - cache.getAll(null, (Function, Map>) null); + Function, Map> mappingFunction = null; + assertThrows(NullPointerException.class, () -> cache.getAll(null, mappingFunction)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllFunction_nullFunction(AsyncCache cache, CacheContext context) { - cache.getAll(context.original().keySet(), (Function, Map>) null); + Function, Map> mappingFunction = null; + assertThrows(NullPointerException.class, () -> + cache.getAll(context.original().keySet(), mappingFunction)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllFunction_nullKey(AsyncCache cache, CacheContext context) { - cache.getAll(Collections.singletonList(null), keys -> { throw new AssertionError(); }); + assertThrows(NullPointerException.class, () -> + cache.getAll(Collections.singletonList(null), keys -> { throw new AssertionError(); })); } @CheckNoStats @@ -412,11 +403,11 @@ public void getAllFunction_immutable_keys(AsyncCache cache, CacheConte } @CacheSpec - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void getAllFunction_immutable_result(AsyncCache cache, CacheContext context) { var result = cache.getAll(context.firstMiddleLastKeys(), keys -> keys.stream().collect(toImmutableMap(identity(), identity()))).join(); - result.clear(); + assertThrows(UnsupportedOperationException.class, result::clear); } @CacheSpec @@ -579,39 +570,38 @@ public void getAllFunction_badLoader(AsyncCache cache, CacheContext co /* --------------- getAllBiFunc --------------- */ @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllBifunction_nullKeys(AsyncCache cache, CacheContext context) { - cache.getAll(null, (keys, executor) -> { throw new AssertionError(); }); + assertThrows(NullPointerException.class, () -> + cache.getAll(null, (keys, executor) -> { throw new AssertionError(); })); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllBifunction_nullKeys_nullBifunction( AsyncCache cache, CacheContext context) { BiFunction, Executor, CompletableFuture>> f = null; - cache.getAll(null, f); + assertThrows(NullPointerException.class, () -> cache.getAll(null, f)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllBifunction_nullBifunction(AsyncCache cache, CacheContext context) { BiFunction, Executor, CompletableFuture>> f = null; - cache.getAll(context.original().keySet(), f); + assertThrows(NullPointerException.class, () -> cache.getAll(context.original().keySet(), f)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllBifunction_nullKey(AsyncCache cache, CacheContext context) { - cache.getAll(Collections.singletonList(null), - (keys, executor) -> { throw new AssertionError(); }); + assertThrows(NullPointerException.class, () -> { + cache.getAll(Collections.singletonList(null), + (keys, executor) -> { throw new AssertionError(); }); + }); } @CheckNoStats @@ -634,23 +624,23 @@ public void getAllBiFunction_nullLookup(AsyncCache cache, CacheContext } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void getAllBifunction_immutable_keys(AsyncCache cache, CacheContext context) { - cache.getAll(context.absentKeys(), (keys, executor) -> { - keys.clear(); - return CompletableFuture.completedFuture(Map.of()); + assertThrows(UnsupportedOperationException.class, () -> { + cache.getAll(context.absentKeys(), (keys, executor) -> { + throw assertThrows(UnsupportedOperationException.class, keys::clear); + }); }); } @CacheSpec - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void getAllBifunction_immutable_result(AsyncCache cache, CacheContext context) { var result = cache.getAll(context.firstMiddleLastKeys(), (keys, executor) -> { return CompletableFuture.completedFuture( keys.stream().collect(toImmutableMap(identity(), identity()))); }).join(); - result.clear(); + assertThrows(UnsupportedOperationException.class, result::clear); } @CacheSpec @@ -662,10 +652,10 @@ public void getAllBifunction_absent_null(AsyncCache cache, CacheContex } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void getAllBifunction_absent_nullValue(AsyncCache cache, CacheContext context) { - cache.getAll(context.absentKeys(), (keys, executor) -> null); + assertThrows(NullPointerException.class, () -> + cache.getAll(context.absentKeys(), (keys, executor) -> null)); } @CacheSpec @@ -679,32 +669,28 @@ public void getAllBifunction_absent_failure(AsyncCache cache, CacheCon } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) + @Test(dataProvider = "caches") public void getAllBifunction_absent_throwsException( AsyncCache cache, CacheContext context) { - try { + assertThrows(IllegalStateException.class, () -> { cache.getAll(context.absentKeys(), (keys, executor) -> { throw new IllegalStateException(); }); - } finally { - int misses = context.absentKeys().size(); - assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); - assertThat(cache).doesNotContainKey(context.absentKey()); - } + }); + + int misses = context.absentKeys().size(); + assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); + assertThat(cache).doesNotContainKey(context.absentKey()); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = UnknownError.class) + @Test(dataProvider = "caches") public void getAllBifunction_absent_throwsError( AsyncCache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys(), (keys, executor) -> { throw new UnknownError(); }); - } finally { - int misses = context.absentKeys().size(); - assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); - assertThat(cache).doesNotContainKey(context.absentKey()); - } + assertThrows(UnknownError.class, () -> + cache.getAll(context.absentKeys(), (keys, executor) -> { throw new UnknownError(); })); + int misses = context.absentKeys().size(); + assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); + assertThat(cache).doesNotContainKey(context.absentKey()); } @Test(dataProvider = "caches") @@ -852,16 +838,11 @@ public void getAllBifunction_present_ordered_exceeds( } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAllBifunction_badLoader(AsyncCache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys(), (keysToLoad, executor) -> - { throw new LoadAllException(); }); - Assert.fail(); - } catch (LoadAllException e) { - assertThat(cache).hasSize(context.initialSize()); - } + assertThrows(LoadAllException.class, () -> + cache.getAll(context.absentKeys(), (keys, executor) -> { throw new LoadAllException(); })); + assertThat(cache).hasSize(context.initialSize()); } @Test(dataProvider = "caches") @@ -905,23 +886,23 @@ public void getAllBifunction_early_failure(AsyncCache cache, CacheCont /* --------------- put --------------- */ + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullKey(AsyncCache cache, CacheContext context) { var value = context.absentValue().asFuture(); - cache.put(null, value); + assertThrows(NullPointerException.class, () -> cache.put(null, value)); } + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullValue(AsyncCache cache, CacheContext context) { - cache.put(context.absentKey(), null); + assertThrows(NullPointerException.class, () -> cache.put(context.absentKey(), null)); } + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullKeyAndValue(AsyncCache cache, CacheContext context) { - cache.put(null, null); + assertThrows(NullPointerException.class, () -> cache.put(null, null)); } @Test(dataProvider = "caches") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncLoadingCacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncLoadingCacheTest.java index 726b9530e0..dcdcff455a 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncLoadingCacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/AsyncLoadingCacheTest.java @@ -26,6 +26,7 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static java.util.function.Function.identity; +import static org.junit.jupiter.api.Assertions.assertThrows; import static uk.org.lidalia.slf4jext.Level.WARN; import java.util.ArrayList; @@ -43,7 +44,6 @@ import java.util.function.BiFunction; import java.util.function.Function; -import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -75,16 +75,14 @@ @CheckNoEvictions @CheckMaxLogLevel(WARN) @Listeners(CacheValidationListener.class) @Test(dataProviderClass = CacheProvider.class) -@SuppressWarnings({"FutureReturnValueIgnored", "PreferJavaTimeOverload"}) public final class AsyncLoadingCacheTest { /* --------------- get --------------- */ @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void get_null(AsyncLoadingCache cache, CacheContext context) { - cache.get(null); + assertThrows(NullPointerException.class, () -> cache.get(null)); } @CacheSpec @@ -119,38 +117,28 @@ public void get_absent_failure_async(AsyncLoadingCache cache, CacheCon @Test(dataProvider = "caches") @CacheSpec(loader = Loader.ASYNC_EXCEPTIONAL) public void get_absent_throwsException(AsyncLoadingCache cache, CacheContext context) { - try { - cache.get(context.absentKey()).join(); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(context).stats().hits(0).misses(1).success(0).failures(1); - } + assertThrows(IllegalStateException.class, () -> cache.get(context.absentKey())); + assertThat(context).stats().hits(0).misses(1).success(0).failures(1); } @Test(dataProvider = "caches") @CacheSpec(loader = Loader.ASYNC_CHECKED_EXCEPTIONAL) public void get_absent_throwsCheckedException( AsyncLoadingCache cache, CacheContext context) { - try { - cache.get(context.absentKey()).join(); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); - assertThat(context).stats().hits(0).misses(1).success(0).failures(1); - } + var e = assertThrows(CompletionException.class, () -> cache.get(context.absentKey())); + + assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); + assertThat(context).stats().hits(0).misses(1).success(0).failures(1); } @Test(dataProvider = "caches") @CacheSpec(loader = Loader.ASYNC_INTERRUPTED) public void get_absent_interrupted(AsyncLoadingCache cache, CacheContext context) { - try { - cache.get(context.absentKey()).join(); - Assert.fail(); - } catch (CompletionException e) { - assertThat(Thread.interrupted()).isTrue(); - assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); - assertThat(context).stats().hits(0).misses(1).success(0).failures(1); - } + var e = assertThrows(CompletionException.class, () -> cache.get(context.absentKey())); + + assertThat(Thread.interrupted()).isTrue(); + assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); + assertThat(context).stats().hits(0).misses(1).success(0).failures(1); } @Test(dataProvider = "caches") @@ -165,20 +153,19 @@ public void get_present(AsyncLoadingCache cache, CacheContext context) /* --------------- getAll --------------- */ @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_null(AsyncLoadingCache cache, CacheContext context) { - cache.getAll(null); + assertThrows(NullPointerException.class, () -> cache.getAll(null)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(loader = { Loader.NEGATIVE, Loader.BULK_NEGATIVE }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_nullKey(AsyncLoadingCache cache, CacheContext context) { - cache.getAll(Collections.singletonList(null)); + List keys = Collections.singletonList(null); + assertThrows(NullPointerException.class, () -> cache.getAll(keys)); } @CheckNoStats @@ -198,18 +185,18 @@ public void getAll_immutable_keys_loader( .hasCauseThat().isInstanceOf(UnsupportedOperationException.class); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(loader = Loader.ASYNC_BULK_MODIFY_KEYS) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void getAll_immutable_keys_asyncLoader( AsyncLoadingCache cache, CacheContext context) { - cache.getAll(context.absentKeys()); + assertThrows(UnsupportedOperationException.class, () -> cache.getAll(context.absentKeys())); } @CacheSpec - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void getAll_immutable_result(AsyncLoadingCache cache, CacheContext context) { - cache.getAll(context.firstMiddleLastKeys()).join().clear(); + var results = cache.getAll(context.firstMiddleLastKeys()).join(); + assertThrows(UnsupportedOperationException.class, results::clear); } @CacheSpec @@ -241,42 +228,31 @@ public void getAll_absent_failure(AsyncLoadingCache cache, CacheContex @CacheSpec(loader = { Loader.ASYNC_EXCEPTIONAL, Loader.ASYNC_BULK_EXCEPTIONAL }) public void getAll_absent_throwsException( AsyncLoadingCache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys()).join(); - Assert.fail(); - } catch (IllegalStateException e) { - int misses = context.loader().isBulk() ? context.absentKeys().size() : 1; - assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); - } + assertThrows(IllegalStateException.class, () -> cache.getAll(context.absentKeys())); + int misses = context.loader().isBulk() ? context.absentKeys().size() : 1; + assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); } @Test(dataProvider = "caches") @CacheSpec(loader = { Loader.ASYNC_CHECKED_EXCEPTIONAL, Loader.ASYNC_BULK_CHECKED_EXCEPTIONAL }) public void getAll_absent_throwsCheckedException( AsyncLoadingCache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys()).join(); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); - int misses = context.loader().isBulk() ? context.absentKeys().size() : 1; - assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); - } + var e = assertThrows(CompletionException.class, () -> cache.getAll(context.absentKeys())); + + assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); + int misses = context.loader().isBulk() ? context.absentKeys().size() : 1; + assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = { Loader.ASYNC_INTERRUPTED, Loader.ASYNC_BULK_INTERRUPTED }) public void getAll_absent_interrupted(AsyncLoadingCache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys()); - Assert.fail(); - } catch (CompletionException e) { - assertThat(Thread.interrupted()).isTrue(); - assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); - int misses = context.loader().isBulk() ? context.absentKeys().size() : 1; - assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); - } + var e = assertThrows(CompletionException.class, () -> cache.getAll(context.absentKeys())); + + assertThat(Thread.interrupted()).isTrue(); + assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); + int misses = context.loader().isBulk() ? context.absentKeys().size() : 1; + assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); } @Test(dataProvider = "caches") @@ -399,7 +375,6 @@ public void getAll_present_ordered_exceeds( } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(compute = Compute.ASYNC, removalListener = { Listener.DISABLED, Listener.REJECTING }) public void getAll_badLoader(CacheContext context) { var loader = new AsyncCacheLoader() { @@ -413,12 +388,8 @@ public void getAll_badLoader(CacheContext context) { }; var cache = context.buildAsync(loader); - try { - cache.getAll(context.absentKeys()); - Assert.fail(); - } catch (LoadAllException e) { - assertThat(cache).isEmpty(); - } + assertThrows(LoadAllException.class, () -> cache.getAll(context.absentKeys())); + assertThat(cache).isEmpty(); } @SuppressWarnings("serial") @@ -467,14 +438,15 @@ public void refresh(CacheContext context) { await().untilAsserted(() -> assertThat(cache).containsEntry(key, key.negate())); } - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, compute = Compute.ASYNC) public void refresh_nullFuture_load(CacheContext context) { var cache = context.buildAsync((Int key, Executor executor) -> null); - cache.synchronous().refresh(context.absentKey()); + assertThrows(NullPointerException.class, () -> + cache.synchronous().refresh(context.absentKey())); } - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, compute = Compute.ASYNC) public void refresh_nullFuture_reload(CacheContext context) { var cache = context.buildAsync(new AsyncCacheLoader() { @@ -487,7 +459,8 @@ public void refresh_nullFuture_reload(CacheContext context) { } }); cache.synchronous().put(context.absentKey(), context.absentValue()); - cache.synchronous().refresh(context.absentKey()); + assertThrows(NullPointerException.class, () -> + cache.synchronous().refresh(context.absentKey())); } @Test(dataProvider = "caches", timeOut = 5_000) // Issue #69 @@ -507,46 +480,35 @@ public void refresh_deadlock(CacheContext context) { @Test(dataProvider = "caches") @CacheSpec(loader = Loader.REFRESH_EXCEPTIONAL) public void refresh_throwsException(AsyncLoadingCache cache, CacheContext context) { - try { - var key = context.original().isEmpty() ? context.absentKey() : context.firstKey(); - cache.synchronous().refresh(key); - Assert.fail(); - } catch (IllegalStateException e) { - int failures = context.isGuava() ? 1 : 0; - assertThat(context).stats().hits(0).misses(0).success(0).failures(failures); - } + var key = context.original().isEmpty() ? context.absentKey() : context.firstKey(); + assertThrows(IllegalStateException.class, () -> cache.synchronous().refresh(key)); + + int failures = context.isGuava() ? 1 : 0; + assertThat(context).stats().hits(0).misses(0).success(0).failures(failures); } @Test(dataProvider = "caches") @CacheSpec(loader = Loader.REFRESH_CHECKED_EXCEPTIONAL) public void refresh_throwsCheckedException( AsyncLoadingCache cache, CacheContext context) { - try { - var key = context.original().isEmpty() ? context.absentKey() : context.firstKey(); - cache.synchronous().refresh(key); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); + var key = context.original().isEmpty() ? context.absentKey() : context.firstKey(); + var e = assertThrows(CompletionException.class, () -> cache.synchronous().refresh(key)); + assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); - int failures = context.isGuava() ? 1 : 0; - assertThat(context).stats().hits(0).misses(0).success(0).failures(failures); - } + int failures = context.isGuava() ? 1 : 0; + assertThat(context).stats().hits(0).misses(0).success(0).failures(failures); } @Test(dataProvider = "caches") @CacheSpec(loader = Loader.REFRESH_INTERRUPTED) public void refresh_interrupted(AsyncLoadingCache cache, CacheContext context) { - try { - var key = context.original().isEmpty() ? context.absentKey() : context.firstKey(); - cache.synchronous().refresh(key); - Assert.fail(); - } catch (CompletionException e) { - assertThat(Thread.interrupted()).isTrue(); - assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); + var key = context.original().isEmpty() ? context.absentKey() : context.firstKey(); + var e = assertThrows(CompletionException.class, () -> cache.synchronous().refresh(key)); + assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); + assertThat(Thread.interrupted()).isTrue(); - int failures = context.isGuava() ? 1 : 0; - assertThat(context).stats().hits(0).misses(0).success(0).failures(failures); - } + int failures = context.isGuava() ? 1 : 0; + assertThat(context).stats().hits(0).misses(0).success(0).failures(failures); } @CacheSpec @@ -611,11 +573,11 @@ public void refresh_current_removed(CacheContext context) { /* --------------- AsyncCacheLoader --------------- */ - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = UnsupportedOperationException.class) - public void asyncLoadAll() throws Exception { + @Test + public void asyncLoadAll() { AsyncCacheLoader loader = (key, executor) -> key.negate().asFuture(); - loader.asyncLoadAll(Set.of(), Runnable::run); + assertThrows(UnsupportedOperationException.class, () -> + loader.asyncLoadAll(Set.of(), Runnable::run)); } @Test @@ -625,11 +587,10 @@ public void asyncReload() throws Exception { assertThat(future).succeedsWith(-1); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = NullPointerException.class) + @Test public void bulk_function_null() { Function, Map> f = null; - AsyncCacheLoader.bulk(f); + assertThrows(NullPointerException.class, () -> AsyncCacheLoader.bulk(f)); } @Test @@ -649,11 +610,10 @@ public void bulk_function_present() throws Exception { assertThat(loader.asyncLoad(Int.valueOf(1), Runnable::run)).succeedsWith(1); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = NullPointerException.class) + @Test public void bulk_bifunction_null() { BiFunction, Executor, CompletableFuture>> f = null; - AsyncCacheLoader.bulk(f); + assertThrows(NullPointerException.class, () -> AsyncCacheLoader.bulk(f)); } @Test diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedBufferTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedBufferTest.java index d0f1ed5ad2..95ac10a7e1 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedBufferTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedBufferTest.java @@ -39,11 +39,10 @@ public Object[][] buffer() { } @Test(dataProvider = "buffer") - @SuppressWarnings("CheckReturnValue") public void offer(BoundedBuffer buffer) { ConcurrentTestHarness.timeTasks(10, () -> { for (int i = 0; i < 100; i++) { - buffer.offer(Boolean.TRUE); + assertThat(buffer.offer(Boolean.TRUE)).isAnyOf(Buffer.SUCCESS, Buffer.FULL, Buffer.FAILED); } }); assertThat(buffer.writes()).isGreaterThan(0); @@ -51,10 +50,9 @@ public void offer(BoundedBuffer buffer) { } @Test(dataProvider = "buffer") - @SuppressWarnings("CheckReturnValue") public void drain(BoundedBuffer buffer) { for (int i = 0; i < BoundedBuffer.BUFFER_SIZE; i++) { - buffer.offer(Boolean.TRUE); + assertThat(buffer.offer(Boolean.TRUE)).isAnyOf(Buffer.SUCCESS, Buffer.FULL); } long[] read = new long[1]; buffer.drainTo(e -> read[0]++); @@ -83,13 +81,12 @@ public void offerAndDrain(BoundedBuffer buffer) { } @Test - @SuppressWarnings("CheckReturnValue") public void overflow() { var buffer = new BoundedBuffer.RingBuffer(null); buffer.writeCounter = Long.MAX_VALUE; buffer.readCounter = Long.MAX_VALUE; - buffer.offer(Boolean.TRUE); + assertThat(buffer.offer(Boolean.TRUE)).isEqualTo(Buffer.SUCCESS); var data = new ArrayList<>(); buffer.drainTo(data::add); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedLocalCacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedLocalCacheTest.java index 1f1ae910d6..733d14dc45 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedLocalCacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/BoundedLocalCacheTest.java @@ -50,8 +50,10 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.doReturn; @@ -66,6 +68,7 @@ import static uk.org.lidalia.slf4jext.Level.WARN; import java.lang.ref.Reference; +import java.lang.ref.WeakReference; import java.time.Duration; import java.util.AbstractMap.SimpleEntry; import java.util.Arrays; @@ -83,12 +86,12 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.stream.IntStream; import org.apache.commons.lang3.mutable.MutableInt; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -146,12 +149,12 @@ public final class BoundedLocalCacheTest { @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, removalListener = Listener.MOCKITO) public void clear_pendingWrites(BoundedLocalCache cache, CacheContext context) { - var populate = new boolean[] { true }; + var populated = new boolean[1]; Answer fillWriteBuffer = invocation -> { - while (populate[0] && cache.writeBuffer.offer(() -> {})) { + while (!populated[0] && cache.writeBuffer.offer(() -> {})) { // ignored } - populate[0] = false; + populated[0] = true; return null; }; doAnswer(fillWriteBuffer) @@ -159,6 +162,7 @@ public void clear_pendingWrites(BoundedLocalCache cache, CacheContext .onRemoval(any(), any(), any()); cache.clear(); + assertThat(populated[0]).isTrue(); assertThat(cache).isExhaustivelyEmpty(); assertThat(cache.writeBuffer).isEmpty(); } @@ -167,14 +171,14 @@ public void clear_pendingWrites(BoundedLocalCache cache, CacheContext @CacheSpec(implementation = Implementation.Caffeine, loader = Loader.IDENTITY, population = Population.FULL, removalListener = Listener.MOCKITO) public void clear_pendingWrites_reload(BoundedLocalCache cache, CacheContext context) { - var populate = new boolean[] { true }; + var populated = new boolean[1]; Answer fillWriteBuffer = invocation -> { - while (populate[0] && cache.writeBuffer.offer(() -> {})) { + while (!populated[0] && cache.writeBuffer.offer(() -> {})) { // ignored } var loadingCache = (LoadingCache) context.cache(); loadingCache.refresh(invocation.getArgument(0)); - populate[0] = false; + populated[0] = true; return null; }; doAnswer(fillWriteBuffer) @@ -182,10 +186,45 @@ public void clear_pendingWrites_reload(BoundedLocalCache cache, CacheC .onRemoval(any(), any(), any()); cache.clear(); + assertThat(populated[0]).isTrue(); assertThat(cache.writeBuffer).isEmpty(); assertThat(cache).hasSize(context.initialSize()); } + @Test(dataProvider = "caches", groups = "slow") + @CacheSpec(implementation = Implementation.Caffeine, loader = Loader.IDENTITY, + population = Population.FULL, keys = ReferenceType.WEAK, removalListener = Listener.MOCKITO) + public void clear_pendingWrites_weakKeys( + BoundedLocalCache cache, CacheContext context) { + var collected = new boolean[1]; + var populated = new boolean[1]; + Answer fillWriteBuffer = invocation -> { + while (!populated[0] && cache.writeBuffer.offer(() -> {})) { + // ignored + } + populated[0] = true; + + if (!collected[0]) { + context.clear(); + for (var keyRef : cache.data.keySet()) { + var ref = (WeakReference) keyRef; + ref.enqueue(); + } + GcFinalization.awaitFullGc(); + collected[0] = (invocation.getArgument(2, RemovalCause.class) == COLLECTED); + } + return null; + }; + doAnswer(fillWriteBuffer) + .when(context.removalListener()) + .onRemoval(any(), any(), any()); + + cache.clear(); + assertThat(populated[0]).isTrue(); + assertThat(collected[0]).isTrue(); + assertThat(cache.writeBuffer).isEmpty(); + } + /* --------------- Maintenance --------------- */ @Test @@ -246,19 +285,17 @@ public void scheduleAfterWrite() { }); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void scheduleAfterWrite_invalidDrainStatus() { var cache = new BoundedLocalCache( Caffeine.newBuilder(), /* loader */ null, /* async */ false) {}; var valid = Set.of(IDLE, REQUIRED, PROCESSING_TO_IDLE, PROCESSING_TO_REQUIRED); - for (;;) { - int state = ThreadLocalRandom.current().nextInt(); - if (!valid.contains(state)) { - cache.drainStatus = state; - cache.scheduleAfterWrite(); - Assert.fail("Should not be valid: " + state); - } - } + var invalid = IntStream.generate(ThreadLocalRandom.current()::nextInt).boxed() + .filter(Predicate.not(valid::contains)) + .findFirst().orElseThrow(); + + cache.drainStatus = invalid; + assertThrows(IllegalStateException.class, cache::scheduleAfterWrite); } @Test @@ -325,20 +362,17 @@ public void scheduleDrainBuffers_rejected( assertThat(cache.evictionLock.isLocked()).isFalse(); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void shouldDrainBuffers_invalidDrainStatus() { var cache = new BoundedLocalCache( Caffeine.newBuilder(), /* loader */ null, /* async */ false) {}; var valid = Set.of(IDLE, REQUIRED, PROCESSING_TO_IDLE, PROCESSING_TO_REQUIRED); - for (;;) { - int state = ThreadLocalRandom.current().nextInt(); - if (!valid.contains(state)) { - cache.drainStatus = state; - cache.shouldDrainBuffers(true); - Assert.fail("Should not be valid: " + state); - } - } + var invalid = IntStream.generate(ThreadLocalRandom.current()::nextInt).boxed() + .filter(Predicate.not(valid::contains)) + .findFirst().orElseThrow(); + + cache.drainStatus = invalid; + assertThrows(IllegalStateException.class, () -> cache.shouldDrainBuffers(true)); } @Test(dataProvider = "caches") @@ -2414,80 +2448,77 @@ private static void testForBrokenEquality(BoundedLocalCache cac cache.clear(); key.decrement(); - try { - task.accept(key); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessageThat().contains("An invalid state was detected"); - } finally { - cache.data.clear(); - } + var e = assertThrows(IllegalStateException.class, () -> task.accept(key)); + assertThat(e).hasMessageThat().contains("An invalid state was detected"); + cache.data.clear(); } /* --------------- Miscellaneous --------------- */ @Test - @SuppressWarnings("CheckReturnValue") public void cacheFactory_invalid() { - try { + assertThrows(NullPointerException.class, () -> { LocalCacheFactory.loadFactory(/* builder */ null, /* loader */ null, /* async */ false, /* className */ null); - Assert.fail(); - } catch (NullPointerException expected) {} - try { + }); + + var expected = assertThrows(IllegalStateException.class, () -> { LocalCacheFactory.loadFactory(/* builder */ null, /* loader */ null, /* async */ false, /* className */ ""); - Assert.fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasCauseThat().isInstanceOf(ClassNotFoundException.class); - } + }); + assertThat(expected).hasCauseThat().isInstanceOf(ClassNotFoundException.class); } @Test - @SuppressWarnings("CheckReturnValue") public void nodeFactory_invalid() { - try { - NodeFactory.loadFactory(/* className */ null); - Assert.fail(); - } catch (NullPointerException expected) {} - try { - NodeFactory.loadFactory(/* className */ ""); - Assert.fail(); - } catch (IllegalStateException expected) { - assertThat(expected).hasCauseThat().isInstanceOf(ClassNotFoundException.class); - } + assertThrows(NullPointerException.class, () -> NodeFactory.loadFactory(/* className */ null)); + + var expected = assertThrows(IllegalStateException.class, () -> + NodeFactory.loadFactory(/* className */ "")); + assertThat(expected).hasCauseThat().isInstanceOf(ClassNotFoundException.class); } @Test - @SuppressWarnings("CheckReturnValue") - public void unsupported() { - var cache = Mockito.mock(BoundedLocalCache.class, InvocationOnMock::callRealMethod); - @SuppressWarnings("MethodReferenceUsage") - List methods = List.of( - () -> cache.accessOrderWindowDeque(), () -> cache.accessOrderProbationDeque(), - () -> cache.accessOrderProtectedDeque(), () -> cache.writeOrderDeque(), - () -> cache.expiresAfterAccessNanos(), () -> cache.setExpiresAfterAccessNanos(1L), - () -> cache.expiresAfterWriteNanos(), () -> cache.setExpiresAfterWriteNanos(1L), - () -> cache.refreshAfterWriteNanos(), () -> cache.setRefreshAfterWriteNanos(1L), - () -> cache.timerWheel(), () -> cache.frequencySketch(), - () -> cache.maximum(), () -> cache.windowMaximum(), - () -> cache.mainProtectedMaximum(), () -> cache.setMaximum(1L), - () -> cache.setWindowMaximum(1L), () -> cache.setMainProtectedMaximum(1L), - () -> cache.weightedSize(), () -> cache.windowWeightedSize(), - () -> cache.mainProtectedWeightedSize(), () -> cache.setWeightedSize(1L), - () -> cache.setWindowWeightedSize(0), () -> cache.setMainProtectedWeightedSize(1L), - () -> cache.hitsInSample(), () -> cache.missesInSample(), - () -> cache.sampleCount(), () -> cache.stepSize(), - () -> cache.previousSampleHitRate(), () -> cache.adjustment(), - () -> cache.setHitsInSample(1), () -> cache.setMissesInSample(1), - () -> cache.setSampleCount(1), () -> cache.setStepSize(1.0), - () -> cache.setPreviousSampleHitRate(1.0), () -> cache.setAdjustment(1L)); - for (var method : methods) { - try { - method.run(); - Assert.fail(); - } catch (UnsupportedOperationException expected) {} - } + public void cache_unsupported() { + BoundedLocalCache cache = Mockito.mock(CALLS_REAL_METHODS); + var type = UnsupportedOperationException.class; + + assertThrows(type, cache::accessOrderWindowDeque); + assertThrows(type, cache::accessOrderProbationDeque); + assertThrows(type, cache::accessOrderProtectedDeque); + assertThrows(type, cache::writeOrderDeque); + assertThrows(type, cache::expiresAfterAccessNanos); + assertThrows(type, () -> cache.setExpiresAfterAccessNanos(1L)); + assertThrows(type, cache::expiresAfterWriteNanos); + assertThrows(type, () -> cache.setExpiresAfterWriteNanos(1L)); + assertThrows(type, cache::refreshAfterWriteNanos); + assertThrows(type, () -> cache.setRefreshAfterWriteNanos(1L)); + assertThrows(type, cache::timerWheel); + assertThrows(type, cache::frequencySketch); + assertThrows(type, cache::maximum); + assertThrows(type, cache::windowMaximum); + assertThrows(type, cache::mainProtectedMaximum); + assertThrows(type, () -> cache.setMaximum(1L)); + assertThrows(type, () -> cache.setWindowMaximum(1L)); + assertThrows(type, () -> cache.setMainProtectedMaximum(1L)); + assertThrows(type, cache::weightedSize); + assertThrows(type, cache::windowWeightedSize); + assertThrows(type, cache::mainProtectedWeightedSize); + assertThrows(type, () -> cache.setWeightedSize(1L)); + assertThrows(type, () -> cache.setWindowWeightedSize(0)); + assertThrows(type, () -> cache.setMainProtectedWeightedSize(1L)); + assertThrows(type, cache::hitsInSample); + assertThrows(type, cache::missesInSample); + assertThrows(type, cache::sampleCount); + assertThrows(type, cache::stepSize); + assertThrows(type, cache::previousSampleHitRate); + assertThrows(type, cache::adjustment); + assertThrows(type, () -> cache.setHitsInSample(1)); + assertThrows(type, () -> cache.setMissesInSample(1)); + assertThrows(type, () -> cache.setSampleCount(1)); + assertThrows(type, () -> cache.setStepSize(1.0)); + assertThrows(type, () -> cache.setPreviousSampleHitRate(1.0)); + assertThrows(type, () -> cache.setAdjustment(1L)); } @Test @@ -2516,55 +2547,49 @@ public void node_string(BoundedLocalCache cache, CacheContext context) } @Test - @SuppressWarnings("CheckReturnValue") public void node_unsupported() { - @SuppressWarnings("unchecked") - Node node = Mockito.mock(Node.class, InvocationOnMock::callRealMethod); - @SuppressWarnings("MethodReferenceUsage") - List methods = List.of( - () -> node.getPreviousInVariableOrder(), () -> node.getNextInVariableOrder(), - () -> node.setPreviousInVariableOrder(node),() -> node.setNextInVariableOrder(node), - () -> node.setPreviousInAccessOrder(node), () -> node.setNextInAccessOrder(node), - () -> node.setPreviousInWriteOrder(node), () -> node.setNextInWriteOrder(node), - () -> node.casVariableTime(1L, 2L), () -> node.casWriteTime(1L, 2L), - () -> node.setQueueType(WINDOW)); - for (var method : methods) { - try { - method.run(); - Assert.fail(); - } catch (UnsupportedOperationException expected) {} - } + Node node = Mockito.mock(CALLS_REAL_METHODS); + var type = UnsupportedOperationException.class; + + assertThrows(type, node::getPreviousInVariableOrder); + assertThrows(type, node::getNextInVariableOrder); + assertThrows(type, () -> node.setPreviousInVariableOrder(node)); + assertThrows(type, () -> node.setNextInVariableOrder(node)); + assertThrows(type, () -> node.setPreviousInAccessOrder(node)); + assertThrows(type, () -> node.setNextInAccessOrder(node)); + assertThrows(type, () -> node.setPreviousInWriteOrder(node)); + assertThrows(type, () -> node.setNextInWriteOrder(node)); + assertThrows(type, () -> node.casVariableTime(1L, 2L)); + assertThrows(type, () -> node.casWriteTime(1L, 2L)); + assertThrows(type, () -> node.setQueueType(WINDOW)); } @Test public void node_ignored() { - var node = Mockito.mock(Node.class, InvocationOnMock::callRealMethod); - List methods = List.of(() -> node.setVariableTime(1L), - () -> node.setAccessTime(1L), () -> node.setWriteTime(1L)); - for (var method : methods) { - method.run(); - } + Node node = Mockito.mock(CALLS_REAL_METHODS); + node.setVariableTime(1L); + node.setAccessTime(1L); + node.setWriteTime(1L); } @Test - @SuppressWarnings({"CheckReturnValue", "unchecked"}) public void policy_unsupported() { - Policy policy = Mockito.mock(Policy.class, InvocationOnMock::callRealMethod); - var eviction = Mockito.mock(Eviction.class, InvocationOnMock::callRealMethod); - var fixedExpiration = Mockito.mock(FixedExpiration.class, InvocationOnMock::callRealMethod); - var varExpiration = Mockito.mock(VarExpiration.class, InvocationOnMock::callRealMethod); - List methods = List.of(() -> policy.getEntryIfPresentQuietly(new Object()), - () -> eviction.coldestWeighted(1L), () -> eviction.coldest(identity()), - () -> eviction.hottestWeighted(1L), () -> eviction.hottest(identity()), - () -> fixedExpiration.oldest(identity()), () -> fixedExpiration.youngest(identity()), - () -> varExpiration.compute(new Object(), (k, v) -> v, Duration.ZERO), - () -> varExpiration.oldest(identity()), () -> varExpiration.youngest(identity())); - for (var method : methods) { - try { - method.run(); - Assert.fail(); - } catch (UnsupportedOperationException expected) {} - } + Policy policy = Mockito.mock(CALLS_REAL_METHODS); + Eviction eviction = Mockito.mock(CALLS_REAL_METHODS); + VarExpiration varExpiration = Mockito.mock(CALLS_REAL_METHODS); + FixedExpiration fixedExpiration = Mockito.mock(CALLS_REAL_METHODS); + + var type = UnsupportedOperationException.class; + assertThrows(type, () -> policy.getEntryIfPresentQuietly(Int.MAX_VALUE)); + assertThrows(type, () -> eviction.coldestWeighted(1L)); + assertThrows(type, () -> eviction.coldest(identity())); + assertThrows(type, () -> eviction.hottestWeighted(1L)); + assertThrows(type, () -> eviction.hottest(identity())); + assertThrows(type, () -> fixedExpiration.oldest(identity())); + assertThrows(type, () -> fixedExpiration.youngest(identity())); + assertThrows(type, () -> varExpiration.oldest(identity())); + assertThrows(type, () -> varExpiration.youngest(identity())); + assertThrows(type, () -> varExpiration.compute(Int.MAX_VALUE, (k, v) -> v, Duration.ZERO)); } @Test diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CacheTest.java index edaacfa1cf..e7bda2f96a 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CacheTest.java @@ -25,6 +25,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static java.util.function.Function.identity; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static uk.org.lidalia.slf4jext.Level.ERROR; @@ -107,11 +108,10 @@ public void estimatedSize(Cache cache, CacheContext context) { /* --------------- getIfPresent --------------- */ @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getIfPresent_nullKey(Cache cache, CacheContext context) { - cache.getIfPresent(null); + assertThrows(NullPointerException.class, () -> cache.getIfPresent(null)); } @Test(dataProvider = "caches") @@ -135,26 +135,23 @@ public void getIfPresent_present(Cache cache, CacheContext context) { @CacheSpec @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void get_nullKey(Cache cache, CacheContext context) { - cache.get(null, identity()); + assertThrows(NullPointerException.class, () -> cache.get(null, identity())); } @CacheSpec @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void get_nullLoader(Cache cache, CacheContext context) { - cache.get(context.absentKey(), null); + assertThrows(NullPointerException.class, () -> cache.get(context.absentKey(), null)); } @CacheSpec @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void get_nullKeyAndLoader(Cache cache, CacheContext context) { - cache.get(null, null); + assertThrows(NullPointerException.class, () -> cache.get(null, null)); } @CacheSpec @@ -165,25 +162,19 @@ public void get_absent_null(Cache cache, CacheContext context) { } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) + @Test(dataProvider = "caches") public void get_absent_throwsException(Cache cache, CacheContext context) { - try { - cache.get(context.absentKey(), key -> { throw new IllegalStateException(); }); - } finally { - assertThat(context).stats().hits(0).misses(1).success(0).failures(1); - } + assertThrows(IllegalStateException.class, () -> + cache.get(context.absentKey(), key -> { throw new IllegalStateException(); })); + assertThat(context).stats().hits(0).misses(1).success(0).failures(1); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = UnknownError.class) + @Test(dataProvider = "caches") public void get_absent_throwsError(Cache cache, CacheContext context) { - try { - cache.get(context.absentKey(), key -> { throw new UnknownError(); }); - } finally { - assertThat(context).stats().hits(0).misses(1).success(0).failures(1); - } + assertThrows(UnknownError.class, () -> + cache.get(context.absentKey(), key -> { throw new UnknownError(); })); + assertThat(context).stats().hits(0).misses(1).success(0).failures(1); } @CacheSpec @@ -211,19 +202,18 @@ public void get_present(Cache cache, CacheContext context) { /* --------------- getAllPresent --------------- */ @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAllPresent_iterable_null(Cache cache, CacheContext context) { - cache.getAllPresent(null); + assertThrows(NullPointerException.class, () -> cache.getAllPresent(null)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAllPresent_iterable_nullKey(Cache cache, CacheContext context) { - cache.getAllPresent(Collections.singletonList(null)); + List keys = Collections.singletonList(null); + assertThrows(NullPointerException.class, () -> cache.getAllPresent(keys)); } @Test(dataProvider = "caches") @@ -243,9 +233,10 @@ public void getAllPresent_absent(Cache cache, CacheContext context) { } @CacheSpec - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void getAllPresent_immutable(Cache cache, CacheContext context) { - cache.getAllPresent(context.firstMiddleLastKeys()).clear(); + var result = cache.getAllPresent(context.firstMiddleLastKeys()); + assertThrows(UnsupportedOperationException.class, result::clear); } @Test(dataProvider = "caches") @@ -336,18 +327,19 @@ class Key { /* --------------- getAll --------------- */ - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_null(Cache cache, CacheContext context) { - cache.getAll(null, keys -> { throw new AssertionError(); }); + assertThrows(NullPointerException.class, () -> + cache.getAll(null, keys -> { throw new AssertionError(); })); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_nullKey(Cache cache, CacheContext context) { - cache.getAll(Collections.singletonList(null), keys -> { throw new AssertionError(); }); + List keys = Collections.singletonList(null); + assertThrows(NullPointerException.class, () -> + cache.getAll(keys, k -> { throw new AssertionError(); })); } @Test(dataProvider = "caches") @@ -358,40 +350,36 @@ public void getAll_iterable_empty(Cache cache, CacheContext context) { assertThat(context).stats().hits(0).misses(0); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_function_null(Cache cache, CacheContext context) { - cache.getAll(context.absentKeys(), null); + assertThrows(NullPointerException.class, () -> cache.getAll(context.absentKeys(), null)); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_function_nullValue(Cache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys(), keys -> null); - } finally { - int misses = context.loader().isBulk() ? 1 : context.absentKeys().size(); - assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); - } + assertThrows(NullPointerException.class, + () -> cache.getAll(context.absentKeys(), keys -> null)); + int misses = context.loader().isBulk() ? 1 : context.absentKeys().size(); + assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void getAll_immutable_keys(Cache cache, CacheContext context) { - cache.getAll(context.absentKeys(), keys -> { - keys.clear(); - return Map.of(); + assertThrows(UnsupportedOperationException.class, () -> { + cache.getAll(context.absentKeys(), keys -> { + throw assertThrows(UnsupportedOperationException.class, keys::clear); + }); }); } @CacheSpec - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void getAll_immutable_result(Cache cache, CacheContext context) { var result = cache.getAll(context.firstMiddleLastKeys(), bulkMappingFunction()); - result.clear(); + assertThrows(UnsupportedOperationException.class, result::clear); } @CacheSpec @@ -404,27 +392,21 @@ public void getAll_nullLookup(Cache cache, CacheContext context) { } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) + @Test(dataProvider = "caches") public void getAll_absent_throwsException(Cache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys(), keys -> { throw new IllegalStateException(); }); - } finally { - int misses = context.absentKeys().size(); - assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); - } + assertThrows(IllegalStateException.class, () -> + cache.getAll(context.absentKeys(), keys -> { throw new IllegalStateException(); })); + int misses = context.absentKeys().size(); + assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); } @CacheSpec - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = UnknownError.class) + @Test(dataProvider = "caches") public void getAll_function_throwsError(Cache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys(), keys -> { throw new UnknownError(); }); - } finally { - int misses = context.absentKeys().size(); - assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); - } + assertThrows(UnknownError.class, () -> + cache.getAll(context.absentKeys(), keys -> { throw new UnknownError(); })); + int misses = context.absentKeys().size(); + assertThat(context).stats().hits(0).misses(misses).success(0).failures(1); } @CacheSpec @@ -647,24 +629,24 @@ public void put_replace_differentValue(Cache cache, CacheContext conte } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullKey(Cache cache, CacheContext context) { - cache.put(null, context.absentValue()); + assertThrows(NullPointerException.class, () -> cache.put(null, context.absentValue())); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullValue(Cache cache, CacheContext context) { - cache.put(context.absentKey(), null); + assertThrows(NullPointerException.class, () -> cache.put(context.absentKey(), null)); } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullKeyAndValue(Cache cache, CacheContext context) { - cache.put(null, null); + assertThrows(NullPointerException.class, () -> cache.put(null, null)); } /* --------------- put all --------------- */ @@ -724,10 +706,10 @@ public void putAll_empty(Cache cache, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void putAll_null(Cache cache, CacheContext context) { - cache.putAll(null); + assertThrows(NullPointerException.class, () -> cache.putAll(null)); } /* --------------- invalidate --------------- */ @@ -755,10 +737,10 @@ public void invalidate_present(Cache cache, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void invalidate_nullKey(Cache cache, CacheContext context) { - cache.invalidate(null); + assertThrows(NullPointerException.class, () -> cache.invalidate(null)); } /* --------------- invalidateAll --------------- */ @@ -802,9 +784,9 @@ public void invalidateAll_full(Cache cache, CacheContext context) { @CacheSpec @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") public void invalidateAll_null(Cache cache, CacheContext context) { - cache.invalidateAll(null); + assertThrows(NullPointerException.class, () -> cache.invalidateAll(null)); } @CheckNoStats @@ -856,19 +838,17 @@ public void serialize(Cache cache, CacheContext context) { } @CheckNoStats + @Test(dataProvider = "caches") @CacheSpec(implementation = Implementation.Caffeine, population = Population.EMPTY) - @Test(dataProvider = "caches", expectedExceptions = InvalidObjectException.class, - expectedExceptionsMessageRegExp = "Proxy required") - public void readObject(CacheContext context) throws Throwable { + public void readObject(CacheContext context) throws NoSuchMethodException { var cache = context.isAsync() ? context.asyncCache() : context.cache(); var readObject = cache.getClass().getDeclaredMethod("readObject", ObjectInputStream.class); readObject.setAccessible(true); - try { - readObject.invoke(cache, new ObjectInputStream() {}); - } catch (InvocationTargetException e) { - throw e.getTargetException(); - } + var exception = assertThrows(InvocationTargetException.class, + () -> readObject.invoke(cache, new ObjectInputStream() {})); + assertThat(exception).hasCauseThat().isInstanceOf(InvalidObjectException.class); + assertThat(exception).hasCauseThat().hasMessageThat().isEqualTo("Proxy required"); } /* --------------- null parameter --------------- */ @@ -943,7 +923,6 @@ private ImmutableSetMultimap, Method> getPublicMethods() { @CacheSpec @CheckNoStats @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") public void stats(Cache cache, CacheContext context) { var stats = cache.stats() .plus(CacheStats.of(1, 2, 3, 4, 5, 6, 7) @@ -955,11 +934,10 @@ public void stats(Cache cache, CacheContext context) { /* --------------- Policy: getIfPresentQuietly --------------- */ @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getIfPresentQuietly_nullKey(Cache cache, CacheContext context) { - cache.policy().getIfPresentQuietly(null); + assertThrows(NullPointerException.class, () -> cache.policy().getIfPresentQuietly(null)); } @CheckNoStats @@ -982,11 +960,10 @@ public void getIfPresentQuietly_present(Cache cache, CacheContext cont /* --------------- Policy: getEntryIfPresentQuietly --------------- */ @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getEntryIfPresentQuietly_nullKey(Cache cache, CacheContext context) { - cache.policy().getEntryIfPresentQuietly(null); + assertThrows(NullPointerException.class, () -> cache.policy().getEntryIfPresentQuietly(null)); } @CheckNoStats @@ -1018,10 +995,9 @@ public void refreshes_empty(Cache cache, CacheContext context) { @CacheSpec @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void refreshes_unmodifiable(Cache cache, CacheContext context) { - cache.policy().refreshes().clear(); + assertThrows(UnsupportedOperationException.class, () -> cache.policy().refreshes().clear()); } @CacheSpec @@ -1034,10 +1010,10 @@ public void refreshes_nullLookup(Cache cache, CacheContext context) { /* --------------- Policy: CacheEntry --------------- */ - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = UnsupportedOperationException.class) + @Test public void cacheEntry_setValue() { - SnapshotEntry.forEntry(1, 2).setValue(3); + var entry = SnapshotEntry.forEntry(1, 2); + assertThrows(UnsupportedOperationException.class, () -> entry.setValue(3)); } @Test diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecGuavaTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecGuavaTest.java index cb3e469266..38d2f1fcfb 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecGuavaTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecGuavaTest.java @@ -17,6 +17,8 @@ import static com.github.benmanes.caffeine.cache.Caffeine.UNSET_INT; import static com.github.benmanes.caffeine.cache.CaffeineSpec.parse; +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import java.time.Duration; import java.util.concurrent.TimeUnit; @@ -450,31 +452,24 @@ public void testEqualsAndHashCode() { .testEquals(); } - @SuppressWarnings("CheckReturnValue") public void testMaximumWeight_withWeigher() { Caffeine builder = Caffeine.from(parse("maximumWeight=9000")); - builder.weigher((k, v) -> 42).build(k -> null); + assertThat(builder.weigher((k, v) -> 42).build(k -> null)).isNotNull(); } - @SuppressWarnings("CheckReturnValue") public void testMaximumWeight_withoutWeigher() { Caffeine builder = Caffeine.from(parse("maximumWeight=9000")); - try { - builder.build(k -> null); - fail(); - } catch (IllegalStateException expected) {} + assertThrows(IllegalStateException.class, () -> builder.build(k -> null)); } - @SuppressWarnings("CheckReturnValue") public void testMaximumSize_withWeigher() { Caffeine builder = Caffeine.from(parse("maximumSize=9000")); - builder.weigher((k, v) -> 42).build(k -> null); + assertThat(builder.weigher((k, v) -> 42).build(k -> null)).isNotNull(); } - @SuppressWarnings("CheckReturnValue") public void testMaximumSize_withoutWeigher() { Caffeine builder = Caffeine.from(parse("maximumSize=9000")); - builder.build(k -> null); + assertThat(builder.build(k -> null)).isNotNull(); } public void testCaffeineFrom_string() { diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java index b331bc0b46..16f3f461c3 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineSpecTest.java @@ -19,6 +19,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.Locale.US; import static java.util.Objects.requireNonNull; +import static org.junit.Assert.assertThrows; import java.time.Duration; import java.util.ArrayList; @@ -53,22 +54,19 @@ public final class CaffeineSpecTest { static final long UNSET_LONG = UNSET_INT; - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void parseInt_exception() { - CaffeineSpec.parseInt("key", "value"); + assertThrows(IllegalArgumentException.class, () -> CaffeineSpec.parseInt("key", "value")); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void parseLong_exception() { - CaffeineSpec.parseLong("key", "value"); + assertThrows(IllegalArgumentException.class, () -> CaffeineSpec.parseLong("key", "value")); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void parseTimeUnit_exception() { - CaffeineSpec.parseTimeUnit("key", "value"); + assertThrows(IllegalArgumentException.class, () -> CaffeineSpec.parseTimeUnit("key", "value")); } @Test(dataProvider = "caches") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java index 72e929fae2..ee1c2b0852 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/CaffeineTest.java @@ -17,6 +17,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; +import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.verify; import java.time.Duration; @@ -27,7 +28,6 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -93,10 +93,9 @@ public void configured() { .isNotEqualTo(Caffeine.newBuilder().maximumWeight(1).toString()); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = NullPointerException.class) + @Test public void fromSpec_null() { - Caffeine.from((CaffeineSpec) null); + assertThrows(NullPointerException.class, () -> Caffeine.from((CaffeineSpec) null)); } @Test @@ -110,10 +109,9 @@ public void fromSpec() { assertThat(Caffeine.from(CaffeineSpec.parse(""))).isNotNull(); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = NullPointerException.class) + @Test public void fromString_null() { - Caffeine.from((String) null); + assertThrows(NullPointerException.class, () -> Caffeine.from((String) null)); } @Test @@ -180,85 +178,79 @@ public void calculateHashMapCapacity() { /* --------------- loading --------------- */ - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = NullPointerException.class) + @Test public void loading_nullLoader() { - Caffeine.newBuilder().build(null); + assertThrows(NullPointerException.class, () -> Caffeine.newBuilder().build(null)); } /* --------------- async --------------- */ - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void async_weakValues() { - Caffeine.newBuilder().weakValues().buildAsync(loader); + var builder = Caffeine.newBuilder().weakValues(); + assertThrows(IllegalStateException.class, () -> builder.buildAsync(loader)); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void async_softValues() { - Caffeine.newBuilder().softValues().buildAsync(loader); + var builder = Caffeine.newBuilder().softValues(); + assertThrows(IllegalStateException.class, () -> builder.buildAsync(loader)); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void async_weakKeys_evictionListener() { RemovalListener evictionListener = (k, v, c) -> {}; - Caffeine.newBuilder().weakKeys().evictionListener(evictionListener).buildAsync(); + var builder = Caffeine.newBuilder().weakKeys().evictionListener(evictionListener); + assertThrows(IllegalStateException.class, builder::buildAsync); } /* --------------- async loader --------------- */ @Test - @SuppressWarnings("CheckReturnValue") public void asyncLoader_nullLoader() { - try { - Caffeine.newBuilder().buildAsync((CacheLoader) null); - Assert.fail(); - } catch (NullPointerException expected) {} - - try { - Caffeine.newBuilder().buildAsync((AsyncCacheLoader) null); - Assert.fail(); - } catch (NullPointerException expected) {} + assertThrows(NullPointerException.class, () -> + Caffeine.newBuilder().buildAsync((CacheLoader) null)); + assertThrows(NullPointerException.class, () -> + Caffeine.newBuilder().buildAsync((AsyncCacheLoader) null)); } @Test - @SuppressWarnings("UnnecessaryMethodReference") public void asyncLoader() { - var cache = Caffeine.newBuilder().buildAsync(loader::asyncLoad); + AsyncCacheLoader asyncLoader = loader::asyncLoad; + var cache = Caffeine.newBuilder().buildAsync(asyncLoader); assertThat(cache).isNotNull(); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void asyncLoader_weakValues() { - Caffeine.newBuilder().weakValues().buildAsync(loader); + var builder = Caffeine.newBuilder().weakValues(); + assertThrows(IllegalStateException.class, () -> builder.buildAsync(loader)); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void asyncLoader_softValues() { - Caffeine.newBuilder().softValues().buildAsync(loader); + var builder = Caffeine.newBuilder().softValues(); + assertThrows(IllegalStateException.class, () -> builder.buildAsync(loader)); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void async_asyncLoader_weakKeys_evictionListener() { RemovalListener evictionListener = (k, v, c) -> {}; - Caffeine.newBuilder().weakKeys().evictionListener(evictionListener).buildAsync(loader); + var builder = Caffeine.newBuilder().weakKeys().evictionListener(evictionListener); + assertThrows(IllegalStateException.class, () -> builder.buildAsync(loader)); } /* --------------- initialCapacity --------------- */ - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void initialCapacity_negative() { - Caffeine.newBuilder().initialCapacity(-1); + assertThrows(IllegalArgumentException.class, () -> Caffeine.newBuilder().initialCapacity(-1)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void initialCapacity_twice() { - Caffeine.newBuilder().initialCapacity(1).initialCapacity(1); + var builder = Caffeine.newBuilder().initialCapacity(1); + assertThrows(IllegalStateException.class, () -> builder.initialCapacity(1)); } @Test @@ -278,24 +270,27 @@ public void initialCapacity_large() { /* --------------- maximumSize --------------- */ - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void maximumSize_negative() { - Caffeine.newBuilder().maximumSize(-1); + assertThrows(IllegalArgumentException.class, () -> Caffeine.newBuilder().maximumSize(-1)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void maximumSize_twice() { - Caffeine.newBuilder().maximumSize(1).maximumSize(1); + var builder = Caffeine.newBuilder().maximumSize(1); + assertThrows(IllegalStateException.class, () -> builder.maximumSize(1)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void maximumSize_maximumWeight() { - Caffeine.newBuilder().maximumWeight(1).maximumSize(1); + var builder = Caffeine.newBuilder().maximumWeight(1); + assertThrows(IllegalStateException.class, () -> builder.maximumSize(1)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void maximumSize_weigher() { - Caffeine.newBuilder().weigher(Weigher.singletonWeigher()).maximumSize(1); + var builder = Caffeine.newBuilder().weigher(Weigher.singletonWeigher()); + assertThrows(IllegalStateException.class, () -> builder.maximumSize(1)); } @Test @@ -316,25 +311,26 @@ public void maximumSize_large() { /* --------------- maximumWeight --------------- */ - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void maximumWeight_negative() { - Caffeine.newBuilder().maximumWeight(-1); + assertThrows(IllegalArgumentException.class, () -> Caffeine.newBuilder().maximumWeight(-1)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void maximumWeight_twice() { - Caffeine.newBuilder().maximumWeight(1).maximumWeight(1); + var builder = Caffeine.newBuilder().maximumWeight(1); + assertThrows(IllegalStateException.class, () -> builder.maximumWeight(1)); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void maximumWeight_noWeigher() { - Caffeine.newBuilder().maximumWeight(1).build(); + assertThrows(IllegalStateException.class, () -> Caffeine.newBuilder().maximumWeight(1).build()); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void maximumWeight_maximumSize() { - Caffeine.newBuilder().maximumSize(1).maximumWeight(1); + var builder = Caffeine.newBuilder().maximumSize(1); + assertThrows(IllegalStateException.class, () -> builder.maximumWeight(1)); } @Test @@ -362,25 +358,27 @@ public void maximumWeight_large() { /* --------------- weigher --------------- */ - @Test(expectedExceptions = NullPointerException.class) + @Test public void weigher_null() { - Caffeine.newBuilder().weigher(null); + assertThrows(NullPointerException.class, () -> Caffeine.newBuilder().weigher(null)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void weigher_twice() { - Caffeine.newBuilder().weigher(Weigher.singletonWeigher()).weigher(Weigher.singletonWeigher()); + var builder = Caffeine.newBuilder().weigher(Weigher.singletonWeigher()); + assertThrows(IllegalStateException.class, () -> builder.weigher(Weigher.singletonWeigher())); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void weigher_maximumSize() { - Caffeine.newBuilder().maximumSize(1).weigher(Weigher.singletonWeigher()); + var builder = Caffeine.newBuilder().maximumSize(1); + assertThrows(IllegalStateException.class, () -> builder.weigher(Weigher.singletonWeigher())); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void weigher_noMaximumWeight() { - Caffeine.newBuilder().weigher(Weigher.singletonWeigher()).build(); + assertThrows(IllegalStateException.class, () -> + Caffeine.newBuilder().weigher(Weigher.singletonWeigher()).build()); } @Test @@ -393,20 +391,24 @@ public void weigher() { /* --------------- expireAfterAccess --------------- */ - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void expireAfterAccess_negative() { - Caffeine.newBuilder().expireAfterAccess(-1, TimeUnit.MILLISECONDS); + assertThrows(IllegalArgumentException.class, () -> + Caffeine.newBuilder().expireAfterAccess(-1, TimeUnit.MILLISECONDS)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfterAccess_expiry() { - Caffeine.newBuilder().expireAfter(expiry).expireAfterAccess(1, TimeUnit.MILLISECONDS); + var builder = Caffeine.newBuilder().expireAfter(expiry); + assertThrows(IllegalStateException.class, () -> + builder.expireAfterAccess(1, TimeUnit.MILLISECONDS)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfterAccess_twice() { - Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MILLISECONDS) - .expireAfterAccess(1, TimeUnit.MILLISECONDS); + var builder = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MILLISECONDS); + assertThrows(IllegalStateException.class, () -> + builder.expireAfterAccess(1, TimeUnit.MILLISECONDS)); } @Test @@ -427,20 +429,24 @@ public void expireAfterAccess_large() { /* --------------- expireAfterAccess: java.time --------------- */ - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void expireAfterAccess_duration_negative() { - Caffeine.newBuilder().expireAfterAccess(Duration.ofMillis(-1)); + assertThrows(IllegalArgumentException.class, () -> + Caffeine.newBuilder().expireAfterAccess(Duration.ofMillis(-1))); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfterAccess_duration_expiry() { - Caffeine.newBuilder().expireAfter(expiry).expireAfterAccess(Duration.ofMillis(1)); + var builder = Caffeine.newBuilder().expireAfter(expiry); + assertThrows(IllegalStateException.class, () -> + builder.expireAfterAccess(Duration.ofMillis(1))); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfterAccess_duration_twice() { - Caffeine.newBuilder().expireAfterAccess(Duration.ofMillis(1)) - .expireAfterAccess(Duration.ofMillis(1)); + var builder = Caffeine.newBuilder().expireAfterAccess(Duration.ofMillis(1)); + assertThrows(IllegalStateException.class, () -> + builder.expireAfterAccess(Duration.ofMillis(1))); } @Test @@ -469,20 +475,24 @@ public void expireAfterAccess_duration_excessive() { /* --------------- expireAfterWrite --------------- */ - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void expireAfterWrite_negative() { - Caffeine.newBuilder().expireAfterWrite(-1, TimeUnit.MILLISECONDS); + assertThrows(IllegalArgumentException.class, () -> + Caffeine.newBuilder().expireAfterWrite(-1, TimeUnit.MILLISECONDS)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfterWrite_expiry() { - Caffeine.newBuilder().expireAfter(expiry).expireAfterWrite(1, TimeUnit.MILLISECONDS); + var builder = Caffeine.newBuilder().expireAfter(expiry); + assertThrows(IllegalStateException.class, () -> + builder.expireAfterWrite(1, TimeUnit.MILLISECONDS)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfterWrite_twice() { - Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MILLISECONDS) - .expireAfterWrite(1, TimeUnit.MILLISECONDS); + var builder = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MILLISECONDS); + assertThrows(IllegalStateException.class, () -> + builder.expireAfterWrite(1, TimeUnit.MILLISECONDS)); } @Test @@ -504,20 +514,22 @@ public void expireAfterWrite_large() { /* --------------- expireAfterWrite: java.time --------------- */ - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void expireAfterWrite_duration_negative() { - Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(-1)); + assertThrows(IllegalArgumentException.class, () -> + Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(-1))); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfterWrite_duration_expiry() { - Caffeine.newBuilder().expireAfter(expiry).expireAfterWrite(Duration.ofMillis(1)); + var builder = Caffeine.newBuilder().expireAfter(expiry); + assertThrows(IllegalStateException.class, () -> builder.expireAfterWrite(Duration.ofMillis(1))); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfterWrite_duration_twice() { - Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(1)) - .expireAfterWrite(Duration.ofMillis(1)); + var builder = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(1)); + assertThrows(IllegalStateException.class, () -> builder.expireAfterWrite(Duration.ofMillis(1))); } @Test @@ -546,24 +558,27 @@ public void expireAfterWrite_duration_excessive() { /* --------------- expiry --------------- */ - @Test(expectedExceptions = NullPointerException.class) + @Test public void expireAfter_null() { - Caffeine.newBuilder().expireAfter(null); + assertThrows(NullPointerException.class, () -> Caffeine.newBuilder().expireAfter(null)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfter_twice() { - Caffeine.newBuilder().expireAfter(expiry).expireAfter(expiry); + var builder = Caffeine.newBuilder().expireAfter(expiry); + assertThrows(IllegalStateException.class, () -> builder.expireAfter(expiry)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfter_access() { - Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MILLISECONDS).expireAfter(expiry); + var builder = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MILLISECONDS); + assertThrows(IllegalStateException.class, () -> builder.expireAfter(expiry)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void expireAfter_write() { - Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MILLISECONDS).expireAfter(expiry); + var builder = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MILLISECONDS); + assertThrows(IllegalStateException.class, () -> builder.expireAfter(expiry)); } @Test @@ -575,26 +590,29 @@ public void expireAfter() { /* --------------- refreshAfterWrite --------------- */ - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void refreshAfterWrite_negative() { - Caffeine.newBuilder().refreshAfterWrite(-1, TimeUnit.MILLISECONDS); + assertThrows(IllegalArgumentException.class, () -> + Caffeine.newBuilder().refreshAfterWrite(-1, TimeUnit.MILLISECONDS)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void refreshAfterWrite_twice() { - Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MILLISECONDS) - .refreshAfterWrite(1, TimeUnit.MILLISECONDS); + var builder = Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MILLISECONDS); + assertThrows(IllegalStateException.class, () -> + builder.refreshAfterWrite(1, TimeUnit.MILLISECONDS)); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void refreshAfterWrite_noCacheLoader() { - Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MILLISECONDS).build(); + assertThrows(IllegalStateException.class, () -> + Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MILLISECONDS).build()); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void refreshAfterWrite_zero() { - Caffeine.newBuilder().refreshAfterWrite(0, TimeUnit.MILLISECONDS); + assertThrows(IllegalArgumentException.class, () -> + Caffeine.newBuilder().refreshAfterWrite(0, TimeUnit.MILLISECONDS)); } @Test @@ -607,26 +625,29 @@ public void refreshAfterWrite() { /* --------------- refreshAfterWrite: java.time --------------- */ - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void refreshAfterWrite_duration_negative() { - Caffeine.newBuilder().refreshAfterWrite(Duration.ofMillis(-1)); + assertThrows(IllegalArgumentException.class, () -> + Caffeine.newBuilder().refreshAfterWrite(Duration.ofMillis(-1))); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void refreshAfterWrite_duration_twice() { - Caffeine.newBuilder().refreshAfterWrite(Duration.ofMillis(1)) - .refreshAfterWrite(Duration.ofMillis(1)); + var builder = Caffeine.newBuilder().refreshAfterWrite(Duration.ofMillis(1)); + assertThrows(IllegalStateException.class, () -> + builder.refreshAfterWrite(Duration.ofMillis(1))); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void refreshAfterWrite_duration_noCacheLoader() { - Caffeine.newBuilder().refreshAfterWrite(Duration.ofMillis(1)).build(); + assertThrows(IllegalStateException.class, () -> + Caffeine.newBuilder().refreshAfterWrite(Duration.ofMillis(1)).build()); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void refreshAfterWrite_duration_zero() { - Caffeine.newBuilder().refreshAfterWrite(Duration.ZERO); + assertThrows(IllegalArgumentException.class, () -> + Caffeine.newBuilder().refreshAfterWrite(Duration.ZERO)); } @Test @@ -645,9 +666,10 @@ public void refreshAfterWrite_excessive() { /* --------------- weakKeys --------------- */ - @Test(expectedExceptions = IllegalStateException.class) + @Test public void weakKeys_twice() { - Caffeine.newBuilder().weakKeys().weakKeys(); + var builder = Caffeine.newBuilder().weakKeys(); + assertThrows(IllegalStateException.class, builder::weakKeys); } @Test @@ -658,9 +680,10 @@ public void weakKeys() { /* --------------- weakValues --------------- */ - @Test(expectedExceptions = IllegalStateException.class) + @Test public void weakValues_twice() { - Caffeine.newBuilder().weakValues().weakValues(); + var builder = Caffeine.newBuilder().weakValues(); + assertThrows(IllegalStateException.class, builder::weakValues); } @Test @@ -671,9 +694,10 @@ public void weakValues() { /* --------------- softValues --------------- */ - @Test(expectedExceptions = IllegalStateException.class) + @Test public void softValues_twice() { - Caffeine.newBuilder().softValues().softValues(); + var builder = Caffeine.newBuilder().softValues(); + assertThrows(IllegalStateException.class, builder::softValues); } @Test @@ -684,15 +708,16 @@ public void softValues() { /* --------------- scheduler --------------- */ - @Test(expectedExceptions = NullPointerException.class) + @Test public void scheduler_null() { - Caffeine.newBuilder().scheduler(null); + assertThrows(NullPointerException.class, () -> Caffeine.newBuilder().scheduler(null)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void scheduler_twice() { - Caffeine.newBuilder().scheduler(Scheduler.disabledScheduler()) - .scheduler(Scheduler.disabledScheduler()); + var builder = Caffeine.newBuilder().scheduler(Scheduler.disabledScheduler()); + assertThrows(IllegalStateException.class, () -> + builder.scheduler(Scheduler.disabledScheduler())); } @Test @@ -712,15 +737,15 @@ public void scheduler_custom() { /* --------------- executor --------------- */ - @Test(expectedExceptions = NullPointerException.class) + @Test public void executor_null() { - Caffeine.newBuilder().executor(null); + assertThrows(NullPointerException.class, () -> Caffeine.newBuilder().executor(null)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void executor_twice() { - Caffeine.newBuilder().executor(directExecutor()) - .executor(directExecutor()); + var builder = Caffeine.newBuilder().executor(directExecutor()); + assertThrows(IllegalStateException.class, () -> builder.executor(directExecutor())); } @Test @@ -732,14 +757,15 @@ public void executor() { /* --------------- ticker --------------- */ - @Test(expectedExceptions = NullPointerException.class) + @Test public void ticker_null() { - Caffeine.newBuilder().ticker(null); + assertThrows(NullPointerException.class, () -> Caffeine.newBuilder().ticker(null)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void ticker_twice() { - Caffeine.newBuilder().ticker(Ticker.systemTicker()).ticker(Ticker.systemTicker()); + var builder = Caffeine.newBuilder().ticker(Ticker.systemTicker()); + assertThrows(IllegalStateException.class, () -> builder.ticker(Ticker.systemTicker())); } @Test @@ -752,26 +778,19 @@ public void ticker() { /* --------------- stats --------------- */ - @Test(expectedExceptions = NullPointerException.class) + @Test public void recordStats_null() { - Caffeine.newBuilder().recordStats(null); + assertThrows(NullPointerException.class, () -> Caffeine.newBuilder().recordStats(null)); } @Test public void recordStats_twice() { + var type = IllegalStateException.class; Supplier supplier = () -> statsCounter; - Runnable[] tasks = { - () -> Caffeine.newBuilder().recordStats().recordStats(), - () -> Caffeine.newBuilder().recordStats(supplier).recordStats(), - () -> Caffeine.newBuilder().recordStats().recordStats(supplier), - () -> Caffeine.newBuilder().recordStats(supplier).recordStats(supplier), - }; - for (Runnable task : tasks) { - try { - task.run(); - Assert.fail(); - } catch (IllegalStateException expected) {} - } + assertThrows(type, () -> Caffeine.newBuilder().recordStats().recordStats()); + assertThrows(type, () -> Caffeine.newBuilder().recordStats(supplier).recordStats()); + assertThrows(type, () -> Caffeine.newBuilder().recordStats().recordStats(supplier)); + assertThrows(type, () -> Caffeine.newBuilder().recordStats(supplier).recordStats(supplier)); } @Test @@ -792,14 +811,15 @@ public void recordStats_custom() { /* --------------- removalListener --------------- */ - @Test(expectedExceptions = NullPointerException.class) + @Test public void removalListener_null() { - Caffeine.newBuilder().removalListener(null); + assertThrows(NullPointerException.class, () -> Caffeine.newBuilder().removalListener(null)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void removalListener_twice() { - Caffeine.newBuilder().removalListener((k, v, c) -> {}).removalListener((k, v, c) -> {}); + var builder = Caffeine.newBuilder().removalListener((k, v, c) -> {}); + assertThrows(IllegalStateException.class, () -> builder.removalListener((k, v, c) -> {})); } @Test @@ -812,14 +832,15 @@ public void removalListener() { /* --------------- removalListener --------------- */ - @Test(expectedExceptions = NullPointerException.class) + @Test public void evictionListener_null() { - Caffeine.newBuilder().evictionListener(null); + assertThrows(NullPointerException.class, () -> Caffeine.newBuilder().evictionListener(null)); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void evictionListener_twice() { - Caffeine.newBuilder().evictionListener((k, v, c) -> {}).evictionListener((k, v, c) -> {}); + var builder = Caffeine.newBuilder().evictionListener((k, v, c) -> {}); + assertThrows(IllegalStateException.class, () -> builder.evictionListener((k, v, c) -> {})); } @Test diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java index c93bd33f88..e50ab1d4ca 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/EvictionTest.java @@ -30,6 +30,8 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; +import static java.util.function.Function.identity; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; @@ -46,7 +48,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -214,7 +215,6 @@ public void evict_weighted_entryTooBig(Cache cache, CacheContext conte @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.TEN, weigher = CacheWeigher.VALUE, removalListener = Listener.CONSUMING) - @SuppressWarnings("FutureReturnValueIgnored") public void evict_weighted_async(AsyncCache cache, CacheContext context) { var ready = new AtomicBoolean(); var done = new AtomicBoolean(); @@ -222,7 +222,7 @@ public void evict_weighted_async(AsyncCache cache, CacheContext contex await().untilTrue(ready); return Int.valueOf(6); }, executor); - valueFuture.whenComplete((r, e) -> done.set(true)); + var completed = valueFuture.whenComplete((r, e) -> done.set(true)); cache.put(Int.valueOf(5), Int.futureOf(5)); cache.put(Int.valueOf(4), Int.futureOf(4)); @@ -232,6 +232,7 @@ public void evict_weighted_async(AsyncCache cache, CacheContext contex ready.set(true); await().untilTrue(done); + await().until(completed::isDone); await().untilAsserted(() -> assertThat(cache).hasSize(2)); await().untilAsserted(() -> assertThat(context) .hasWeightedSizeLessThan(context.maximumWeight() + 1)); @@ -245,7 +246,6 @@ public void evict_weighted_async(AsyncCache cache, CacheContext contex @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.ZERO, weigher = CacheWeigher.COLLECTION) - @SuppressWarnings("FutureReturnValueIgnored") public void evict_zero_async(AsyncCache> cache, CacheContext context) { var ready = new AtomicBoolean(); var done = new AtomicBoolean(); @@ -253,7 +253,7 @@ public void evict_zero_async(AsyncCache> cache, CacheContext cont await().untilTrue(ready); return Int.listOf(1, 2, 3, 4, 5); }, executor); - valueFuture.whenComplete((r, e) -> done.set(true)); + var completed = valueFuture.whenComplete((r, e) -> done.set(true)); cache.put(context.absentKey(), valueFuture); assertThat(context).hasWeightedSize(0); @@ -261,6 +261,7 @@ public void evict_zero_async(AsyncCache> cache, CacheContext cont ready.set(true); await().untilTrue(done); + await().until(completed::isDone); await().untilAsserted(() -> assertThat(cache).isEmpty()); assertThat(context).notifications().withCause(SIZE) .contains(Map.entry(context.absentKey(), Int.listOf(1, 2, 3, 4, 5))) @@ -282,47 +283,40 @@ public void evict_evictionListenerFails(Cache cache, CacheContext cont /* --------------- Weighted --------------- */ + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.FULL, weigher = CacheWeigher.NEGATIVE) - @Test(dataProvider = "caches", - expectedExceptions = { IllegalArgumentException.class, IllegalStateException.class }) public void put_negativeWeight(Cache cache, CacheContext context) { - try { - cache.put(context.absentKey(), context.absentValue()); - } finally { - assertThat(cache).doesNotContainKey(context.absentKey()); - } + assertThrows(IllegalArgumentException.class, () -> + cache.put(context.absentKey(), context.absentValue())); + assertThat(cache).doesNotContainKey(context.absentKey()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void put_weigherFails_insert(Cache cache, CacheContext context) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - cache.put(context.absentKey(), context.absentValue()); - } finally { - assertThat(cache).doesNotContainKey(context.absentKey()); - } + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> + cache.put(context.absentKey(), context.absentValue())); + assertThat(cache).doesNotContainKey(context.absentKey()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void put_weigherFails_update(Cache cache, CacheContext context, Eviction eviction) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - cache.put(context.firstKey(), context.absentValue()); - } finally { - assertThat(cache).containsExactlyEntriesIn(context.original()); - assertThat(eviction.weightOf(context.firstKey())).hasValue(1); - } + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> + cache.put(context.firstKey(), context.absentValue())); + assertThat(cache).containsExactlyEntriesIn(context.original()); + assertThat(eviction.weightOf(context.firstKey())).hasValue(1); } + @Test(dataProvider = "caches") @CacheSpec(maximumSize = Maximum.FULL, weigher = CacheWeigher.ZERO, population = Population.EMPTY) - @Test(dataProvider = "caches") public void put_zeroWeight(Cache cache, CacheContext context) { cache.put(context.absentKey(), context.absentValue()); } @@ -359,7 +353,6 @@ public void put_changeWeight(Cache> cache, CacheContext contex @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.FULL, weigher = CacheWeigher.COLLECTION) - @SuppressWarnings("FutureReturnValueIgnored") public void put_asyncWeight(AsyncCache> cache, CacheContext context) { var ready = new AtomicBoolean(); var done = new AtomicBoolean(); @@ -367,7 +360,7 @@ public void put_asyncWeight(AsyncCache> cache, CacheContext conte await().untilTrue(ready); return Int.listOf(1, 2, 3, 4, 5); }, executor); - valueFuture.whenComplete((r, e) -> done.set(true)); + var completed = valueFuture.whenComplete((r, e) -> done.set(true)); cache.put(context.absentKey(), valueFuture); assertThat(context).hasWeightedSize(0); @@ -375,36 +368,35 @@ public void put_asyncWeight(AsyncCache> cache, CacheContext conte ready.set(true); await().untilTrue(done); + await().until(completed::isDone); await().untilAsserted(() -> assertThat(cache).hasSize(1)); await().untilAsserted(() -> assertThat(context).hasWeightedSize(5)); } - @CacheSpec(population = Population.EMPTY, - maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) @Test(dataProvider = "caches") + @CacheSpec(population = Population.EMPTY, implementation = Implementation.Guava, + maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) public void replace_weigherFails_absent(Cache cache, CacheContext context) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - cache.asMap().replace(context.absentKey(), context.absentValue()); - } catch (IllegalStateException expected) { - // optionally thrown - } finally { - assertThat(cache).doesNotContainKey(context.absentKey()); + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + Runnable replace = () -> cache.asMap().replace(context.absentKey(), context.absentValue()); + if (context.isAsync() || context.isGuava()) { + replace.run(); + } else { + assertThrows(IllegalStateException.class, replace::run); } + assertThat(cache).doesNotContainKey(context.absentKey()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void replace_weigherFails_present(Cache cache, CacheContext context, Eviction eviction) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - cache.asMap().replace(context.firstKey(), context.absentValue()); - } finally { - assertThat(cache).containsExactlyEntriesIn(context.original()); - assertThat(eviction.weightOf(context.firstKey())).hasValue(1); - } + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> + cache.asMap().replace(context.firstKey(), context.absentValue())); + assertThat(cache).containsExactlyEntriesIn(context.original()); + assertThat(eviction.weightOf(context.firstKey())).hasValue(1); } @Test(dataProvider = "caches") @@ -453,48 +445,46 @@ public void replaceConditionally_changeWeight( assertThat(cache).hasSize(2); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches") public void replaceConditionally_weigherFails_absent( Cache cache, CacheContext context) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - cache.asMap().replace(context.absentKey(), context.absentValue(), context.absentValue()); - } catch (IllegalStateException expected) { - // optionally thrown - } finally { - assertThat(cache).doesNotContainKey(context.absentKey()); + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + Runnable replace = () -> cache.asMap().replace( + context.absentKey(), context.absentValue(), context.absentValue()); + if (context.isAsync() || context.isGuava()) { + replace.run(); + } else { + assertThrows(IllegalStateException.class, replace::run); } + assertThat(cache).doesNotContainKey(context.absentKey()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void replaceConditionally_weigherFails_presentKey( Cache cache, CacheContext context, Eviction eviction) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - cache.asMap().replace(context.firstKey(), context.absentValue(), context.absentValue()); - } finally { - assertThat(cache).containsExactlyEntriesIn(context.original()); - assertThat(eviction.weightOf(context.firstKey())).hasValue(1); - } + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> + cache.asMap().replace(context.firstKey(), context.absentValue(), context.absentValue())); + assertThat(cache).containsExactlyEntriesIn(context.original()); + assertThat(eviction.weightOf(context.firstKey())).hasValue(1); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void replaceConditionally_weigherFails_presentKeyAndValue( Cache cache, CacheContext context, Eviction eviction) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> { cache.asMap().replace(context.firstKey(), context.original().get(context.firstKey()), context.absentValue()); - } finally { - assertThat(cache).containsExactlyEntriesIn(context.original()); - assertThat(eviction.weightOf(context.firstKey())).hasValue(1); - } + }); + assertThat(cache).containsExactlyEntriesIn(context.original()); + assertThat(eviction.weightOf(context.firstKey())).hasValue(1); } @Test(dataProvider = "caches") @@ -549,21 +539,19 @@ public void invalidateAll(Cache> cache, CacheContext context) assertThat(cache).isEmpty(); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void computeIfAbsent_weigherFails(Cache cache, CacheContext context) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - cache.asMap().computeIfAbsent(context.absentKey(), key -> context.absentValue()); - } finally { - assertThat(cache).doesNotContainKey(context.absentKey()); - } + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> + cache.asMap().computeIfAbsent(context.absentKey(), key -> context.absentValue())); + assertThat(cache).doesNotContainKey(context.absentKey()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.FULL, weigher = CacheWeigher.TEN) - @Test(dataProvider = "caches") public void computeIfAbsent(Cache cache, CacheContext context, Eviction eviction) { cache.asMap().computeIfAbsent(context.absentKey(), key -> context.absentValue()); @@ -571,23 +559,21 @@ public void computeIfAbsent(Cache cache, assertThat(context).hasWeightedSize(10); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void computeIfPresent_weigherFails(Cache cache, CacheContext context, Eviction eviction) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - cache.asMap().computeIfPresent(context.firstKey(), (key, value) -> context.absentValue()); - } finally { - assertThat(cache).containsExactlyEntriesIn(context.original()); - assertThat(eviction.weightOf(context.firstKey())).hasValue(1); - } + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> + cache.asMap().computeIfPresent(context.firstKey(), (key, value) -> context.absentValue())); + assertThat(cache).containsExactlyEntriesIn(context.original()); + assertThat(eviction.weightOf(context.firstKey())).hasValue(1); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.UNREACHABLE, weigher = CacheWeigher.VALUE) - @Test(dataProvider = "caches") public void computeIfPresent(Cache cache, CacheContext context, Eviction eviction) { long weightedSize = eviction.weightedSize().getAsLong() @@ -598,35 +584,31 @@ public void computeIfPresent(Cache cache, assertThat(context).hasWeightedSize(weightedSize); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void compute_weigherFails_absent(Cache cache, CacheContext context) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - cache.asMap().compute(context.absentKey(), (key, value) -> context.absentValue()); - } finally { - assertThat(cache).doesNotContainKey(context.absentKey()); - } + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> + cache.asMap().compute(context.absentKey(), (key, value) -> context.absentValue())); + assertThat(cache).doesNotContainKey(context.absentKey()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void compute_weigherFails_present(Cache cache, CacheContext context, Eviction eviction) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); - cache.asMap().compute(context.firstKey(), (key, value) -> context.absentValue()); - } finally { - assertThat(cache).containsExactlyEntriesIn(context.original()); - assertThat(eviction.weightOf(context.firstKey())).hasValue(1); - } + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> + cache.asMap().compute(context.firstKey(), (key, value) -> context.absentValue())); + assertThat(cache).containsExactlyEntriesIn(context.original()); + assertThat(eviction.weightOf(context.firstKey())).hasValue(1); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.UNREACHABLE, weigher = CacheWeigher.VALUE) - @Test(dataProvider = "caches") public void compute_insert(Cache cache, CacheContext context, Eviction eviction) { long weightedSize = eviction.weightedSize().getAsLong() @@ -637,9 +619,9 @@ public void compute_insert(Cache cache, assertThat(context).hasWeightedSize(weightedSize); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.UNREACHABLE, weigher = CacheWeigher.VALUE) - @Test(dataProvider = "caches") public void compute_update(Cache cache, CacheContext context, Eviction eviction) { long weightedSize = eviction.weightedSize().getAsLong() @@ -650,37 +632,35 @@ public void compute_update(Cache cache, assertThat(context).hasWeightedSize(weightedSize); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.EMPTY, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void merge_weigherFails_absent(Cache cache, CacheContext context) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> { cache.asMap().merge(context.absentKey(), context.absentKey(), (key, value) -> context.absentValue()); - } finally { - assertThat(cache).doesNotContainKey(context.absentKey()); - } + }); + assertThat(cache).doesNotContainKey(context.absentKey()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.FULL, weigher = CacheWeigher.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void merge_weigherFails_present(Cache cache, CacheContext context, Eviction eviction) { - try { - when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + when(context.weigher().weigh(any(), any())).thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> { cache.asMap().merge(context.firstKey(), context.absentValue(), (key, value) -> context.absentValue()); - } finally { - assertThat(cache).containsExactlyEntriesIn(context.original()); - assertThat(eviction.weightOf(context.firstKey())).hasValue(1); - } + }); + assertThat(cache).containsExactlyEntriesIn(context.original()); + assertThat(eviction.weightOf(context.firstKey())).hasValue(1); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.UNREACHABLE, weigher = CacheWeigher.VALUE) - @Test(dataProvider = "caches") public void merge_absent(Cache cache, CacheContext context, Eviction eviction) { long weightedSize = eviction.weightedSize().getAsLong() @@ -692,9 +672,9 @@ public void merge_absent(Cache cache, assertThat(context).hasWeightedSize(weightedSize); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, maximumSize = Maximum.UNREACHABLE, weigher = CacheWeigher.VALUE) - @Test(dataProvider = "caches") public void merge_update(Cache cache, CacheContext context, Eviction eviction) { long weightedSize = eviction.weightedSize().getAsLong() @@ -821,16 +801,13 @@ public void maximumSize_decrease_min(Cache cache, .contains(context.original()).exclusively(); } + @Test(dataProvider = "caches") @CacheSpec(maximumSize = Maximum.FULL) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void maximumSize_decrease_negative(Cache cache, CacheContext context, Eviction eviction) { - try { - eviction.setMaximum(-1); - } finally { - assertThat(eviction.getMaximum()).isEqualTo(context.maximumWeightOrSize()); - assertThat(context).notifications().isEmpty(); - } + assertThrows(IllegalArgumentException.class, () -> eviction.setMaximum(-1)); + assertThat(eviction.getMaximum()).isEqualTo(context.maximumWeightOrSize()); + assertThat(context).notifications().isEmpty(); } @Test(dataProvider = "caches") @@ -853,17 +830,17 @@ public void maximumSize_increase_max(Cache cache, /* --------------- Policy: Coldest --------------- */ + @Test(dataProvider = "caches") @CacheSpec(maximumSize = Maximum.FULL) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void coldest_unmodifiable(CacheContext context, Eviction eviction) { - eviction.coldest(Integer.MAX_VALUE).clear(); + var result = eviction.coldest(Integer.MAX_VALUE); + assertThrows(UnsupportedOperationException.class, result::clear); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(maximumSize = Maximum.FULL) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void coldest_negative(CacheContext context, Eviction eviction) { - eviction.coldest(-1); + assertThrows(IllegalArgumentException.class, () -> eviction.coldest(-1)); } @Test(dataProvider = "caches") @@ -903,11 +880,10 @@ public void coldest_snapshot(Cache cache, assertThat(coldest).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void coldestFunc_null(CacheContext context, Eviction eviction) { - eviction.coldest(null); + assertThrows(NullPointerException.class, () -> eviction.coldest(null)); } @Test(dataProvider = "caches") @@ -918,34 +894,32 @@ public void coldestFunc_nullResult(CacheContext context, Eviction evic } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void coldestFunc_throwsException(CacheContext context, Eviction eviction) { var expected = new IllegalStateException(); - try { - eviction.coldest(stream -> { throw expected; }); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(e).isSameInstanceAs(expected); - } + var actual = assertThrows(IllegalStateException.class, () -> + eviction.coldest(stream -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) + @Test(dataProvider = "caches") @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void coldestFunc_concurrentModification(Cache cache, CacheContext context, Eviction eviction) { - eviction.coldest(stream -> { - cache.put(context.absentKey(), context.absentValue()); - return stream.count(); + assertThrows(ConcurrentModificationException.class, () -> { + eviction.coldest(stream -> { + cache.put(context.absentKey(), context.absentValue()); + throw assertThrows(ConcurrentModificationException.class, stream::count); + }); }); } - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "source already consumed or closed") + @Test(dataProvider = "caches") @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void coldestFunc_closed(CacheContext context, Eviction eviction) { - eviction.coldest(stream -> stream).forEach(e -> {}); + var stream = eviction.coldest(identity()); + var exception = assertThrows(IllegalStateException.class, () -> stream.forEach(e -> {})); + assertThat(exception).hasMessageThat().isEqualTo("source already consumed or closed"); } @Test(dataProvider = "caches") @@ -993,17 +967,17 @@ public void coldestFunc_metadata(Cache cache, } } + @Test(dataProvider = "caches") @CacheSpec(maximumSize = Maximum.FULL) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void coldestWeight_unmodifiable(CacheContext context, Eviction eviction) { - eviction.coldestWeighted(Long.MAX_VALUE).clear(); + var results = eviction.coldestWeighted(Long.MAX_VALUE); + assertThrows(UnsupportedOperationException.class, results::clear); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(maximumSize = Maximum.FULL) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void coldestWeighted_negative(CacheContext context, Eviction eviction) { - eviction.coldestWeighted(-1); + assertThrows(IllegalArgumentException.class, () -> eviction.coldestWeighted(-1)); } @Test(dataProvider = "caches") @@ -1061,17 +1035,17 @@ public void coldestWeighted_snapshot(Cache cache, /* --------------- Policy: Hottest --------------- */ + @Test(dataProvider = "caches") @CacheSpec(maximumSize = Maximum.FULL) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void hottest_unmodifiable(CacheContext context, Eviction eviction) { - eviction.hottest(Integer.MAX_VALUE).clear(); + var result = eviction.hottest(Integer.MAX_VALUE); + assertThrows(UnsupportedOperationException.class, result::clear); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(maximumSize = Maximum.FULL) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void hottest_negative(CacheContext context, Eviction eviction) { - eviction.hottest(-1); + assertThrows(IllegalArgumentException.class, () -> eviction.hottest(-1)); } @Test(dataProvider = "caches") @@ -1111,11 +1085,10 @@ public void hottest_snapshot(Cache cache, assertThat(hottest).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void hottestFunc_null(CacheContext context, Eviction eviction) { - eviction.hottest(null); + assertThrows(NullPointerException.class, () -> eviction.hottest(null)); } @Test(dataProvider = "caches") @@ -1126,34 +1099,32 @@ public void hottestFunc_nullResult(CacheContext context, Eviction evic } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void hottestFunc_throwsException(CacheContext context, Eviction eviction) { var expected = new IllegalStateException(); - try { - eviction.hottest(stream -> { throw expected; }); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(e).isSameInstanceAs(expected); - } + var actual = assertThrows(IllegalStateException.class, () -> + eviction.hottest(stream -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) + @Test(dataProvider = "caches") @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void hottestFunc_concurrentModification(Cache cache, CacheContext context, Eviction eviction) { - eviction.hottest(stream -> { - cache.put(context.absentKey(), context.absentValue()); - return stream.count(); + assertThrows(ConcurrentModificationException.class, () -> { + eviction.hottest(stream -> { + cache.put(context.absentKey(), context.absentValue()); + throw assertThrows(ConcurrentModificationException.class, stream::count); + }); }); } - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "source already consumed or closed") + @Test(dataProvider = "caches") @CacheSpec(initialCapacity = InitialCapacity.EXCESSIVE, maximumSize = Maximum.FULL) public void hottestFunc_closed(CacheContext context, Eviction eviction) { - eviction.hottest(stream -> stream).forEach(e -> {}); + var stream = eviction.hottest(identity()); + var exception = assertThrows(IllegalStateException.class, () -> stream.forEach(e -> {})); + assertThat(exception).hasMessageThat().isEqualTo("source already consumed or closed"); } @Test(dataProvider = "caches") @@ -1210,17 +1181,17 @@ public void hottestWeighted_snapshot(Cache cache, assertThat(hottest).containsExactlyEntriesIn(context.original()); } + @Test(dataProvider = "caches") @CacheSpec(maximumSize = Maximum.FULL) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void hottestWeighted_unmodifiable(CacheContext context, Eviction eviction) { - eviction.hottestWeighted(Long.MAX_VALUE).clear(); + var result = eviction.hottestWeighted(Long.MAX_VALUE); + assertThrows(UnsupportedOperationException.class, result::clear); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(maximumSize = Maximum.FULL) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void hottestWeighted_negative(CacheContext context, Eviction eviction) { - eviction.hottestWeighted(-1); + assertThrows(IllegalArgumentException.class, () -> eviction.hottestWeighted(-1)); } @Test(dataProvider = "caches") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java index 72035a2e75..1a88c40337 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpirationTest.java @@ -29,6 +29,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.Map.entry; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; @@ -50,7 +51,6 @@ import org.mockito.ArgumentCaptor; import org.mockito.stubbing.Answer; -import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -1032,12 +1032,10 @@ public void computeIfAbsent_writeTime(Map map, CacheContext context) { expireAfterWrite = { Expire.DISABLED, Expire.ONE_MINUTE }) public void computeIfAbsent_error(Cache cache, CacheContext context) { context.ticker().advance(2, TimeUnit.MINUTES); - try { + assertThrows(IllegalStateException.class, () -> { cache.asMap().computeIfAbsent(context.firstKey(), key -> { throw new IllegalStateException(); }); - Assert.fail(); - } catch (IllegalStateException expected) {} - + }); assertThat(cache.policy().expireAfterAccess() .flatMap(policy -> policy.ageOf(context.firstKey()))).isEmpty(); assertThat(cache.policy().expireAfterWrite() @@ -1140,11 +1138,10 @@ public void computeIfPresent_error(Cache cache, CacheContext context) .flatMap(policy -> policy.ageOf(context.firstKey())); var variable = cache.policy().expireVariably() .flatMap(policy -> policy.getExpiresAfter(context.firstKey())); - try { + assertThrows(IllegalStateException.class, () -> { cache.asMap().computeIfPresent(context.firstKey(), (key, value) -> { throw new IllegalStateException(); }); - Assert.fail(); - } catch (IllegalStateException expected) {} + }); assertThat(access).isEqualTo(cache.policy().expireAfterAccess() .flatMap(policy -> policy.ageOf(context.firstKey()))); @@ -1257,11 +1254,10 @@ public void compute_writeTime(Map map, CacheContext context) { expireAfterWrite = { Expire.DISABLED, Expire.ONE_MINUTE }) public void compute_absent_error(Cache cache, CacheContext context) { context.ticker().advance(2, TimeUnit.MINUTES); - try { + assertThrows(IllegalStateException.class, () -> { cache.asMap().compute(context.firstKey(), (key, value) -> { throw new IllegalStateException(); }); - Assert.fail(); - } catch (IllegalStateException expected) {} + }); assertThat(cache.policy().expireAfterAccess() .flatMap(policy -> policy.ageOf(context.firstKey()))).isEmpty(); @@ -1283,11 +1279,10 @@ public void compute_present_error(Cache cache, CacheContext context) { .flatMap(policy -> policy.ageOf(context.firstKey())); var variable = cache.policy().expireVariably() .flatMap(policy -> policy.getExpiresAfter(context.firstKey())); - try { + assertThrows(IllegalStateException.class, () -> { cache.asMap().compute(context.firstKey(), (key, value) -> { throw new IllegalStateException(); }); - Assert.fail(); - } catch (IllegalStateException expected) {} + }); assertThat(access).isEqualTo(cache.policy().expireAfterAccess() .flatMap(policy -> policy.ageOf(context.firstKey()))); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterAccessTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterAccessTest.java index 4c3b7fd2a9..311654279e 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterAccessTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterAccessTest.java @@ -27,6 +27,7 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; +import static org.junit.Assert.assertThrows; import static uk.org.lidalia.slf4jext.Level.WARN; import java.time.Duration; @@ -38,7 +39,6 @@ import java.util.concurrent.TimeUnit; import java.util.function.Function; -import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -301,11 +301,12 @@ public void getExpiresAfter_duration(CacheContext context, assertThat(expireAfterAccess.getExpiresAfter()).isEqualTo(Duration.ofMinutes(1)); } - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void setExpiresAfter_negative(Cache cache, CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.setExpiresAfter(Duration.ofMinutes(-2)); + var duration = Duration.ofMinutes(-2); + assertThrows(IllegalArgumentException.class, () -> expireAfterAccess.setExpiresAfter(duration)); } @Test(dataProvider = "caches") @@ -384,20 +385,19 @@ public void ageOf_expired(Cache cache, CacheContext context, /* --------------- Policy: oldest --------------- */ - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void oldest_unmodifiable(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.oldest(Integer.MAX_VALUE).clear(); + var results = expireAfterAccess.oldest(Integer.MAX_VALUE); + assertThrows(UnsupportedOperationException.class, results::clear); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void oldest_negative(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.oldest(-1); + assertThrows(IllegalArgumentException.class, () -> expireAfterAccess.oldest(-1)); } @Test(dataProvider = "caches") @@ -434,12 +434,11 @@ public void oldest_snapshot(Cache cache, CacheContext context, assertThat(oldest).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void oldestFunc_null(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.oldest(null); + assertThrows(NullPointerException.class, () -> expireAfterAccess.oldest(null)); } @Test(dataProvider = "caches") @@ -451,36 +450,34 @@ public void oldestFunc_nullResult(CacheContext context, } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void oldestFunc_throwsException(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { var expected = new IllegalStateException(); - try { - expireAfterAccess.oldest(stream -> { throw expected; }); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(e).isSameInstanceAs(expected); - } + var actual = assertThrows(IllegalStateException.class, () -> + expireAfterAccess.oldest(stream -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) public void oldestFunc_concurrentModification(Cache cache, CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.oldest(stream -> { - cache.put(context.absentKey(), context.absentValue()); - return stream.count(); + assertThrows(ConcurrentModificationException.class, () -> { + expireAfterAccess.oldest(stream -> { + cache.put(context.absentKey(), context.absentValue()); + throw assertThrows(ConcurrentModificationException.class, stream::count); + }); }); } - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "source already consumed or closed") + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void oldestFunc_closed(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.oldest(stream -> stream).forEach(e -> {}); + var stream = expireAfterAccess.oldest(identity()); + var exception = assertThrows(IllegalStateException.class, () -> stream.forEach(e -> {})); + assertThat(exception).hasMessageThat().isEqualTo("source already consumed or closed"); } @Test(dataProvider = "caches") @@ -536,20 +533,19 @@ public void oldestFunc_metadata_expiresInTraversal(CacheContext context, /* --------------- Policy: youngest --------------- */ - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void youngest_unmodifiable(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.youngest(Integer.MAX_VALUE).clear(); + var results = expireAfterAccess.youngest(Integer.MAX_VALUE); + assertThrows(UnsupportedOperationException.class, results::clear); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void youngest_negative(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.youngest(-1); + assertThrows(IllegalArgumentException.class, () -> expireAfterAccess.youngest(-1)); } @Test(dataProvider = "caches") @@ -587,12 +583,11 @@ public void youngest_snapshot(Cache cache, CacheContext context, assertThat(youngest).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void youngestFunc_null(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.youngest(null); + assertThrows(NullPointerException.class, () -> expireAfterAccess.youngest(null)); } @Test(dataProvider = "caches") @@ -604,36 +599,34 @@ public void youngestFunc_nullResult(CacheContext context, } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void youngestFunc_throwsException(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { var expected = new IllegalStateException(); - try { - expireAfterAccess.youngest(stream -> { throw expected; }); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(e).isSameInstanceAs(expected); - } + var actual = assertThrows(IllegalStateException.class, () -> + expireAfterAccess.youngest(stream -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) public void youngestFunc_concurrentModification(Cache cache, CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.youngest(stream -> { - cache.put(context.absentKey(), context.absentValue()); - return stream.count(); + assertThrows(ConcurrentModificationException.class, () -> { + expireAfterAccess.youngest(stream -> { + cache.put(context.absentKey(), context.absentValue()); + throw assertThrows(ConcurrentModificationException.class, stream::count); + }); }); } - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "source already consumed or closed") + @Test(dataProvider = "caches") @CacheSpec(expireAfterAccess = Expire.ONE_MINUTE) public void youngestFunc_closed(CacheContext context, @ExpireAfterAccess FixedExpiration expireAfterAccess) { - expireAfterAccess.youngest(stream -> stream).forEach(e -> {}); + var stream = expireAfterAccess.youngest(identity()); + var exception = assertThrows(IllegalStateException.class, () -> stream.forEach(e -> {})); + assertThat(exception).hasMessageThat().isEqualTo("source already consumed or closed"); } @Test(dataProvider = "caches") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java index 88fd3cbc78..71daee2007 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterVarTest.java @@ -34,6 +34,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.times; @@ -275,16 +276,14 @@ public void replace_updated(Map map, CacheContext context) { assertThat(map).isExhaustivelyEmpty(); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void replace_expiryFails(Map map, CacheContext context) { - try { - when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) - .thenThrow(ExpirationException.class); - map.replace(context.firstKey(), context.absentValue()); - } finally { - assertThat(map).containsExactlyEntriesIn(context.original()); - } + when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> + map.replace(context.firstKey(), context.absentValue())); + assertThat(map).containsExactlyEntriesIn(context.original()); } @Test(dataProvider = "caches") @@ -300,136 +299,111 @@ public void replaceConditionally_updated(Map map, CacheContext context assertThat(map).isExhaustivelyEmpty(); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void replaceConditionally_expiryFails(Map map, CacheContext context) { - try { - when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) - .thenThrow(ExpirationException.class); - Int oldValue = context.original().get(context.firstKey()); - map.replace(context.firstKey(), oldValue, context.absentValue()); - } finally { - assertThat(map).containsExactlyEntriesIn(context.original()); - } + when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) + .thenThrow(ExpirationException.class); + Int oldValue = context.original().get(context.firstKey()); + assertThrows(ExpirationException.class, () -> + map.replace(context.firstKey(), oldValue, context.absentValue())); + assertThat(map).containsExactlyEntriesIn(context.original()); } /* --------------- Exceptional --------------- */ - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void getIfPresent_expiryFails(Cache cache, CacheContext context) { - try { - context.ticker().advance(1, TimeUnit.HOURS); - when(context.expiry().expireAfterRead(any(), any(), anyLong(), anyLong())) - .thenThrow(ExpirationException.class); - cache.getIfPresent(context.firstKey()); - } finally { - context.ticker().advance(-1, TimeUnit.HOURS); - assertThat(cache).containsExactlyEntriesIn(context.original()); - } + context.ticker().advance(1, TimeUnit.HOURS); + when(context.expiry().expireAfterRead(any(), any(), anyLong(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> cache.getIfPresent(context.firstKey())); + context.ticker().advance(-1, TimeUnit.HOURS); + assertThat(cache).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void get_expiryFails_create(Cache cache, CacheContext context) { - try { - context.ticker().advance(1, TimeUnit.HOURS); - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(ExpirationException.class); - cache.get(context.absentKey(), identity()); - } finally { - context.ticker().advance(-1, TimeUnit.HOURS); - assertThat(cache).containsExactlyEntriesIn(context.original()); - } + context.ticker().advance(1, TimeUnit.HOURS); + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> cache.get(context.absentKey(), identity())); + context.ticker().advance(-1, TimeUnit.HOURS); + assertThat(cache).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void get_expiryFails_read(Cache cache, CacheContext context) { - try { - context.ticker().advance(1, TimeUnit.HOURS); - when(context.expiry().expireAfterRead(any(), any(), anyLong(), anyLong())) - .thenThrow(ExpirationException.class); - cache.get(context.firstKey(), identity()); - } finally { - context.ticker().advance(-1, TimeUnit.HOURS); - assertThat(cache).containsExactlyEntriesIn(context.original()); - } + context.ticker().advance(1, TimeUnit.HOURS); + when(context.expiry().expireAfterRead(any(), any(), anyLong(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> cache.get(context.firstKey(), identity())); + context.ticker().advance(-1, TimeUnit.HOURS); + assertThat(cache).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void getAllPresent_expiryFails(Cache cache, CacheContext context) { - try { - context.ticker().advance(1, TimeUnit.HOURS); - when(context.expiry().expireAfterRead(any(), any(), anyLong(), anyLong())) - .thenThrow(ExpirationException.class); - cache.getAllPresent(context.firstMiddleLastKeys()); - } finally { - context.ticker().advance(-1, TimeUnit.HOURS); - assertThat(cache).containsExactlyEntriesIn(context.original()); - } + context.ticker().advance(1, TimeUnit.HOURS); + when(context.expiry().expireAfterRead(any(), any(), anyLong(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> + cache.getAllPresent(context.firstMiddleLastKeys())); + context.ticker().advance(-1, TimeUnit.HOURS); + assertThat(cache).containsExactlyEntriesIn(context.original()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void put_insert_expiryFails(Cache cache, CacheContext context) { - try { - context.ticker().advance(1, TimeUnit.HOURS); - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(ExpirationException.class); - cache.put(context.absentKey(), context.absentValue()); - } finally { - context.ticker().advance(-1, TimeUnit.HOURS); - assertThat(cache).containsExactlyEntriesIn(context.original()); - } + context.ticker().advance(1, TimeUnit.HOURS); + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> + cache.put(context.absentKey(), context.absentValue())); + context.ticker().advance(-1, TimeUnit.HOURS); + assertThat(cache).containsExactlyEntriesIn(context.original()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void put_insert_replaceExpired_expiryFails(Cache cache, CacheContext context, VarExpiration expireVariably) { var expectedDuration = expireVariably.getExpiresAfter(context.firstKey(), TimeUnit.NANOSECONDS); - try { - context.ticker().advance(1, TimeUnit.HOURS); - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(ExpirationException.class); - cache.put(context.firstKey(), context.absentValue()); - } finally { - context.ticker().advance(-1, TimeUnit.HOURS); - assertThat(cache).containsExactlyEntriesIn(context.original()); - var currentDuration = expireVariably.getExpiresAfter( - context.firstKey(), TimeUnit.NANOSECONDS); - assertThat(currentDuration).isEqualTo(expectedDuration); - } + context.ticker().advance(1, TimeUnit.HOURS); + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> + cache.put(context.firstKey(), context.absentValue())); + + context.ticker().advance(-1, TimeUnit.HOURS); + assertThat(cache).containsExactlyEntriesIn(context.original()); + var currentDuration = expireVariably.getExpiresAfter( + context.firstKey(), TimeUnit.NANOSECONDS); + assertThat(currentDuration).isEqualTo(expectedDuration); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void put_update_expiryFails(Cache cache, CacheContext context, VarExpiration expireVariably) { var expectedDuration = expireVariably.getExpiresAfter(context.firstKey(), TimeUnit.NANOSECONDS); - try { - context.ticker().advance(1, TimeUnit.HOURS); - when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) - .thenThrow(ExpirationException.class); - cache.put(context.firstKey(), context.absentValue()); - } finally { - context.ticker().advance(-1, TimeUnit.HOURS); - assertThat(cache).containsExactlyEntriesIn(context.original()); - var currentDuration = expireVariably.getExpiresAfter( - context.firstKey(), TimeUnit.NANOSECONDS); - assertThat(currentDuration).isEqualTo(expectedDuration); - } - } + context.ticker().advance(1, TimeUnit.HOURS); + when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> + cache.put(context.firstKey(), context.absentValue())); - static final class ExpirationException extends RuntimeException { - private static final long serialVersionUID = 1L; + context.ticker().advance(-1, TimeUnit.HOURS); + assertThat(cache).containsExactlyEntriesIn(context.original()); + var currentDuration = expireVariably.getExpiresAfter( + context.firstKey(), TimeUnit.NANOSECONDS); + assertThat(currentDuration).isEqualTo(expectedDuration); } /* --------------- Compute --------------- */ @@ -457,16 +431,14 @@ public void computeIfAbsent_present(Map map, CacheContext context) { verifyNoMoreInteractions(context.expiry()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void computeIfAbsent_expiryFails(Map map, CacheContext context) { - try { - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(ExpirationException.class); - map.computeIfAbsent(context.absentKey(), identity()); - } finally { - assertThat(map).containsExactlyEntriesIn(context.original()); - } + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> + map.computeIfAbsent(context.absentKey(), identity())); + assertThat(map).containsExactlyEntriesIn(context.original()); } @Test(dataProvider = "caches") @@ -499,16 +471,14 @@ public void computeIfPresent_present_sameInstance(Map map, CacheContex verifyNoMoreInteractions(context.expiry()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void computeIfPresent_expiryFails(Map map, CacheContext context) { - try { - when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) - .thenThrow(ExpirationException.class); - map.computeIfPresent(context.firstKey(), (k, v) -> v.negate()); - } finally { - assertThat(map).containsExactlyEntriesIn(context.original()); - } + when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> + map.computeIfPresent(context.firstKey(), (k, v) -> v.negate())); + assertThat(map).containsExactlyEntriesIn(context.original()); } @Test(dataProvider = "caches") @@ -670,11 +640,13 @@ public void getExpiresAfter_expired(Cache cache, assertThat(expireAfterVar.getExpiresAfter(context.absentKey(), TimeUnit.SECONDS)).isEmpty(); } - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) public void setExpiresAfter_negative(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.setExpiresAfter(context.absentKey(), Duration.ofMinutes(-2)); + var duration = Duration.ofMinutes(-2); + assertThrows(IllegalArgumentException.class, () -> + expireAfterVar.setExpiresAfter(context.absentKey(), duration)); } @Test(dataProvider = "caches") @@ -746,53 +718,53 @@ public void setExpiresAfter_expired(Cache cache, /* --------------- Policy: putIfAbsent --------------- */ @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void putIfAbsent_nullKey(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.putIfAbsent(null, Int.valueOf(2), 3, TimeUnit.SECONDS); + assertThrows(NullPointerException.class, () -> + expireAfterVar.putIfAbsent(null, Int.valueOf(2), 3, TimeUnit.SECONDS)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void putIfAbsent_nullValue(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.putIfAbsent(Int.valueOf(1), null, 3, TimeUnit.SECONDS); + assertThrows(NullPointerException.class, () -> + expireAfterVar.putIfAbsent(Int.valueOf(1), null, 3, TimeUnit.SECONDS)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void putIfAbsent_nullTimeUnit(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.putIfAbsent(Int.valueOf(1), Int.valueOf(2), 3, null); + assertThrows(NullPointerException.class, () -> + expireAfterVar.putIfAbsent(Int.valueOf(1), Int.valueOf(2), 3, null)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void putIfAbsent_negativeDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.putIfAbsent(Int.valueOf(1), Int.valueOf(2), -10, TimeUnit.SECONDS); + assertThrows(IllegalArgumentException.class, () -> + expireAfterVar.putIfAbsent(Int.valueOf(1), Int.valueOf(2), -10, TimeUnit.SECONDS)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void putIfAbsent_nullDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.putIfAbsent(Int.valueOf(1), Int.valueOf(2), null); + assertThrows(NullPointerException.class, () -> + expireAfterVar.putIfAbsent(Int.valueOf(1), Int.valueOf(2), null)); } @CheckNoStats @@ -847,43 +819,43 @@ public void putIfAbsent_present(Cache cache, /* --------------- Policy: put --------------- */ @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullKey(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.put(null, Int.valueOf(2), 3, TimeUnit.SECONDS); + assertThrows(NullPointerException.class, () -> + expireAfterVar.put(null, Int.valueOf(2), 3, TimeUnit.SECONDS)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullValue(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.put(Int.valueOf(1), null, 3, TimeUnit.SECONDS); + assertThrows(NullPointerException.class, () -> + expireAfterVar.put(Int.valueOf(1), null, 3, TimeUnit.SECONDS)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullTimeUnit(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.put(Int.valueOf(1), Int.valueOf(2), 3, null); + assertThrows(NullPointerException.class, () -> + expireAfterVar.put(Int.valueOf(1), Int.valueOf(2), 3, null)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void put_negativeDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.put(Int.valueOf(1), Int.valueOf(2), -10, TimeUnit.SECONDS); + assertThrows(IllegalArgumentException.class, () -> + expireAfterVar.put(Int.valueOf(1), Int.valueOf(2), -10, TimeUnit.SECONDS)); } @CheckNoStats @@ -900,13 +872,13 @@ public void put_excessiveDuration(Cache cache, } @CheckNoStats - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void put_nullDuration(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.put(Int.valueOf(1), Int.valueOf(2), null); + assertThrows(NullPointerException.class, () -> + expireAfterVar.put(Int.valueOf(1), Int.valueOf(2), null)); } @Test(dataProvider = "caches") @@ -947,29 +919,30 @@ public void put_replace(Cache cache, /* --------------- Policy: compute --------------- */ - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS, removalListener = {Listener.DISABLED, Listener.REJECTING}) public void compute_nullKey(CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.compute(null, (key, value) -> key.negate(), Duration.ZERO); + assertThrows(NullPointerException.class, () -> + expireAfterVar.compute(null, (key, value) -> key.negate(), Duration.ZERO)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS, removalListener = {Listener.DISABLED, Listener.REJECTING}) public void compute_nullMappingFunction(CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.compute(Int.valueOf(1), null, Duration.ZERO); + assertThrows(NullPointerException.class, () -> + expireAfterVar.compute(Int.valueOf(1), null, Duration.ZERO)); } @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS, removalListener = {Listener.DISABLED, Listener.REJECTING}) public void compute_negativeDuration( CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.compute(Int.valueOf(1), (key, value) -> key.negate(), Duration.ofMinutes(-1)); + var duration = Duration.ofMinutes(-1); + assertThrows(IllegalArgumentException.class, () -> + expireAfterVar.compute(Int.valueOf(1), (key, value) -> key.negate(), duration)); } @Test(dataProvider = "caches") @@ -1040,15 +1013,13 @@ public void compute_pingpong(CacheContext context, VarExpiration expir } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.MOCKITO) public void compute_error(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - try { + assertThrows(IllegalStateException.class, () -> { expireAfterVar.compute(context.absentKey(), (key, value) -> { throw new IllegalStateException(); }, Duration.ofDays(1)); - Assert.fail(); - } catch (IllegalStateException e) { /* ignored */ } + }); verifyNoInteractions(context.expiry()); assertThat(cache).containsExactlyEntriesIn(context.original()); @@ -1346,73 +1317,62 @@ public void compute_writeTime(Cache cache, } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) public void compute_absent_error(CacheContext context, VarExpiration expireAfterVar) { context.ticker().advance(2, TimeUnit.MINUTES); - try { + assertThrows(IllegalStateException.class, () -> { expireAfterVar.compute(context.firstKey(), (key, value) -> { throw new IllegalStateException(); }, Duration.ofDays(1)); - Assert.fail(); - } catch (IllegalStateException expected) {} - + }); assertThat(expireAfterVar.getExpiresAfter(context.firstKey())).isEmpty(); } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, compute = Compute.SYNC, expiry = CacheExpiry.WRITE, expiryTime = Expire.ONE_MINUTE) public void compute_present_error(CacheContext context, VarExpiration expireAfterVar) { context.ticker().advance(30, TimeUnit.SECONDS); var variable = expireAfterVar.getExpiresAfter(context.firstKey()); - try { + assertThrows(IllegalStateException.class, () -> { expireAfterVar.compute(context.firstKey(), (key, value) -> { throw new IllegalStateException(); }, Duration.ofDays(1)); - Assert.fail(); - } catch (IllegalStateException expected) {} - + }); assertThat(variable).isEqualTo(expireAfterVar.getExpiresAfter(context.firstKey())); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void compute_absent_expiryFails(Map map, CacheContext context) { - try { - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(ExpirationException.class); - map.compute(context.absentKey(), (k, v) -> k); - } finally { - assertThat(map).containsExactlyEntriesIn(context.original()); - } + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> map.compute(context.absentKey(), (k, v) -> k)); + assertThat(map).containsExactlyEntriesIn(context.original()); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO) - @Test(dataProvider = "caches", expectedExceptions = ExpirationException.class) public void compute_present_expiryFails(Map map, CacheContext context) { - try { - when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) - .thenThrow(ExpirationException.class); - map.compute(context.firstKey(), (k, v) -> v.negate()); - } finally { - assertThat(map).containsExactlyEntriesIn(context.original()); - } + when(context.expiry().expireAfterUpdate(any(), any(), anyLong(), anyLong())) + .thenThrow(ExpirationException.class); + assertThrows(ExpirationException.class, () -> + map.compute(context.firstKey(), (k, v) -> v.negate())); + assertThat(map).containsExactlyEntriesIn(context.original()); } /* --------------- Policy: oldest --------------- */ + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void oldest_unmodifiable(CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.oldest(Integer.MAX_VALUE).clear(); + var results = expireAfterVar.oldest(Integer.MAX_VALUE); + assertThrows(UnsupportedOperationException.class, results::clear); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void oldest_negative(CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.oldest(-1); + assertThrows(IllegalArgumentException.class, () -> expireAfterVar.oldest(-1)); } @Test(dataProvider = "caches") @@ -1445,11 +1405,10 @@ public void oldest_snapshot(Cache cache, assertThat(oldest).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void oldestFunc_null(CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.oldest(null); + assertThrows(NullPointerException.class, () -> expireAfterVar.oldest(null)); } @Test(dataProvider = "caches") @@ -1460,36 +1419,34 @@ public void oldestFunc_nullResult(CacheContext context, VarExpiration } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) public void oldestFunc_throwsException(CacheContext context, VarExpiration expireAfterVar) { var expected = new IllegalStateException(); - try { - expireAfterVar.oldest(stream -> { throw expected; }); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(e).isSameInstanceAs(expected); - } + var actual = assertThrows(IllegalStateException.class, () -> + expireAfterVar.oldest(stream -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) public void oldestFunc_concurrentModification(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.oldest(stream -> { - context.ticker().advance(1, TimeUnit.NANOSECONDS); - cache.put(context.absentKey(), context.absentValue()); - return stream.count(); + assertThrows(ConcurrentModificationException.class, () -> { + expireAfterVar.oldest(stream -> { + context.ticker().advance(1, TimeUnit.NANOSECONDS); + cache.put(context.absentKey(), context.absentValue()); + throw assertThrows(ConcurrentModificationException.class, stream::count); + }); }); } - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "source already consumed or closed") + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) public void oldestFunc_closed(CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.oldest(stream -> stream).forEach(e -> {}); + var stream = expireAfterVar.oldest(identity()); + var exception = assertThrows(IllegalStateException.class, () -> stream.forEach(e -> {})); + assertThat(exception).hasMessageThat().isEqualTo("source already consumed or closed"); } @Test(dataProvider = "caches") @@ -1544,17 +1501,17 @@ public void oldestFunc_metadata_expiresInTraversal(CacheContext context, /* --------------- Policy: youngest --------------- */ + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void youngest_unmodifiable(CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.youngest(Integer.MAX_VALUE).clear(); + var results = expireAfterVar.youngest(Integer.MAX_VALUE); + assertThrows(UnsupportedOperationException.class, results::clear); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void youngest_negative(CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.youngest(-1); + assertThrows(IllegalArgumentException.class, () -> expireAfterVar.youngest(-1)); } @Test(dataProvider = "caches") @@ -1588,11 +1545,10 @@ public void youngest_snapshot(Cache cache, assertThat(youngest).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void youngestFunc_null(CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.youngest(null); + assertThrows(NullPointerException.class, () -> expireAfterVar.youngest(null)); } @Test(dataProvider = "caches") @@ -1604,36 +1560,34 @@ public void youngestFunc_nullResult(CacheContext context, } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(expiry = CacheExpiry.ACCESS) public void youngestFunc_throwsException(CacheContext context, VarExpiration expireAfterVar) { var expected = new IllegalStateException(); - try { - expireAfterVar.youngest(stream -> { throw expected; }); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(e).isSameInstanceAs(expected); - } + var actual = assertThrows(IllegalStateException.class, () -> + expireAfterVar.youngest(stream -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) public void youngestFunc_concurrentModification(Cache cache, CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.youngest(stream -> { - context.ticker().advance(1, TimeUnit.NANOSECONDS); - cache.put(context.absentKey(), context.absentValue()); - return stream.count(); + assertThrows(ConcurrentModificationException.class, () -> { + expireAfterVar.youngest(stream -> { + context.ticker().advance(1, TimeUnit.NANOSECONDS); + cache.put(context.absentKey(), context.absentValue()); + throw assertThrows(ConcurrentModificationException.class, stream::count); + }); }); } - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "source already consumed or closed") + @Test(dataProvider = "caches") @CacheSpec(expiry = CacheExpiry.ACCESS) public void youngestFunc_closed(CacheContext context, VarExpiration expireAfterVar) { - expireAfterVar.youngest(stream -> stream).forEach(e -> {}); + var stream = expireAfterVar.youngest(identity()); + var exception = assertThrows(IllegalStateException.class, () -> stream.forEach(e -> {})); + assertThat(exception).hasMessageThat().isEqualTo("source already consumed or closed"); } @Test(dataProvider = "caches") @@ -1658,8 +1612,7 @@ public void youngestFunc_full(Cache cache, @Test(dataProvider = "caches") @CacheSpec(population = {Population.PARTIAL, Population.FULL}, - removalListener = { Listener.DISABLED, Listener.REJECTING }, - expiry = CacheExpiry.ACCESS) + removalListener = { Listener.DISABLED, Listener.REJECTING }, expiry = CacheExpiry.ACCESS) public void youngestFunc_order(CacheContext context, VarExpiration expireAfterVar) { var youngest = expireAfterVar.youngest( stream -> stream.map(Map.Entry::getKey).collect(toImmutableList())); @@ -1686,4 +1639,8 @@ public void youngestFunc_metadata_expiresInTraversal(CacheContext context, assertThat(context.cache()).hasSize(context.initialSize()); assertThat(entries).hasSize(1); } + + static final class ExpirationException extends RuntimeException { + private static final long serialVersionUID = 1L; + } } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterWriteTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterWriteTest.java index 99431a3e0d..41cbaa2943 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterWriteTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ExpireAfterWriteTest.java @@ -21,12 +21,14 @@ import static com.github.benmanes.caffeine.cache.testing.CacheSpec.Expiration.AFTER_WRITE; import static com.github.benmanes.caffeine.cache.testing.CacheSpec.Expiration.VARIABLE; import static com.github.benmanes.caffeine.cache.testing.CacheSubject.assertThat; +import static com.github.benmanes.caffeine.testing.FutureSubject.assertThat; import static com.github.benmanes.caffeine.testing.MapSubject.assertThat; import static com.google.common.base.Functions.identity; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; +import static org.junit.Assert.assertThrows; import static uk.org.lidalia.slf4jext.Level.WARN; import java.time.Duration; @@ -37,7 +39,6 @@ import java.util.concurrent.TimeUnit; import java.util.function.Function; -import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -72,14 +73,15 @@ public final class ExpireAfterWriteTest { /* --------------- Cache --------------- */ @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expireAfterWrite = { Expire.DISABLED, Expire.ONE_MINUTE }, expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE, population = { Population.PARTIAL, Population.FULL }) public void getIfPresent(Cache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.getIfPresent(context.firstKey()); + var value = cache.getIfPresent(context.firstKey()); + assertThat(value).isEqualTo(context.original().get(context.firstKey())); + context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache.getIfPresent(context.firstKey())).isNull(); @@ -90,16 +92,18 @@ public void getIfPresent(Cache cache, CacheContext context) { } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(population = { Population.PARTIAL, Population.FULL }, mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expireAfterWrite = Expire.ONE_MINUTE, expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE) public void get(Cache cache, CacheContext context) { Function mappingFunction = context.original()::get; context.ticker().advance(30, TimeUnit.SECONDS); - cache.get(context.firstKey(), mappingFunction); + var value = cache.get(context.firstKey(), mappingFunction); + assertThat(value).isEqualTo(context.original().get(context.firstKey())); + context.ticker().advance(45, TimeUnit.SECONDS); - cache.get(context.lastKey(), mappingFunction); // recreated + var recreated = cache.get(context.lastKey(), mappingFunction); + assertThat(recreated).isEqualTo(context.lastKey().negate()); cache.cleanUp(); assertThat(cache).hasSize(1); @@ -108,13 +112,15 @@ public void get(Cache cache, CacheContext context) { } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(population = { Population.PARTIAL, Population.FULL }, mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expireAfterWrite = Expire.ONE_MINUTE, expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE) public void getAllPresent(Cache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.getAllPresent(context.firstMiddleLastKeys()); + var results = cache.getAllPresent(context.firstMiddleLastKeys()); + assertThat(results).containsExactlyEntriesIn(Maps.filterKeys( + context.original(), context.firstMiddleLastKeys()::contains)); + context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache.getAllPresent(context.firstMiddleLastKeys())).isExhaustivelyEmpty(); @@ -150,14 +156,13 @@ public void getAll(Cache cache, CacheContext context) { /* --------------- LoadingCache --------------- */ @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(population = { Population.PARTIAL, Population.FULL }, mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expireAfterWrite = Expire.ONE_MINUTE, expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE) public void get_loading(LoadingCache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.get(context.firstKey()); - cache.get(context.absentKey()); + assertThat(cache.get(context.firstKey())).isEqualTo(context.original().get(context.firstKey())); + assertThat(cache.get(context.absentKey())).isEqualTo(context.absentKey().negate()); context.ticker().advance(45, TimeUnit.SECONDS); cache.cleanUp(); @@ -197,7 +202,8 @@ public void getAll_loading(LoadingCache cache, CacheContext context) { expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE) public void getIfPresent(AsyncCache cache, CacheContext context) { context.ticker().advance(30, TimeUnit.SECONDS); - cache.getIfPresent(context.firstKey()).join(); + assertThat(cache.getIfPresent(context.firstKey())) + .succeedsWith(context.original().get(context.firstKey())); context.ticker().advance(45, TimeUnit.SECONDS); assertThat(cache).doesNotContainKey(context.firstKey()); assertThat(cache).doesNotContainKey(context.lastKey()); @@ -230,14 +236,14 @@ public void putIfAbsent(Map map, CacheContext context) { @CheckNoStats @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(population = Population.FULL, expireAfterWrite = Expire.ONE_MINUTE) public void getIfPresentQuietly(Cache cache, CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { var original = expireAfterWrite.ageOf(context.firstKey()).orElseThrow(); var advancement = Duration.ofSeconds(30); context.ticker().advance(advancement); - cache.policy().getIfPresentQuietly(context.firstKey()); + assertThat(cache.policy().getIfPresentQuietly(context.firstKey())) + .isEqualTo(context.original().get(context.firstKey())); var current = expireAfterWrite.ageOf(context.firstKey()).orElseThrow(); assertThat(current.minus(advancement)).isEqualTo(original); } @@ -256,11 +262,12 @@ public void getExpiresAfter_duration(CacheContext context, assertThat(expireAfterWrite.getExpiresAfter()).isEqualTo(Duration.ofMinutes(1)); } - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void setExpiresAfter_negative(Cache cache, CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.setExpiresAfter(Duration.ofMinutes(-2)); + assertThrows(IllegalArgumentException.class, () -> + expireAfterWrite.setExpiresAfter(Duration.ofMinutes(-2))); } @Test(dataProvider = "caches") @@ -340,19 +347,19 @@ public void ageOf_expired(Cache cache, CacheContext context, /* --------------- Policy: oldest --------------- */ + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void oldest_unmodifiable(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.oldest(Integer.MAX_VALUE).clear(); + var results = expireAfterWrite.oldest(Integer.MAX_VALUE); + assertThrows(UnsupportedOperationException.class, results::clear); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void oldest_negative(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.oldest(-1); + assertThrows(IllegalArgumentException.class, () -> expireAfterWrite.oldest(-1)); } @Test(dataProvider = "caches") @@ -389,12 +396,11 @@ public void oldest_snapshot(Cache cache, CacheContext context, assertThat(oldest).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void oldestFunc_null(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.oldest(null); + assertThrows(NullPointerException.class, () -> expireAfterWrite.oldest(null)); } @Test(dataProvider = "caches") @@ -406,36 +412,34 @@ public void oldestFunc_nullResult(CacheContext context, } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void oldestFunc_throwsException(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { var expected = new IllegalStateException(); - try { - expireAfterWrite.oldest(stream -> { throw expected; }); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(e).isSameInstanceAs(expected); - } + var actual = assertThrows(IllegalStateException.class, () -> + expireAfterWrite.oldest(stream -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void oldestFunc_concurrentModification(Cache cache, CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.oldest(stream -> { - cache.put(context.absentKey(), context.absentValue()); - return stream.count(); + assertThrows(ConcurrentModificationException.class, () -> { + expireAfterWrite.oldest(stream -> { + cache.put(context.absentKey(), context.absentValue()); + throw assertThrows(ConcurrentModificationException.class, stream::count); + }); }); } - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "source already consumed or closed") + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void oldestFunc_closed(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.oldest(stream -> stream).forEach(e -> {}); + var stream = expireAfterWrite.oldest(identity()); + var exception = assertThrows(IllegalStateException.class, () -> stream.forEach(e -> {})); + assertThat(exception).hasMessageThat().isEqualTo("source already consumed or closed"); } @Test(dataProvider = "caches") @@ -491,19 +495,19 @@ public void oldestFunc_metadata_expiresInTraversal(CacheContext context, /* --------------- Policy: youngest --------------- */ + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void youngest_unmodifiable(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.youngest(Integer.MAX_VALUE).clear(); + var results = expireAfterWrite.youngest(Integer.MAX_VALUE); + assertThrows(UnsupportedOperationException.class, results::clear); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) public void youngest_negative(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.youngest(-1); + assertThrows(IllegalArgumentException.class, () -> expireAfterWrite.youngest(-1)); } @Test(dataProvider = "caches") @@ -541,12 +545,11 @@ public void youngest_snapshot(Cache cache, CacheContext context, assertThat(youngest).containsExactlyEntriesIn(context.original()); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void youngestFunc_null(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.youngest(null); + assertThrows(NullPointerException.class, () -> expireAfterWrite.youngest(null)); } @Test(dataProvider = "caches") @@ -558,36 +561,34 @@ public void youngestFunc_nullResult(CacheContext context, } @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void youngestFunc_throwsException(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { var expected = new IllegalStateException(); - try { - expireAfterWrite.youngest(stream -> { throw expected; }); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(e).isSameInstanceAs(expected); - } + var actual = assertThrows(IllegalStateException.class, () -> + expireAfterWrite.youngest(stream -> { throw expected; })); + assertThat(actual).isSameInstanceAs(expected); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = ConcurrentModificationException.class) + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void youngestFunc_concurrentModification(Cache cache, CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.youngest(stream -> { - cache.put(context.absentKey(), context.absentValue()); - return stream.count(); + assertThrows(ConcurrentModificationException.class, () -> { + expireAfterWrite.youngest(stream -> { + cache.put(context.absentKey(), context.absentValue()); + throw assertThrows(ConcurrentModificationException.class, stream::count); + }); }); } - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class, - expectedExceptionsMessageRegExp = "source already consumed or closed") + @Test(dataProvider = "caches") @CacheSpec(expireAfterWrite = Expire.ONE_MINUTE) public void youngestFunc_closed(CacheContext context, @ExpireAfterWrite FixedExpiration expireAfterWrite) { - expireAfterWrite.youngest(stream -> stream).forEach(e -> {}); + var stream = expireAfterWrite.youngest(identity()); + var exception = assertThrows(IllegalStateException.class, () -> stream.forEach(e -> {})); + assertThat(exception).hasMessageThat().isEqualTo("source already consumed or closed"); } @Test(dataProvider = "caches") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/FrequencySketchTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/FrequencySketchTest.java index bdd9d11eda..c99ca0c9f4 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/FrequencySketchTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/FrequencySketchTest.java @@ -16,6 +16,7 @@ package com.github.benmanes.caffeine.cache; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import java.util.concurrent.ThreadLocalRandom; @@ -38,9 +39,9 @@ public void construct() { assertThat(sketch.frequency(item)).isEqualTo(0); } - @Test(dataProvider = "sketch", expectedExceptions = IllegalArgumentException.class) + @Test(dataProvider = "sketch") public void ensureCapacity_negative(FrequencySketch sketch) { - sketch.ensureCapacity(-1); + assertThrows(IllegalArgumentException.class, () -> sketch.ensureCapacity(-1)); } @Test(dataProvider = "sketch") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/InternerTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/InternerTest.java index b77602ff06..c10f6e0495 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/InternerTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/InternerTest.java @@ -20,6 +20,7 @@ import static com.github.benmanes.caffeine.testing.MapSubject.assertThat; import static com.google.common.truth.Truth.assertAbout; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import java.lang.ref.WeakReference; import java.util.Arrays; @@ -63,10 +64,9 @@ public static TestSuite suite() { .createTestSuite(); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "interners", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "interners") public void intern_null(Interner interner) { - interner.intern(null); + assertThrows(NullPointerException.class, () -> interner.intern(null)); } @Test(dataProvider = "interners") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LinkedDequeTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LinkedDequeTest.java index 29d397ce8b..7e071ed234 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LinkedDequeTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LinkedDequeTest.java @@ -18,6 +18,7 @@ import static com.github.benmanes.caffeine.testing.CollectionSubject.assertThat; import static com.google.common.collect.Iterators.elementsEqual; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import java.util.ArrayList; import java.util.Collection; @@ -218,9 +219,9 @@ public void peekLast_whenPopulated(AbstractLinkedDeque deque) { /* --------------- Get --------------- */ - @Test(dataProvider = "empty", expectedExceptions = NoSuchElementException.class) + @Test(dataProvider = "empty") public void getFirst_whenEmpty(LinkedDeque deque) { - deque.getFirst(); + assertThrows(NoSuchElementException.class, deque::getFirst); } @Test(dataProvider = "full") @@ -232,9 +233,9 @@ public void getFirst_whenPopulated(AbstractLinkedDeque deque) { assertThat(deque.getFirst()).isSameInstanceAs(first); } - @Test(dataProvider = "empty", expectedExceptions = NoSuchElementException.class) + @Test(dataProvider = "empty") public void getLast_whenEmpty(LinkedDeque deque) { - deque.getLast(); + assertThrows(NoSuchElementException.class, deque::getLast); } @Test(dataProvider = "full") @@ -248,9 +249,9 @@ public void getLast_whenPopulated(AbstractLinkedDeque deque) { /* --------------- Element --------------- */ - @Test(dataProvider = "empty", expectedExceptions = NoSuchElementException.class) + @Test(dataProvider = "empty") public void element_whenEmpty(LinkedDeque deque) { - deque.element(); + assertThrows(NoSuchElementException.class, deque::element); } @Test(dataProvider = "full") @@ -379,9 +380,9 @@ public void addFirst_whenPopulated(LinkedDeque deque) { assertThat(deque).hasSize(SIZE + 1); } - @Test(dataProvider = "full", expectedExceptions = IllegalArgumentException.class) + @Test(dataProvider = "full") public void addFirst_whenLinked(LinkedDeque deque) { - deque.addFirst(deque.peek()); + assertThrows(IllegalArgumentException.class, () -> deque.addFirst(deque.peek())); } @Test(dataProvider = "empty") @@ -402,9 +403,9 @@ public void addLast_whenPopulated(LinkedDeque deque) { assertThat(deque).hasSize(SIZE + 1); } - @Test(dataProvider = "full", expectedExceptions = IllegalArgumentException.class) + @Test(dataProvider = "full") public void addLast_whenLinked(LinkedDeque deque) { - deque.addLast(deque.peek()); + assertThrows(IllegalArgumentException.class, () -> deque.addLast(deque.peek())); } @Test(dataProvider = "empty") @@ -497,9 +498,9 @@ public void pollLast_toEmpty(LinkedDeque deque) { /* --------------- Remove --------------- */ - @Test(dataProvider = "empty", expectedExceptions = NoSuchElementException.class) + @Test(dataProvider = "empty") public void remove_whenEmpty(LinkedDeque deque) { - deque.remove(); + assertThrows(NoSuchElementException.class, deque::remove); } @Test(dataProvider = "full") @@ -542,9 +543,9 @@ public void removeElement_toEmpty(LinkedDeque deque) { assertThat(deque).isExhaustivelyEmpty(); } - @Test(dataProvider = "empty", expectedExceptions = NoSuchElementException.class) + @Test(dataProvider = "empty") public void removeFirst_whenEmpty(LinkedDeque deque) { - deque.removeFirst(); + assertThrows(NoSuchElementException.class, deque::removeFirst); } @Test(dataProvider = "full") @@ -564,9 +565,9 @@ public void removeFirst_toEmpty(LinkedDeque deque) { assertThat(deque).isExhaustivelyEmpty(); } - @Test(dataProvider = "empty", expectedExceptions = NoSuchElementException.class) + @Test(dataProvider = "empty") public void removeLast_whenEmpty(LinkedDeque deque) { - deque.removeLast(); + assertThrows(NoSuchElementException.class, deque::removeLast); } @Test(dataProvider = "full") @@ -672,14 +673,14 @@ public void push_whenPopulated(LinkedDeque deque) { assertThat(deque).hasSize(SIZE + 1); } - @Test(dataProvider = "full", expectedExceptions = IllegalArgumentException.class) + @Test(dataProvider = "full") public void push_whenLinked(LinkedDeque deque) { - deque.push(deque.peek()); + assertThrows(IllegalArgumentException.class, () -> deque.push(deque.peek())); } - @Test(dataProvider = "empty", expectedExceptions = NoSuchElementException.class) + @Test(dataProvider = "empty") public void pop_whenEmpty(LinkedDeque deque) { - deque.pop(); + assertThrows(NoSuchElementException.class, deque::pop); } @Test(dataProvider = "full") @@ -701,9 +702,10 @@ public void pop_toEmpty(LinkedDeque deque) { /* --------------- Iterators --------------- */ - @Test(dataProvider = "empty", expectedExceptions = NoSuchElementException.class) + @Test(dataProvider = "empty") public void iterator_noMoreElements(LinkedDeque deque) { - deque.iterator().next(); + var iterator = deque.iterator(); + assertThrows(NoSuchElementException.class, iterator::next); } @Test(dataProvider = "empty") @@ -737,17 +739,18 @@ public void iterator_removal(LinkedDeque deque) { assertThat(deque).hasSize(SIZE - 1); } - @Test(dataProvider = "full", expectedExceptions = IllegalStateException.class) + @Test(dataProvider = "full") public void iterator_removal_exception(LinkedDeque deque) { var iterator = deque.iterator(); iterator.next(); iterator.remove(); - iterator.remove(); + assertThrows(IllegalStateException.class, iterator::remove); } - @Test(dataProvider = "empty", expectedExceptions = NoSuchElementException.class) + @Test(dataProvider = "empty") public void descendingIterator_noMoreElements(LinkedDeque deque) { - deque.descendingIterator().next(); + var iterator = deque.descendingIterator(); + assertThrows(NoSuchElementException.class, iterator::next); } @Test(dataProvider = "empty") @@ -800,9 +803,10 @@ public void concat_peek(LinkedDeque deque) { assertThat(iterator.peek()).isNull(); } - @Test(dataProvider = "empty", expectedExceptions = NoSuchElementException.class) + @Test(dataProvider = "empty") public void concat_noMoreElements(LinkedDeque deque) { - PeekingIterator.concat(deque.iterator(), deque.iterator()).next(); + var iterator = PeekingIterator.concat(deque.iterator(), deque.iterator()); + assertThrows(NoSuchElementException.class, iterator::next); } @Test(dataProvider = "full") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java index 7c29a86699..1e27c99259 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LoadingCacheTest.java @@ -33,6 +33,7 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static java.util.function.Function.identity; +import static org.junit.Assert.assertThrows; import static uk.org.lidalia.slf4jext.Level.TRACE; import static uk.org.lidalia.slf4jext.Level.WARN; @@ -49,7 +50,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -72,6 +72,7 @@ import com.github.benmanes.caffeine.cache.testing.CheckNoStats; import com.github.benmanes.caffeine.testing.Int; import com.github.valfirst.slf4jtest.TestLoggerFactory; +import com.google.common.cache.CacheLoader.InvalidCacheLoadException; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.primitives.Ints; @@ -85,18 +86,16 @@ */ @CheckMaxLogLevel(WARN) @Listeners(CacheValidationListener.class) -@SuppressWarnings("FutureReturnValueIgnored") @Test(dataProviderClass = CacheProvider.class) public final class LoadingCacheTest { /* --------------- get --------------- */ @CacheSpec + @Test(dataProvider = "caches") @CheckNoEvictions @CheckNoStats - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void get_null(LoadingCache cache, CacheContext context) { - cache.get(null); + assertThrows(NullPointerException.class, () -> cache.get(null)); } @CheckNoEvictions @@ -108,45 +107,31 @@ public void get_absent_null(LoadingCache cache, CacheContext context) } @CheckNoEvictions - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(loader = Loader.EXCEPTIONAL) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void get_absent_throwsException(LoadingCache cache, CacheContext context) { - try { - cache.get(context.absentKey()); - } finally { - assertThat(context).stats().hits(0).misses(1).success(0).failures(1); - } + assertThrows(IllegalStateException.class, () -> cache.get(context.absentKey())); + assertThat(context).stats().hits(0).misses(1).success(0).failures(1); } @CheckNoEvictions @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = Loader.CHECKED_EXCEPTIONAL) public void get_absent_throwsCheckedException( LoadingCache cache, CacheContext context) { - try { - cache.get(context.absentKey()); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); - assertThat(context).stats().hits(0).misses(1).success(0).failures(1); - } + var exception = assertThrows(CompletionException.class, () -> cache.get(context.absentKey())); + assertThat(exception).hasCauseThat().isInstanceOf(ExecutionException.class); + assertThat(context).stats().hits(0).misses(1).success(0).failures(1); } @CheckNoEvictions @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(compute = Compute.SYNC, loader = Loader.INTERRUPTED) public void get_absent_interrupted(LoadingCache cache, CacheContext context) { - try { - cache.get(context.absentKey()); - Assert.fail(); - } catch (CompletionException e) { - assertThat(Thread.interrupted()).isTrue(); - assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); - assertThat(context).stats().hits(0).misses(1).success(0).failures(1); - } + var exception = assertThrows(CompletionException.class, () -> cache.get(context.absentKey())); + assertThat(Thread.interrupted()).isTrue(); + assertThat(exception).hasCauseThat().isInstanceOf(InterruptedException.class); + assertThat(context).stats().hits(0).misses(1).success(0).failures(1); } @CacheSpec @@ -171,20 +156,19 @@ public void get_present(LoadingCache cache, CacheContext context) { /* --------------- getAll --------------- */ @CheckNoEvictions - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_null(LoadingCache cache, CacheContext context) { - cache.getAll(null); + assertThrows(NullPointerException.class, () -> cache.getAll(null)); } @CheckNoEvictions - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(loader = { Loader.NEGATIVE, Loader.BULK_NEGATIVE }, removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void getAll_iterable_nullKey(LoadingCache cache, CacheContext context) { - cache.getAll(Collections.singletonList(null)); + List keys = Collections.singletonList(null); + assertThrows(NullPointerException.class, () -> cache.getAll(keys)); } @CheckNoEvictions @@ -197,19 +181,18 @@ public void getAll_iterable_empty(LoadingCache cache, CacheContext con } @CheckNoEvictions - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(loader = Loader.BULK_MODIFY_KEYS) - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) public void getAll_immutable_keys(LoadingCache cache, CacheContext context) { - cache.getAll(context.absentKeys()); + assertThrows(UnsupportedOperationException.class, () -> cache.getAll(context.absentKeys())); } @CacheSpec @CheckNoEvictions - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void getAll_immutable_result(LoadingCache cache, CacheContext context) { - cache.getAll(context.firstMiddleLastKeys()).clear(); + var results = cache.getAll(context.firstMiddleLastKeys()); + assertThrows(UnsupportedOperationException.class, results::clear); } @CacheSpec @@ -229,78 +212,62 @@ public void getAll_absent_null(LoadingCache cache, CacheContext contex } @CheckNoEvictions - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(loader = Loader.BULK_NULL) - @Test(dataProvider = "caches", expectedExceptions = Exception.class) public void getAll_absent_bulkNull(LoadingCache cache, CacheContext context) { - cache.getAll(context.absentKeys()); + var exception = assertThrows(Exception.class, () -> cache.getAll(context.absentKeys())); + assertThat(exception).isInstanceOf( + context.isGuava() ? InvalidCacheLoadException.class : NullPointerException.class); } @CheckNoEvictions - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(loader = { Loader.EXCEPTIONAL, Loader.BULK_EXCEPTIONAL }) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void getAll_absent_throwsExecption(LoadingCache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys()); - } finally { - int misses = context.absentKeys().size(); - int loadFailures = (context.loader().isBulk() || context.isSync()) ? 1 : misses; - assertThat(context).stats().hits(0).misses(misses).success(0).failures(loadFailures); - } + assertThrows(IllegalStateException.class, () -> cache.getAll(context.absentKeys())); + int misses = context.absentKeys().size(); + int loadFailures = (context.loader().isBulk() || context.isSync()) ? 1 : misses; + assertThat(context).stats().hits(0).misses(misses).success(0).failures(loadFailures); } @CheckNoEvictions @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = { Loader.CHECKED_EXCEPTIONAL, Loader.BULK_CHECKED_EXCEPTIONAL }) public void getAll_absent_throwsCheckedExecption( LoadingCache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys()); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); - - int misses = context.absentKeys().size(); - int loadFailures = (context.loader().isBulk() || context.isSync()) ? 1 : misses; - assertThat(context).stats().hits(0).misses(misses).success(0).failures(loadFailures); - } + var e = assertThrows(CompletionException.class, () -> cache.getAll(context.absentKeys())); + assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); + + int misses = context.absentKeys().size(); + int loadFailures = (context.loader().isBulk() || context.isSync()) ? 1 : misses; + assertThat(context).stats().hits(0).misses(misses).success(0).failures(loadFailures); } @CheckNoEvictions - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(loader = { Loader.EXCEPTIONAL, Loader.BULK_EXCEPTIONAL }) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void getAll_absent_throwsExecption_iterable( LoadingCache cache, CacheContext context) { - try { - cache.getAll(() -> context.absentKeys().iterator()); - } finally { - int misses = context.absentKeys().size(); - int loadFailures = (context.loader().isBulk() || context.isSync()) ? 1 : misses; - assertThat(context).stats().hits(0).misses(misses).success(0).failures(loadFailures); - } + assertThrows(IllegalStateException.class, () -> + cache.getAll(() -> context.absentKeys().iterator())); + int misses = context.absentKeys().size(); + int loadFailures = (context.loader().isBulk() || context.isSync()) ? 1 : misses; + assertThat(context).stats().hits(0).misses(misses).success(0).failures(loadFailures); } @CheckNoEvictions @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(loader = { Loader.INTERRUPTED, Loader.BULK_INTERRUPTED }) public void getAll_absent_interrupted(LoadingCache cache, CacheContext context) { - try { - cache.getAll(context.absentKeys()); - Assert.fail(); - } catch (CompletionException e) { - if (context.isSync()) { - assertThat(Thread.interrupted()).isTrue(); - } - assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); - - int misses = context.absentKeys().size(); - int loadFailures = (context.loader().isBulk() || context.isSync()) ? 1 : misses; - assertThat(context).stats().hits(0).misses(misses).success(0).failures(loadFailures); + var e = assertThrows(CompletionException.class, () -> cache.getAll(context.absentKeys())); + if (context.isSync()) { + assertThat(Thread.interrupted()).isTrue(); } + assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); + + int misses = context.absentKeys().size(); + int loadFailures = (context.loader().isBulk() || context.isSync()) ? 1 : misses; + assertThat(context).stats().hits(0).misses(misses).success(0).failures(loadFailures); } @CheckNoEvictions @@ -462,10 +429,10 @@ class Key { /* --------------- refresh --------------- */ @CheckNoEvictions + @Test(dataProvider = "caches") @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void refresh_null(LoadingCache cache, CacheContext context) { - cache.refresh(null); + assertThrows(NullPointerException.class, () -> cache.refresh(null)); } @CheckNoEvictions @@ -524,38 +491,30 @@ public void refresh_failure(LoadingCache cache, CacheContext context) } @CheckNoEvictions @CheckNoStats - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) + @Test(dataProvider = "caches") @CacheSpec(implementation = Implementation.Caffeine, loader = Loader.REFRESH_EXCEPTIONAL) public void refresh_throwsException(LoadingCache cache, CacheContext context) { - cache.refresh(context.absentKey()); + assertThrows(IllegalStateException.class, () -> cache.refresh(context.absentKey())); } @CheckNoEvictions @CheckNoStats @Test(dataProvider = "caches") @CacheSpec(implementation = Implementation.Caffeine, loader = Loader.REFRESH_CHECKED_EXCEPTIONAL) public void refresh_throwsCheckedException(LoadingCache cache, CacheContext context) { - try { - cache.refresh(context.absentKey()); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); - } + var e = assertThrows(CompletionException.class, () -> cache.refresh(context.absentKey())); + assertThat(e).hasCauseThat().isInstanceOf(ExecutionException.class); } @CheckNoEvictions @Test(dataProvider = "caches") @CacheSpec(loader = Loader.REFRESH_INTERRUPTED) public void refresh_interrupted(LoadingCache cache, CacheContext context) { - try { - cache.refresh(context.absentKey()); - Assert.fail(); - } catch (CompletionException e) { - assertThat(Thread.interrupted()).isTrue(); - assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); + var e = assertThrows(CompletionException.class, () -> cache.refresh(context.absentKey())); + assertThat(Thread.interrupted()).isTrue(); + assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); - int failures = context.isGuava() ? 1 : 0; - assertThat(context).stats().hits(0).misses(0).success(0).failures(failures); - } + int failures = context.isGuava() ? 1 : 0; + assertThat(context).stats().hits(0).misses(0).success(0).failures(failures); } @CheckNoEvictions @@ -716,8 +675,8 @@ public void refresh_conflict(CacheContext context) { @CheckNoEvictions @Test(dataProvider = "caches") - @CacheSpec(population = Population.EMPTY, executor = CacheExecutor.THREADED, - removalListener = Listener.CONSUMING) + @CacheSpec(population = Population.EMPTY, + executor = CacheExecutor.THREADED, removalListener = Listener.CONSUMING) public void refresh_put(CacheContext context) { var started = new AtomicBoolean(); var refresh = new AtomicBoolean(); @@ -757,8 +716,8 @@ public void refresh_put(CacheContext context) { @CheckNoEvictions @Test(dataProvider = "caches") - @CacheSpec(population = Population.EMPTY, executor = CacheExecutor.THREADED, - removalListener = Listener.CONSUMING) + @CacheSpec(population = Population.EMPTY, + executor = CacheExecutor.THREADED, removalListener = Listener.CONSUMING) public void refresh_invalidate(CacheContext context) { var started = new AtomicBoolean(); var done = new AtomicBoolean(); @@ -966,7 +925,7 @@ public void refresh_error_log(CacheContext context) { assertThat(event.getLevel()).isEqualTo(WARN); } - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(implementation = Implementation.Caffeine, population = Population.EMPTY) public void refresh_nullFuture_load(CacheContext context) { var cache = context.build(new CacheLoader() { @@ -977,10 +936,10 @@ public void refresh_nullFuture_load(CacheContext context) { return null; } }); - cache.refresh(context.absentKey()); + assertThrows(NullPointerException.class, () -> cache.refresh(context.absentKey())); } - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(implementation = Implementation.Caffeine, population = Population.EMPTY) public void refresh_nullFuture_reload(CacheContext context) { var cache = context.build(new CacheLoader() { @@ -993,23 +952,24 @@ public void refresh_nullFuture_reload(CacheContext context) { } }); cache.put(context.absentKey(), context.absentValue()); - cache.refresh(context.absentKey()); + assertThrows(NullPointerException.class, () -> cache.refresh(context.absentKey())); } /* --------------- refreshAll --------------- */ + @Test(dataProvider = "caches") @CheckNoEvictions @CheckNoStats @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void refreshAll_null(LoadingCache cache, CacheContext context) { - cache.refreshAll(null); + assertThrows(NullPointerException.class, () -> cache.refreshAll(null)); } + @Test(dataProvider = "caches") @CheckNoEvictions @CheckNoStats @CacheSpec(removalListener = { Listener.DISABLED, Listener.REJECTING }) - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) public void refreshAll_nullKey(LoadingCache cache, CacheContext context) { - cache.refreshAll(Collections.singletonList(null)); + List keys = Collections.singletonList(null); + assertThrows(NullPointerException.class, () -> cache.refreshAll(keys)); } @CacheSpec @@ -1024,9 +984,10 @@ public void refreshAll_nullLookup(LoadingCache cache, CacheContext con @CacheSpec @CheckNoEvictions - @Test(dataProvider = "caches", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "caches") public void refreshAll_immutable(LoadingCache cache, CacheContext context) { - cache.refreshAll(context.firstMiddleLastKeys()).join().clear(); + var results = cache.refreshAll(context.firstMiddleLastKeys()).join(); + assertThrows(UnsupportedOperationException.class, results::clear); } @CheckNoEvictions @@ -1068,16 +1029,12 @@ public void refreshAll_failure(LoadingCache cache, CacheContext contex @Test(dataProvider = "caches") @CacheSpec(loader = Loader.REFRESH_INTERRUPTED) public void refreshAll_interrupted(LoadingCache cache, CacheContext context) { - try { - cache.refreshAll(context.absentKeys()); - Assert.fail(); - } catch (CompletionException e) { - assertThat(Thread.interrupted()).isTrue(); - assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); + var e = assertThrows(CompletionException.class, () -> cache.refreshAll(context.absentKeys())); + assertThat(Thread.interrupted()).isTrue(); + assertThat(e).hasCauseThat().isInstanceOf(InterruptedException.class); - int failures = context.isGuava() ? 1 : 0; - assertThat(context).stats().hits(0).misses(0).success(0).failures(failures); - } + int failures = context.isGuava() ? 1 : 0; + assertThat(context).stats().hits(0).misses(0).success(0).failures(failures); } @CheckNoEvictions @@ -1096,7 +1053,7 @@ public void refreshAll_cancel(LoadingCache cache, CacheContext context assertThat(cache).containsExactlyEntriesIn(context.original()); } - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(implementation = Implementation.Caffeine, population = Population.EMPTY) public void refreshAll_nullFuture_load(CacheContext context) { var cache = context.build(new CacheLoader() { @@ -1107,10 +1064,10 @@ public void refreshAll_nullFuture_load(CacheContext context) { return null; } }); - cache.refreshAll(context.absent().keySet()); + assertThrows(NullPointerException.class, () -> cache.refreshAll(context.absent().keySet())); } - @Test(dataProvider = "caches", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "caches") @CacheSpec(implementation = Implementation.Caffeine, population = Population.EMPTY) public void refreshAll_nullFuture_reload(CacheContext context) { var cache = context.build(new CacheLoader() { @@ -1123,16 +1080,15 @@ public void refreshAll_nullFuture_reload(CacheContext context) { } }); cache.put(context.absentKey(), context.absentValue()); - cache.refreshAll(context.absent().keySet()); + assertThrows(NullPointerException.class, () -> cache.refreshAll(context.absent().keySet())); } /* --------------- CacheLoader --------------- */ - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = UnsupportedOperationException.class) + @Test public void loadAll() throws Exception { CacheLoader loader = key -> key; - loader.loadAll(Set.of()); + assertThrows(UnsupportedOperationException.class, () -> loader.loadAll(Set.of())); } @Test @@ -1194,10 +1150,9 @@ public void asyncReload() throws Exception { assertThat(future).succeedsWith(-1); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = NullPointerException.class) + @Test public void bulk_null() { - CacheLoader.bulk(null); + assertThrows(NullPointerException.class, () -> CacheLoader.bulk(null)); } @Test diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MpscGrowableArrayQueueTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MpscGrowableArrayQueueTest.java index 9bf0861435..24370872c8 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MpscGrowableArrayQueueTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/MpscGrowableArrayQueueTest.java @@ -18,6 +18,7 @@ import static com.github.benmanes.caffeine.testing.Awaits.await; import static com.google.common.truth.Truth.assertThat; import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThrows; import java.util.concurrent.atomic.AtomicInteger; @@ -38,22 +39,22 @@ public final class MpscGrowableArrayQueueTest { /* --------------- Constructor --------------- */ - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void constructor_initialCapacity_tooSmall() { - new MpscGrowableArrayQueue(/* initialCapacity */ 1, /* maxCapacity */ 4); + assertThrows(IllegalArgumentException.class, () -> + new MpscGrowableArrayQueue(/* initialCapacity */ 1, /* maxCapacity */ 4)); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void constructor_maxCapacity_tooSmall() { - new MpscGrowableArrayQueue(/* initialCapacity */ 4, /* maxCapacity */ 1); + assertThrows(IllegalArgumentException.class, () -> + new MpscGrowableArrayQueue(/* initialCapacity */ 4, /* maxCapacity */ 1)); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void constructor_inverted() { - new MpscGrowableArrayQueue(/* initialCapacity */ 8, /* maxCapacity */ 4); + assertThrows(IllegalArgumentException.class, () -> + new MpscGrowableArrayQueue(/* initialCapacity */ 8, /* maxCapacity */ 4)); } @Test @@ -194,10 +195,9 @@ public void relaxedPeek_toEmpty(MpscGrowableArrayQueue buffer) { /* --------------- Miscellaneous --------------- */ - @SuppressWarnings("ReturnValueIgnored") - @Test(dataProvider = "full", expectedExceptions = UnsupportedOperationException.class) + @Test(dataProvider = "full") public void iterator(MpscGrowableArrayQueue buffer) { - buffer.iterator(); + assertThrows(UnsupportedOperationException.class, buffer::iterator); } @Test(dataProvider = "populated") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ReferenceTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ReferenceTest.java index 516e9b1f8b..feb2155e08 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ReferenceTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/ReferenceTest.java @@ -29,6 +29,7 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static java.util.function.Function.identity; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doThrow; @@ -107,8 +108,8 @@ public void identity_values(Cache cache, CacheContext context) { } @Test(dataProvider = "caches") - @CacheSpec(population = Population.FULL, requiresWeakOrSoft = true, - evictionListener = Listener.MOCKITO) + @CacheSpec(population = Population.FULL, + requiresWeakOrSoft = true, evictionListener = Listener.MOCKITO) public void collect_evictionListenerFails(CacheContext context) { context.clear(); GcFinalization.awaitFullGc(); @@ -154,22 +155,18 @@ public void get(Cache cache, CacheContext context) { .contains(collected).exclusively(); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO, values = {ReferenceType.WEAK, ReferenceType.SOFT}) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void get_expiryFails(Cache cache, CacheContext context) { Int key = context.firstKey(); context.clear(); GcFinalization.awaitFullGc(); - try { - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(IllegalStateException.class); - cache.get(key, identity()); - } finally { - assertThat(cache).doesNotContainKey(key); - } + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> cache.get(key, identity())); + assertThat(cache).doesNotContainKey(key); } @Test(dataProvider = "caches") @@ -396,22 +393,18 @@ public void get_loading(LoadingCache cache, CacheContext context) { .contains(collected).exclusively(); } - @SuppressWarnings("CheckReturnValue") + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO, values = {ReferenceType.WEAK, ReferenceType.SOFT}, loader = Loader.IDENTITY) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void get_loading_expiryFails(LoadingCache cache, CacheContext context) { Int key = context.firstKey(); context.clear(); GcFinalization.awaitFullGc(); - try { - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(IllegalStateException.class); - cache.get(key); - } finally { - assertThat(cache).doesNotContainKey(key); - } + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> cache.get(key)); + assertThat(cache).doesNotContainKey(key); } @Test(dataProvider = "caches") @@ -570,7 +563,6 @@ public void containsKey(Map map, CacheContext context) { } @Test(dataProvider = "caches") - @SuppressWarnings("UnusedVariable") @CacheSpec(population = Population.FULL, requiresWeakOrSoft = true, expireAfterAccess = Expire.DISABLED, expireAfterWrite = Expire.DISABLED, maximumSize = Maximum.DISABLED, weigher = CacheWeigher.DISABLED, @@ -656,21 +648,18 @@ public void put_weighted(Cache> cache, CacheContext context) { assertThat(context).hasWeightedSize(3); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO, values = {ReferenceType.WEAK, ReferenceType.SOFT}) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void put_expiryFails(Cache cache, CacheContext context) { Int key = context.firstKey(); context.clear(); GcFinalization.awaitFullGc(); - try { - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(IllegalStateException.class); - cache.put(key, key); - } finally { - assertThat(cache).doesNotContainKey(key); - } + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> cache.put(key, key)); + assertThat(cache).doesNotContainKey(key); } @Test(dataProvider = "caches") @@ -711,21 +700,18 @@ public void put_map(Map map, CacheContext context) { } } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO, values = {ReferenceType.WEAK, ReferenceType.SOFT}) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void put_map_expiryFails(Map map, CacheContext context) { Int key = context.firstKey(); context.clear(); GcFinalization.awaitFullGc(); - try { - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(IllegalStateException.class); - map.put(key, key); - } finally { - assertThat(map).doesNotContainKey(key); - } + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> map.put(key, key)); + assertThat(map).doesNotContainKey(key); } @Test(dataProvider = "caches") @@ -901,21 +887,18 @@ public void computeIfAbsent_weighted(Cache> cache, CacheContext c } } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO, values = {ReferenceType.WEAK, ReferenceType.SOFT}) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void computeIfAbsent_expiryFails(Map map, CacheContext context) { Int key = context.firstKey(); context.clear(); GcFinalization.awaitFullGc(); - try { - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(IllegalStateException.class); - map.computeIfAbsent(key, identity()); - } finally { - assertThat(map).doesNotContainKey(key); - } + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> map.computeIfAbsent(key, identity())); + assertThat(map).doesNotContainKey(key); } @Test(dataProvider = "caches") @@ -1027,21 +1010,18 @@ public void compute_weighted(Cache> cache, CacheContext context) assertThat(context).hasWeightedSize(3); } + @Test(dataProvider = "caches") @CacheSpec(population = Population.FULL, expiry = CacheExpiry.MOCKITO, values = {ReferenceType.WEAK, ReferenceType.SOFT}) - @Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class) public void compute_expiryFails(Map map, CacheContext context) { Int key = context.firstKey(); context.clear(); GcFinalization.awaitFullGc(); - try { - when(context.expiry().expireAfterCreate(any(), any(), anyLong())) - .thenThrow(IllegalStateException.class); - map.compute(key, (k, v) -> k); - } finally { - assertThat(map).doesNotContainKey(key); - } + when(context.expiry().expireAfterCreate(any(), any(), anyLong())) + .thenThrow(IllegalStateException.class); + assertThrows(IllegalStateException.class, () -> map.compute(key, (k, v) -> k)); + assertThat(map).doesNotContainKey(key); } @Test(dataProvider = "caches") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java index b8f252545c..5690e49366 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/RefreshAfterWriteTest.java @@ -32,6 +32,7 @@ import static com.google.common.truth.Truth8.assertThat; import static java.util.function.Function.identity; import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThrows; import static uk.org.lidalia.slf4jext.Level.WARN; import java.time.Duration; @@ -85,7 +86,6 @@ public final class RefreshAfterWriteTest { @CheckNoEvictions @Test(dataProvider = "caches") - @SuppressWarnings("CheckReturnValue") @CacheSpec(implementation = Implementation.Caffeine, population = Population.EMPTY, refreshAfterWrite = Expire.ONE_MINUTE, executor = CacheExecutor.THREADED) public void refreshIfNeeded_nonblocking(CacheContext context) { @@ -110,12 +110,14 @@ public CompletableFuture asyncReload(Int key, Int oldValue, Executor execut }); cache.put(key, original); context.ticker().advance(duration); - ConcurrentTestHarness.execute(() -> cache.get(key)); + ConcurrentTestHarness.execute(() -> assertThat(cache.get(key)).isAnyOf(original, refresh1)); await().untilAtomic(reloads, is(1)); assertThat(cache.get(key)).isEqualTo(original); refresh.set(true); - cache.get(key); + + Int refreshed = cache.get(key); + assertThat(refreshed).isAnyOf(original, refresh1); await().untilAsserted(() -> assertThat(reloads.get()).isEqualTo(1)); await().untilAsserted(() -> assertThat(cache).containsEntry(key, refresh1)); @@ -939,11 +941,13 @@ public void getRefreshesAfter(CacheContext context, FixedRefresh refre assertThat(refreshAfterWrite.getRefreshesAfter(TimeUnit.MINUTES)).isEqualTo(1); } - @Test(dataProvider = "caches", expectedExceptions = IllegalArgumentException.class) + @Test(dataProvider = "caches") @CacheSpec(refreshAfterWrite = Expire.ONE_MINUTE) public void setRefreshAfter_negative(Cache cache, CacheContext context, FixedRefresh refreshAfterWrite) { - refreshAfterWrite.setRefreshesAfter(Duration.ofMinutes(-2)); + var duration = Duration.ofMinutes(-2); + assertThrows(IllegalArgumentException.class, () -> + refreshAfterWrite.setRefreshesAfter(duration)); } @Test(dataProvider = "caches") diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/SchedulerTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/SchedulerTest.java index 482cf0f11b..3d88c134f3 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/SchedulerTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/SchedulerTest.java @@ -20,6 +20,7 @@ import static com.github.benmanes.caffeine.testing.ConcurrentTestHarness.scheduledExecutor; import static com.google.common.truth.Truth.assertThat; import static com.google.common.util.concurrent.testing.TestingExecutors.sameThreadScheduledExecutor; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; @@ -45,7 +46,6 @@ /** * @author ben.manes@gmail.com (Ben Manes) */ -@SuppressWarnings("FutureReturnValueIgnored") public final class SchedulerTest { private final NullPointerTester npeTester = new NullPointerTester(); @@ -101,10 +101,8 @@ public void disabledFuture_null() { /* --------------- guarded --------------- */ - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = NullPointerException.class) public void guardedScheduler_null() { - Scheduler.guardedScheduler(null); + assertThrows(NullPointerException.class, () -> Scheduler.guardedScheduler(null)); } @Test @@ -136,10 +134,9 @@ public void guardedScheduler_exception() { /* --------------- ScheduledExecutorService --------------- */ - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = NullPointerException.class) + @Test public void scheduledExecutorService_null() { - Scheduler.forScheduledExecutorService(null); + assertThrows(NullPointerException.class, () -> Scheduler.forScheduledExecutorService(null)); } @Test diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/StripedBufferTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/StripedBufferTest.java index dd3fc5b30f..c8d40d1255 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/StripedBufferTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/StripedBufferTest.java @@ -60,12 +60,12 @@ public void expand() { } @Test - @SuppressWarnings({"CheckReturnValue", "ThreadPriorityCheck"}) + @SuppressWarnings("ThreadPriorityCheck") public void expand_concurrent() { var buffer = new FakeBuffer(Buffer.FAILED); ConcurrentTestHarness.timeTasks(10 * NCPU, () -> { for (int i = 0; i < 1000; i++) { - buffer.offer(Boolean.TRUE); + assertThat(buffer.offer(Boolean.TRUE)).isAnyOf(Buffer.SUCCESS, Buffer.FULL, Buffer.FAILED); Thread.yield(); } }); @@ -73,11 +73,11 @@ public void expand_concurrent() { } @Test(dataProvider = "buffers") - @SuppressWarnings({"CheckReturnValue", "ThreadPriorityCheck"}) + @SuppressWarnings("ThreadPriorityCheck") public void produce(FakeBuffer buffer) { ConcurrentTestHarness.timeTasks(NCPU, () -> { for (int i = 0; i < 10; i++) { - buffer.offer(ELEMENT); + assertThat(buffer.offer(ELEMENT)).isAnyOf(Buffer.SUCCESS, Buffer.FULL, Buffer.FAILED); Thread.yield(); } }); @@ -85,13 +85,13 @@ public void produce(FakeBuffer buffer) { } @Test(dataProvider = "buffers") - @SuppressWarnings("CheckReturnValue") public void drain(FakeBuffer buffer) { buffer.drainTo(e -> {}); assertThat(buffer.drains).isEqualTo(0); // Expand and drain - buffer.offer(ELEMENT); + assertThat(buffer.offer(ELEMENT)).isEqualTo(Buffer.SUCCESS); + buffer.drainTo(e -> {}); assertThat(buffer.drains).isEqualTo(1); } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java index 9e75073760..a4cdaeb262 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/TimerWheelTest.java @@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static java.util.Locale.US; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doThrow; @@ -48,7 +49,6 @@ import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.testng.Assert; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; @@ -166,19 +166,15 @@ public void advance_backwards(long clock) { @Test public void advance_exception() { - doThrow(new IllegalStateException()) + doThrow(new IllegalArgumentException()) .when(cache).evictEntry(captor.capture(), any(), anyLong()); var timer = new Timer(timerWheel.nanos + SPANS[1]); timerWheel.nanos = 0L; timerWheel.schedule(timer); - try { - timerWheel.advance(cache, Long.MAX_VALUE); - Assert.fail(); - } catch (IllegalStateException e) { - assertThat(timerWheel.nanos).isEqualTo(0); - assertThat(timerWheel.wheel[1][1].getNextInVariableOrder()).isSameInstanceAs(timer); - } + assertThrows(IllegalArgumentException.class, () -> timerWheel.advance(cache, Long.MAX_VALUE)); + assertThat(timerWheel.wheel[1][1].getNextInVariableOrder()).isSameInstanceAs(timer); + assertThat(timerWheel.nanos).isEqualTo(0); } @Test(dataProvider = "clock") @@ -442,10 +438,7 @@ public void iterator_hasNext(Iterable> iterable) { iterator.next(); assertThat(iterator.hasNext()).isFalse(); - try { - iterator.next(); - Assert.fail(); - } catch (NoSuchElementException expected) {} + assertThrows(NoSuchElementException.class, iterator::next); } @DataProvider(name = "iterator") @@ -514,16 +507,10 @@ public void sentinel_ignored() { } @Test - @SuppressWarnings("CheckReturnValue") public void sentinel_unsupported() { var node = new Sentinel<>(); - List methods = List.of(node::getKeyReference, node::getValueReference); - for (var method : methods) { - try { - method.run(); - Assert.fail(); - } catch (UnsupportedOperationException expected) {} - } + assertThrows(UnsupportedOperationException.class, node::getKeyReference); + assertThrows(UnsupportedOperationException.class, node::getValueReference); } /** Returns a snapshot roughly ordered by the expiration time. */ diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/stats/CacheStatsTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/stats/CacheStatsTest.java index b01b791933..3bc4d643bc 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/stats/CacheStatsTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/stats/CacheStatsTest.java @@ -16,6 +16,7 @@ package com.github.benmanes.caffeine.cache.stats; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -25,12 +26,13 @@ */ public final class CacheStatsTest { - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "badArgs", expectedExceptions = IllegalArgumentException.class) + @Test(dataProvider = "badArgs") public void invalid(int hitCount, int missCount, int loadSuccessCount, int loadFailureCount, int totalLoadTime, int evictionCount, int evictionWeight) { - CacheStats.of(hitCount, missCount, loadSuccessCount, - loadFailureCount, totalLoadTime, evictionCount, evictionWeight); + assertThrows(IllegalArgumentException.class, () -> { + CacheStats.of(hitCount, missCount, loadSuccessCount, + loadFailureCount, totalLoadTime, evictionCount, evictionWeight); + }); } @Test diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/GuavaCacheFromContext.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/GuavaCacheFromContext.java index b74fbbd0ff..8efb06497c 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/GuavaCacheFromContext.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/GuavaCacheFromContext.java @@ -594,7 +594,7 @@ static final class GuavaWeigher implements Weigher, Serializable { final com.github.benmanes.caffeine.cache.Weigher weigher; GuavaWeigher(com.github.benmanes.caffeine.cache.Weigher weigher) { - this.weigher = weigher; + this.weigher = com.github.benmanes.caffeine.cache.Weigher.boundedWeigher(weigher); } @Override public int weigh(K key, V value) { diff --git a/gradle/dependencies.gradle b/gradle/dependencies.gradle index 1a5b794383..717a1ba85f 100644 --- a/gradle/dependencies.gradle +++ b/gradle/dependencies.gradle @@ -27,7 +27,7 @@ ext { versions = [ autoValue: '1.10.1', cache2k: '2.6.1.Final', - checkerFramework: '3.31.0', + checkerFramework: '3.32.0', coherence: '22.06.2', commonsCompress: '1.22', commonsLang3: '3.12.0', @@ -42,12 +42,12 @@ ext { fastfilter: '1.0.2', fastutil: '8.5.11', flipTables: '1.1.0', - googleJavaFormat: '1.15.0', + googleJavaFormat: '1.16.0', guava: '31.1-jre', hazelcast: '5.2.2', jackrabbit: '1.48.0', jamm: '0.3.3', - javaObjectLayout: '0.16', + javaObjectLayout: '0.17', javapoet: '1.13.0', jcache: '1.1.1', jfreechart: '1.5.4', @@ -64,7 +64,7 @@ ext { univocityParsers: '2.9.1', ycsb: '0.17.0', xz: '1.9', - zstd: '1.5.4-1', + zstd: '1.5.4-2', ] testVersions = [ awaitility: '4.2.0', @@ -90,18 +90,18 @@ ext { ] pluginVersions = [ bnd: '6.4.0', - checkstyle: '10.7.0', + checkstyle: '10.8.0', coveralls: '2.12.0', - dependencyCheck: '8.1.0', + dependencyCheck: '8.1.2', errorprone: '3.0.1', findsecbugs: '1.12.0', forbiddenApis: '3.4', jacoco: '0.8.7', - jmh: '0.6.8', + jmh: '0.7.0', jmhReport: '0.9.0', nexusPublish: '1.2.0', nullaway: '1.5.0', - pmd: '6.54.0', + pmd: '6.55.0', semanticVersioning: '1.1.0', snyk: '0.4', sonarqube: '4.0.0.2929', diff --git a/gradle/jmh.gradle b/gradle/jmh.gradle index 65e01bf51b..c156db17b6 100644 --- a/gradle/jmh.gradle +++ b/gradle/jmh.gradle @@ -54,10 +54,6 @@ jmh { resultFormat = 'json' resultsFile = layout.buildDirectory.file('reports/jmh/results.json') - jvm = javaToolchains - .launcherFor { languageVersion = java.toolchain.languageVersion } - .map { it.executablePath.asFile.absolutePath } - def jvmArguments = [ '-Xmx2G' ] if (System.env.GRAALVM == 'true') { jvmArguments += [ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 96bc8dbba0..7a9e52585e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,4 +1,4 @@ -distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME diff --git a/guava/src/test/java/com/github/benmanes/caffeine/guava/CaffeinatedGuavaTest.java b/guava/src/test/java/com/github/benmanes/caffeine/guava/CaffeinatedGuavaTest.java index ea79afbd05..3d437e42ee 100644 --- a/guava/src/test/java/com/github/benmanes/caffeine/guava/CaffeinatedGuavaTest.java +++ b/guava/src/test/java/com/github/benmanes/caffeine/guava/CaffeinatedGuavaTest.java @@ -16,16 +16,14 @@ package com.github.benmanes.caffeine.guava; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import java.lang.reflect.Constructor; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionException; -import org.junit.Assert; - import com.github.benmanes.caffeine.cache.Caffeine; -import com.github.benmanes.caffeine.guava.CaffeinatedGuavaCache.CacheLoaderException; import com.github.benmanes.caffeine.guava.CaffeinatedGuavaLoadingCache.CaffeinatedLoader; import com.github.benmanes.caffeine.guava.CaffeinatedGuavaLoadingCache.ExternalBulkLoader; import com.github.benmanes.caffeine.guava.CaffeinatedGuavaLoadingCache.ExternalSingleLoader; @@ -70,72 +68,56 @@ public void testHasMethod_notFound() { } public void testReload_interrupted() { - try { - LoadingCache cache = CaffeinatedGuava.build( - Caffeine.newBuilder().executor(MoreExecutors.directExecutor()), - new CacheLoader() { - @Override public Integer load(Integer key) throws InterruptedException { - throw new InterruptedException(); - } - }); - cache.put(1, 1); - cache.refresh(1); - } catch (CacheLoaderException e) { - assertTrue(Thread.currentThread().isInterrupted()); - } + LoadingCache cache = CaffeinatedGuava.build( + Caffeine.newBuilder().executor(MoreExecutors.directExecutor()), + new CacheLoader() { + @Override public Integer load(Integer key) throws InterruptedException { + throw new InterruptedException(); + } + }); + cache.put(1, 1); + + // Unlike Guava, Caffeine does not leak the exception to the caller + cache.refresh(1); } public void testReload_throwable() { - try { - LoadingCache cache = CaffeinatedGuava.build( - Caffeine.newBuilder().executor(MoreExecutors.directExecutor()), - new CacheLoader() { - @Override public Integer load(Integer key) throws Exception { - throw new Exception(); - } - }); - cache.put(1, 1); - cache.refresh(1); - } catch (CacheLoaderException e) { - assertTrue(Thread.currentThread().isInterrupted()); - } + LoadingCache cache = CaffeinatedGuava.build( + Caffeine.newBuilder().executor(MoreExecutors.directExecutor()), + new CacheLoader() { + @Override public Integer load(Integer key) throws Exception { + throw new Exception(); + } + }); + cache.put(1, 1); + + // Unlike Guava, Caffeine does not leak the exception to the caller + cache.refresh(1); } public void testCacheLoader_null() throws Exception { - try { - CaffeinatedGuava.caffeinate(null); - Assert.fail(); - } catch (NullPointerException expected) {} - - try { - var caffeine = CaffeinatedGuava.caffeinate(CacheLoader.from(key -> null)); - caffeine.load(1); - Assert.fail(); - } catch (InvalidCacheLoadException expected) {} - - try { - var caffeine = CaffeinatedGuava.caffeinate(CacheLoader.from(key -> null)); - caffeine.asyncReload(1, 2, Runnable::run).join(); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isInstanceOf(InvalidCacheLoadException.class); - } + assertThrows(NullPointerException.class, () -> CaffeinatedGuava.caffeinate(null)); - try { - var caffeine = CaffeinatedGuava.caffeinate(new CacheLoader() { - @Override public Integer load(Integer key) { - throw new UnsupportedOperationException(); - } - @Override - public ListenableFuture reload(Integer key, Integer oldValue) { - return null; - } - }); - caffeine.asyncReload(1, 2, Runnable::run).join(); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isInstanceOf(InvalidCacheLoadException.class); - } + var caffeine1 = CaffeinatedGuava.caffeinate(CacheLoader.from(key -> null)); + assertThrows(InvalidCacheLoadException.class, () -> caffeine1.load(1)); + + var caffeine2 = CaffeinatedGuava.caffeinate(CacheLoader.from(key -> null)); + var e1 = assertThrows(CompletionException.class, () -> + caffeine2.asyncReload(1, 2, Runnable::run).join()); + assertThat(e1).hasCauseThat().isInstanceOf(InvalidCacheLoadException.class); + + var caffeine3 = CaffeinatedGuava.caffeinate(new CacheLoader() { + @Override public Integer load(Integer key) { + throw new UnsupportedOperationException(); + } + @Override + public ListenableFuture reload(Integer key, Integer oldValue) { + return null; + } + }); + var e2 = assertThrows(CompletionException.class, () -> + caffeine3.asyncReload(1, 2, Runnable::run).join()); + assertThat(e2).hasCauseThat().isInstanceOf(InvalidCacheLoadException.class); } public void testCacheLoader_exception() throws Exception { @@ -155,24 +137,15 @@ public void runCacheLoaderExceptionTest(Exception error) throws Exception { } }; var caffeine = CaffeinatedGuava.caffeinate(guava); - try { - caffeine.load(1); - Assert.fail(); - } catch (Exception e) { - assertThat(e).isSameInstanceAs(error); - } - try { - caffeine.loadAll(Set.of(1, 2)); - Assert.fail(); - } catch (Exception e) { - assertThat(e).isSameInstanceAs(error); - } - try { - caffeine.asyncReload(1, 2, Runnable::run).join(); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isSameInstanceAs(error); - } + var e1 = assertThrows(error.getClass(), () -> caffeine.load(1)); + assertThat(e1).isSameInstanceAs(error); + + var e2 = assertThrows(error.getClass(), () -> caffeine.loadAll(Set.of(1, 2))); + assertThat(e2).isSameInstanceAs(error); + + var e3 = assertThrows(CompletionException.class, () -> + caffeine.asyncReload(1, 2, Runnable::run).join()); + assertThat(e3).hasCauseThat().isSameInstanceAs(error); } public void testCacheLoader_single() throws Exception { @@ -249,12 +222,9 @@ public ListenableFuture reload(Integer key, Integer oldValue) { var error = new IllegalStateException(); reloader.setException(error); assertTrue(future.isCompletedExceptionally()); - try { - future.join(); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isSameInstanceAs(error); - } + + var e = assertThrows(CompletionException.class, future::join); + assertThat(e).hasCauseThat().isSameInstanceAs(error); } private static void checkSingleLoader(Exception error, CacheLoader guava, @@ -265,32 +235,21 @@ private static void checkSingleLoader(Exception error, CacheLoader) caffeine).cacheLoader).isSameInstanceAs(guava); assertThat(caffeine.load(1)).isEqualTo(-1); - try { - caffeine.load(-1); - Assert.fail(); - } catch (Exception e) { - assertThat(e).isSameInstanceAs(error); - } + var e1 = assertThrows(error.getClass(), () -> caffeine.load(-1)); + assertThat(e1).isSameInstanceAs(error); assertThat(caffeine.asyncReload(1, 2, Runnable::run).join()).isEqualTo(-1); - try { - caffeine.asyncReload(-1, 2, Runnable::run).join(); - Assert.fail(); - } catch (CompletionException e) { - assertThat(e).hasCauseThat().isSameInstanceAs(error); - } + var e2 = assertThrows(CompletionException.class, () -> + caffeine.asyncReload(-1, 2, Runnable::run).join()); + assertThat(e2).hasCauseThat().isSameInstanceAs(error); } private static void checkBulkLoader(Exception error, com.github.benmanes.caffeine.cache.CacheLoader caffeine) throws Exception { assertThat(caffeine).isInstanceOf(ExternalBulkLoader.class); assertThat(caffeine.loadAll(Set.of(1, 2, 3))).isEqualTo(Map.of(1, -1, 2, -2, 3, -3)); - try { - caffeine.loadAll(Set.of(1, -1)); - Assert.fail(); - } catch (Exception e) { - assertThat(e).isSameInstanceAs(error); - } + var e = assertThrows(error.getClass(), () -> caffeine.loadAll(Set.of(1, -1))); + assertThat(e).isSameInstanceAs(error); } enum IdentityLoader implements com.github.benmanes.caffeine.cache.CacheLoader { diff --git a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/LocalLoadingCacheTest.java b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/LocalLoadingCacheTest.java index 6547a0b6e1..f7abc2e673 100644 --- a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/LocalLoadingCacheTest.java +++ b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/LocalLoadingCacheTest.java @@ -34,6 +34,7 @@ import com.google.common.collect.ImmutableSet; import com.google.common.testing.NullPointerTester; import com.google.common.util.concurrent.MoreExecutors; +import com.google.errorprone.annotations.CanIgnoreReturnValue; import junit.framework.TestCase; @@ -44,6 +45,7 @@ public class LocalLoadingCacheTest extends TestCase { static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0); + @CanIgnoreReturnValue private static LoadingCache makeCache( Caffeine builder, CacheLoader loader) { return CaffeinatedGuava.build(builder, loader); @@ -55,7 +57,6 @@ private Caffeine createCacheBuilder() { // constructor tests - @SuppressWarnings("CheckReturnValue") public void testComputingFunction() { CacheLoader loader = new CacheLoader() { @Override diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/CacheProxyTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/CacheProxyTest.java index d5a7592cff..e084839608 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/CacheProxyTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/CacheProxyTest.java @@ -14,6 +14,7 @@ package com.github.benmanes.caffeine.jcache; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; @@ -33,7 +34,6 @@ import javax.cache.integration.CacheWriter; import org.mockito.Mockito; -import org.testng.Assert; import org.testng.annotations.Test; import com.github.benmanes.caffeine.jcache.configuration.CaffeineConfiguration; @@ -61,39 +61,34 @@ protected CaffeineConfiguration getConfiguration() { } @Test - @SuppressWarnings({"CheckReturnValue", "ObjectToString", "unchecked"}) + @SuppressWarnings({"ObjectToString", "unchecked"}) public void getConfiguration_immutable() { var config = jcache.getConfiguration(CaffeineConfiguration.class); - List modifiers = List.of( - () -> config.getCacheEntryListenerConfigurations().iterator().remove(), - () -> config.addCacheEntryListenerConfiguration(null), - () -> config.setCacheLoaderFactory(null), - () -> config.setCacheWriterFactory(null), - () -> config.setCopierFactory(null), - () -> config.setExecutorFactory(null), - () -> config.setExpireAfterAccess(OptionalLong.empty()), - () -> config.setExpireAfterWrite(OptionalLong.empty()), - () -> config.setExpiryFactory(Optional.empty()), - () -> config.setExpiryPolicyFactory(null), - () -> config.setManagementEnabled(false), - () -> config.setMaximumSize(OptionalLong.empty()), - () -> config.setMaximumWeight(OptionalLong.empty()), - () -> config.setNativeStatisticsEnabled(false), - () -> config.setReadThrough(false), - () -> config.setRefreshAfterWrite(OptionalLong.empty()), - () -> config.setSchedulerFactory(null), - () -> config.setStatisticsEnabled(false), - () -> config.setStoreByValue(false), - () -> config.setTickerFactory(null), - () -> config.setTypes(String.class, String.class), - () -> config.setWeigherFactory(Optional.empty()), - () -> config.setWriteThrough(false)); - for (var modifier : modifiers) { - try { - modifier.run(); - Assert.fail(); - } catch (UnsupportedOperationException expected) {} - } + var type = UnsupportedOperationException.class; + + assertThrows(type, () -> config.getCacheEntryListenerConfigurations().iterator().remove()); + assertThrows(type, () -> config.addCacheEntryListenerConfiguration(null)); + assertThrows(type, () -> config.setCacheLoaderFactory(null)); + assertThrows(type, () -> config.setCacheWriterFactory(null)); + assertThrows(type, () -> config.setCopierFactory(null)); + assertThrows(type, () -> config.setExecutorFactory(null)); + assertThrows(type, () -> config.setExpireAfterAccess(OptionalLong.empty())); + assertThrows(type, () -> config.setExpireAfterWrite(OptionalLong.empty())); + assertThrows(type, () -> config.setExpiryFactory(Optional.empty())); + assertThrows(type, () -> config.setExpiryPolicyFactory(null)); + assertThrows(type, () -> config.setManagementEnabled(false)); + assertThrows(type, () -> config.setMaximumSize(OptionalLong.empty())); + assertThrows(type, () -> config.setMaximumWeight(OptionalLong.empty())); + assertThrows(type, () -> config.setNativeStatisticsEnabled(false)); + assertThrows(type, () -> config.setReadThrough(false)); + assertThrows(type, () -> config.setRefreshAfterWrite(OptionalLong.empty())); + assertThrows(type, () -> config.setSchedulerFactory(null)); + assertThrows(type, () -> config.setStatisticsEnabled(false)); + assertThrows(type, () -> config.setStoreByValue(false)); + assertThrows(type, () -> config.setTickerFactory(null)); + assertThrows(type, () -> config.setTypes(String.class, String.class)); + assertThrows(type, () -> config.setWeigherFactory(Optional.empty())); + assertThrows(type, () -> config.setWriteThrough(false)); assertThat(config).isEqualTo(jcacheConfiguration); assertThat(config.toString()).isEqualTo(jcacheConfiguration.toString()); @@ -113,10 +108,9 @@ public void getConfiguration_immutable() { .isEqualTo(List.of(configuration).toString()); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void unwrap_fail() { - jcache.unwrap(CaffeineConfiguration.class); + assertThrows(IllegalArgumentException.class, () -> jcache.unwrap(CaffeineConfiguration.class)); } @Test @@ -127,17 +121,18 @@ public void unwrap() { .isSameInstanceAs(jcache.cache); } - @SuppressWarnings({"CheckReturnValue", "serial"}) - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void unwrap_configuration() { + @SuppressWarnings("serial") abstract class Dummy implements Configuration {}; - jcache.getConfiguration(Dummy.class); + assertThrows(IllegalArgumentException.class, () -> jcache.getConfiguration(Dummy.class)); } - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void unwrap_entry() { jcache.put(KEY_1, VALUE_1); - jcache.iterator().next().unwrap(String.class); + var item = jcache.iterator().next(); + assertThrows(IllegalArgumentException.class, () -> item.unwrap(String.class)); } @Test diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/JCacheProfiler.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/JCacheProfiler.java index d85472a354..b373decfa5 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/JCacheProfiler.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/JCacheProfiler.java @@ -21,6 +21,7 @@ import java.util.Random; import java.util.concurrent.Executor; import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.LongAdder; @@ -31,6 +32,7 @@ import com.github.benmanes.caffeine.jcache.spi.CaffeineCachingProvider; import com.google.common.base.Stopwatch; import com.google.common.util.concurrent.ThreadFactoryBuilder; +import com.google.errorprone.annotations.CanIgnoreReturnValue; /** * A hook for profiling the JCache adapter. @@ -80,10 +82,10 @@ public void start() { } } - @SuppressWarnings("FutureReturnValueIgnored") - private void scheduleStatusTask() { + @CanIgnoreReturnValue + private ScheduledFuture scheduleStatusTask() { var stopwatch = Stopwatch.createStarted(); - Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() -> { + return Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() -> { long count = this.count.longValue(); long rate = count / stopwatch.elapsed(TimeUnit.SECONDS); System.out.printf(US, "%s - %,d [%,d / sec]%n", stopwatch, count, rate); diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/JCacheConfigurationTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/JCacheConfigurationTest.java index e18673f31d..4d004039f6 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/JCacheConfigurationTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/JCacheConfigurationTest.java @@ -16,6 +16,7 @@ package com.github.benmanes.caffeine.jcache.configuration; import static com.google.common.truth.Truth8.assertThat; +import static org.junit.Assert.assertThrows; import java.util.function.Supplier; @@ -25,7 +26,6 @@ import javax.cache.Caching; import javax.cache.configuration.MutableConfiguration; -import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -71,10 +71,8 @@ public void anonymousCache() { @Test public void definedCache() { - try { - cacheManager.createCache("test-cache-2", cacheConfig); - Assert.fail(); - } catch (CacheException ignored) {} + assertThrows(CacheException.class, () -> + cacheManager.createCache("test-cache-2", cacheConfig)); checkConfiguration(() -> cacheManager.getCache("test-cache-2", String.class, Integer.class), 1000L); diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java index 2b8c801f76..0eaa3c7567 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TypesafeConfigurationTest.java @@ -17,6 +17,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; +import static org.junit.Assert.assertThrows; import java.util.Optional; import java.util.concurrent.ForkJoinPool; @@ -72,10 +73,10 @@ public void illegalPath() { assertThat(TypesafeConfigurator.from(ConfigFactory.load(), "#")).isEmpty(); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalStateException.class) + @Test public void invalidCache() { - TypesafeConfigurator.from(ConfigFactory.load(), "invalid-cache"); + assertThrows(IllegalStateException.class, () -> + TypesafeConfigurator.from(ConfigFactory.load(), "invalid-cache")); } @Test diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/copy/JavaSerializationCopierTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/copy/JavaSerializationCopierTest.java index f22a20ac04..039f0912b3 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/copy/JavaSerializationCopierTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/copy/JavaSerializationCopierTest.java @@ -18,6 +18,7 @@ import static com.github.benmanes.caffeine.jcache.copy.AbstractCopier.javaDeepCopyStrategies; import static com.google.common.truth.Truth.assertThat; import static java.util.Locale.US; +import static org.junit.Assert.assertThrows; import java.io.IOException; import java.io.InputStream; @@ -46,46 +47,42 @@ */ public final class JavaSerializationCopierTest { - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "nullArgs", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "nullArgs") public void constructor_null(Set> immutableClasses, Map, Function> deepCopyStrategies) { - new JavaSerializationCopier(immutableClasses, deepCopyStrategies); + assertThrows(NullPointerException.class, () -> + new JavaSerializationCopier(immutableClasses, deepCopyStrategies)); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "copier", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "copier") public void null_object(Copier copier) { - copy(copier, null); + assertThrows(NullPointerException.class, () -> copy(copier, null)); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "copier", expectedExceptions = NullPointerException.class) + @Test(dataProvider = "copier") public void null_classLoader(Copier copier) { - copier.copy(1, null); + assertThrows(NullPointerException.class, () -> copier.copy(1, null)); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "copier", expectedExceptions = UncheckedIOException.class) + @Test(dataProvider = "copier") public void serializable_fail(JavaSerializationCopier copier) { - copier.serialize(new Object()); + assertThrows(UncheckedIOException.class, () -> copier.serialize(new Object())); } @Test - @SuppressWarnings("CheckReturnValue") public void deserializable_resolveClass() { var copier = new JavaSerializationCopier(); - copier.copy(ImmutableSet.of(), ClassLoader.getPlatformClassLoader()); + var copy = copier.copy(ImmutableSet.of(), ClassLoader.getPlatformClassLoader()); + assertThat(copy).isInstanceOf(ImmutableSet.class); } - @SuppressWarnings("CheckReturnValue") - @Test(dataProvider = "copier", expectedExceptions = CacheException.class) + @Test(dataProvider = "copier") public void deserializable_badData(JavaSerializationCopier copier) { - copier.deserialize(new byte[0], Thread.currentThread().getContextClassLoader()); + assertThrows(CacheException.class, () -> + copier.deserialize(new byte[0], Thread.currentThread().getContextClassLoader())); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = CacheException.class) + @Test public void deserializable_classNotFound() { var copier = new JavaSerializationCopier() { @Override protected ObjectInputStream newInputStream( @@ -98,7 +95,8 @@ public void deserializable_classNotFound() { }; } }; - copier.roundtrip(100, Thread.currentThread().getContextClassLoader()); + assertThrows(CacheException.class, () -> + copier.roundtrip(100, Thread.currentThread().getContextClassLoader())); } @Test(dataProvider = "copier") @@ -138,7 +136,6 @@ public void deepCopy_calendar(Copier copier) { } @Test(dataProvider = "copier") - @SuppressWarnings("CheckReturnValue") public void array_primitive(Copier copier) { int[] ints = { 0, 1, 2, 3, 4 }; assertThat(copy(copier, ints)).isEqualTo(ints); diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEntryEventTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEntryEventTest.java index d26f8c5eef..cb13f01b74 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEntryEventTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEntryEventTest.java @@ -16,6 +16,7 @@ package com.github.benmanes.caffeine.jcache.event; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import java.util.Iterator; import java.util.Map; @@ -46,10 +47,9 @@ public void before() throws Exception { event = new JCacheEntryEvent<>(cache, EventType.CREATED, 1, true, 2, 3); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void unwrap_fail() { - event.unwrap(Map.Entry.class); + assertThrows(IllegalArgumentException.class, () -> event.unwrap(Map.Entry.class)); } @Test diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryPolicyTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryPolicyTest.java index 838feddf4b..760777bb63 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryPolicyTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/expiry/JCacheExpiryPolicyTest.java @@ -50,9 +50,8 @@ public void access() { } @Test - @SuppressWarnings("TruthIncompatibleType") public void equals_wrongType() { - assertThat(eternal).isNotEqualTo(1); + assertThat(eternal.equals(new Object())).isFalse(); } @Test diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheLoaderTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheLoaderTest.java index aa7838c55a..fb3df624ce 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheLoaderTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheLoaderTest.java @@ -16,6 +16,7 @@ package com.github.benmanes.caffeine.jcache.integration; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyIterable; import static org.mockito.Mockito.when; @@ -30,7 +31,6 @@ import javax.cache.integration.CacheLoaderException; import org.mockito.Mockito; -import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -58,30 +58,20 @@ public void load_null() { } @Test(dataProvider = "throwables") - @SuppressWarnings("CheckReturnValue") public void load_failure(Throwable throwable) { - try { - when(cacheLoader.load(any())).thenThrow(throwable); - jcacheLoading.get(1); - Assert.fail(); - } catch (CacheLoaderException e) { - if (e != throwable) { - assertThat(e).hasCauseThat().isSameInstanceAs(throwable); - } + when(cacheLoader.load(any())).thenThrow(throwable); + var e = assertThrows(CacheLoaderException.class, () -> jcacheLoading.get(1)); + if (e != throwable) { + assertThat(e).hasCauseThat().isSameInstanceAs(throwable); } } @Test - @SuppressWarnings("CheckReturnValue") public void load_failure_expiry() { - try { - when(expiry.getExpiryForCreation()).thenThrow(IllegalStateException.class); - when(cacheLoader.load(any())).thenReturn(-1); - jcacheLoading.get(1); - Assert.fail(); - } catch (CacheLoaderException e) { - assertThat(e).hasCauseThat().isInstanceOf(IllegalStateException.class); - } + when(expiry.getExpiryForCreation()).thenThrow(IllegalStateException.class); + when(cacheLoader.load(any())).thenReturn(-1); + var e = assertThrows(CacheLoaderException.class, () -> jcacheLoading.get(1)); + assertThat(e).hasCauseThat().isInstanceOf(IllegalStateException.class); } @Test @@ -94,11 +84,10 @@ public void loadAll() { assertThat(result).containsExactly(1, -1, 2, -2, 3, -3); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = CacheLoaderException.class) + @Test public void loadAll_null() { when(cacheLoader.loadAll(anyIterable())).thenReturn(null); - jcacheLoading.getAll(Set.of(1, 2, 3)); + assertThrows(CacheLoaderException.class, () -> jcacheLoading.getAll(Set.of(1, 2, 3))); } @Test @@ -109,30 +98,20 @@ public void loadAll_nullMapping() { } @Test(dataProvider = "throwables") - @SuppressWarnings("CheckReturnValue") public void loadAll_failure(Throwable throwable) { - try { - when(cacheLoader.loadAll(any())).thenThrow(throwable); - jcacheLoading.getAll(Set.of(1, 2, 3)); - Assert.fail(); - } catch (CacheLoaderException e) { - if (e != throwable) { - assertThat(e).hasCauseThat().isSameInstanceAs(throwable); - } + when(cacheLoader.loadAll(any())).thenThrow(throwable); + var e = assertThrows(CacheLoaderException.class, () -> jcacheLoading.getAll(Set.of(1, 2, 3))); + if (e != throwable) { + assertThat(e).hasCauseThat().isSameInstanceAs(throwable); } } @Test - @SuppressWarnings("CheckReturnValue") public void loadAll_failure_expiry() { - try { - when(expiry.getExpiryForCreation()).thenThrow(IllegalStateException.class); - when(cacheLoader.loadAll(anyIterable())).thenReturn(Map.of(1, 1, 2, 2)); - jcacheLoading.getAll(Set.of(1, 2, 3)); - Assert.fail(); - } catch (CacheLoaderException e) { - assertThat(e).hasCauseThat().isInstanceOf(IllegalStateException.class); - } + when(expiry.getExpiryForCreation()).thenThrow(IllegalStateException.class); + when(cacheLoader.loadAll(anyIterable())).thenReturn(Map.of(1, 1, 2, 2)); + var e = assertThrows(CacheLoaderException.class, () -> jcacheLoading.getAll(Set.of(1, 2, 3))); + assertThat(e).hasCauseThat().isInstanceOf(IllegalStateException.class); } @DataProvider(name = "throwables") diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheWriterTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheWriterTest.java index 98468ee29b..05010163a7 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheWriterTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/integration/CacheWriterTest.java @@ -16,6 +16,7 @@ package com.github.benmanes.caffeine.jcache.integration; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doThrow; @@ -31,7 +32,6 @@ import javax.cache.integration.CacheWriterException; import org.mockito.Mockito; -import org.testng.Assert; import org.testng.annotations.Test; import com.github.benmanes.caffeine.jcache.AbstractJCacheTest; @@ -53,10 +53,10 @@ protected CaffeineConfiguration getConfiguration() { return configuration; } - @Test(expectedExceptions = CacheWriterException.class) + @Test public void put_fails() { doThrow(CacheWriterException.class).when(writer).write(any()); - jcache.put(KEY_1, VALUE_1); + assertThrows(CacheWriterException.class, () -> jcache.put(KEY_1, VALUE_1)); } @Test @@ -65,12 +65,8 @@ public void putAll_fails() { var map = new HashMap(); map.put(KEY_1, VALUE_1); - try { - jcache.putAll(map); - Assert.fail(); - } catch (CacheWriterException e) { - assertThat(map).containsExactly(KEY_1, VALUE_1); - } + assertThrows(CacheWriterException.class, () -> jcache.putAll(map)); + assertThat(map).containsExactly(KEY_1, VALUE_1); } @Test @@ -78,29 +74,25 @@ public void putAll_fails_immutable() { doThrow(CacheWriterException.class).when(writer).writeAll(any()); var map = Map.of(KEY_1, VALUE_1); - try { - jcache.putAll(map); - Assert.fail(); - } catch (CacheWriterException e) { - assertThat(map).containsExactly(KEY_1, VALUE_1); - } + assertThrows(CacheWriterException.class, () -> jcache.putAll(map)); + assertThat(map).containsExactly(KEY_1, VALUE_1); } - @Test(expectedExceptions = CacheWriterException.class) + @Test public void remove_fails() { jcache.put(KEY_1, VALUE_1); doThrow(CacheWriterException.class).when(writer).delete(any()); - jcache.remove(KEY_1); + assertThrows(CacheWriterException.class, () -> jcache.remove(KEY_1)); } - @Test(expectedExceptions = CacheWriterException.class) + @Test public void removeAll_fails() { doThrow(CacheWriterException.class).when(writer).deleteAll(any()); var keys = new HashSet(); keys.add(KEY_1); - jcache.removeAll(keys); + assertThrows(CacheWriterException.class, () -> jcache.removeAll(keys)); } @Test diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/management/JmxRegistrationTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/management/JmxRegistrationTest.java index 80f15cb624..625fde1cf1 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/management/JmxRegistrationTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/management/JmxRegistrationTest.java @@ -15,6 +15,7 @@ */ package com.github.benmanes.caffeine.jcache.management; +import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; @@ -39,28 +40,27 @@ */ public final class JmxRegistrationTest { - @Test(dataProvider = "registerExceptions", expectedExceptions = CacheException.class) + @Test(dataProvider = "registerExceptions") public void register_error(Class throwableType) throws JMException { var name = new ObjectName(""); var bean = new JCacheStatisticsMXBean(); var server = Mockito.mock(MBeanServer.class); when(server.registerMBean(bean, name)).thenThrow(throwableType); - JmxRegistration.register(server, name, bean); + assertThrows(CacheException.class, () -> JmxRegistration.register(server, name, bean)); } - @Test(dataProvider = "unegisterExceptions", expectedExceptions = CacheException.class) + @Test(dataProvider = "unegisterExceptions") public void unregister_error(Class throwableType) throws JMException { var name = new ObjectName(""); var server = Mockito.mock(MBeanServer.class); when(server.queryNames(any(), any())).thenReturn(Set.of(name)); doThrow(throwableType).when(server).unregisterMBean(any()); - JmxRegistration.unregister(server, name); + assertThrows(CacheException.class, () -> JmxRegistration.unregister(server, name)); } - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = CacheException.class) + @Test public void newObjectName_malformed() { - JmxRegistration.newObjectName("a=b"); + assertThrows(CacheException.class, () -> JmxRegistration.newObjectName("a=b")); } @DataProvider(name = "registerExceptions") diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorEntryTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorEntryTest.java index 2b511920ff..3b02f16d96 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorEntryTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorEntryTest.java @@ -16,6 +16,7 @@ package com.github.benmanes.caffeine.jcache.processor; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import java.util.Map; import java.util.Optional; @@ -30,10 +31,9 @@ public final class EntryProcessorEntryTest { EntryProcessorEntry entry = new EntryProcessorEntry<>(1, 2, Optional.empty()); - @SuppressWarnings("CheckReturnValue") - @Test(expectedExceptions = IllegalArgumentException.class) + @Test public void unwrap_fail() { - entry.unwrap(Map.Entry.class); + assertThrows(IllegalArgumentException.class, () -> entry.unwrap(Map.Entry.class)); } @Test diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorTest.java index b650189269..3523e0ed22 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/processor/EntryProcessorTest.java @@ -74,33 +74,36 @@ protected CaffeineConfiguration getConfiguration() { } @Test - @SuppressWarnings("CheckReturnValue") public void reload() { - jcache.invoke(KEY_1, this::process); + var value1 = jcache.invoke(KEY_1, this::process); assertThat(loads).isEqualTo(1); + assertThat(value1).isNull(); ticker.advance(1, TimeUnit.MINUTES); - jcache.invoke(KEY_1, this::process); + var value2 = jcache.invoke(KEY_1, this::process); assertThat(loads).isEqualTo(1); + assertThat(value2).isNull(); // Expire the entry ticker.advance(5, TimeUnit.MINUTES); - jcache.invoke(KEY_1, this::process); + var value3 = jcache.invoke(KEY_1, this::process); assertThat(loads).isEqualTo(2); + assertThat(value3).isNull(); ticker.advance(1, TimeUnit.MINUTES); - jcache.invoke(KEY_1, this::process); + var value4 = jcache.invoke(KEY_1, this::process); assertThat(loads).isEqualTo(2); + assertThat(value4).isNull(); } @Test - @SuppressWarnings("CheckReturnValue") public void writeOccursForInitialLoadOfEntry() { map.put(KEY_1, 100); - jcache.invoke(KEY_1, this::process); - assertThat(loads).isEqualTo(1); + var value = jcache.invoke(KEY_1, this::process); assertThat(writes).isEqualTo(1); + assertThat(loads).isEqualTo(1); + assertThat(value).isNull(); } private Object process(MutableEntry entry, Object... arguments) { diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/spi/CaffeineCachingProviderTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/spi/CaffeineCachingProviderTest.java index 3366ddf52a..8b6e59582f 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/spi/CaffeineCachingProviderTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/spi/CaffeineCachingProviderTest.java @@ -20,6 +20,7 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.io.UncheckedIOException; @@ -63,10 +64,8 @@ public void loadClass_found() { @Test public void loadClass_notFound() { runWithClassloader(provider -> { - try { - provider.getDefaultClassLoader().loadClass("a.b.c"); - Assert.fail(); - } catch (ClassNotFoundException expected) {} + assertThrows(ClassNotFoundException.class, () -> + provider.getDefaultClassLoader().loadClass("a.b.c")); }); }