From bd45ce79901becbdf52fd2535ff9485dd24fa95e Mon Sep 17 00:00:00 2001 From: Ben Manes Date: Mon, 30 Dec 2024 14:15:05 -0800 Subject: [PATCH] testing polish --- caffeine/build.gradle.kts | 18 +- .../benmanes/caffeine/cache/AsMapTest.java | 2 +- .../caffeine/cache/AsyncAsMapTest.java | 2 +- .../caffeine/cache/AsyncCacheTest.java | 2 +- .../caffeine/cache/AsyncLoadingCacheTest.java | 2 +- .../caffeine/cache/BoundedLocalCacheTest.java | 2 +- .../benmanes/caffeine/cache/CacheTest.java | 4 +- .../caffeine/cache/CaffeineSpecGuavaTest.java | 2 +- .../caffeine/cache/CaffeineSpecTest.java | 2 +- .../benmanes/caffeine/cache/CaffeineTest.java | 2 +- .../benmanes/caffeine/cache/EvictionTest.java | 2 +- .../caffeine/cache/ExpirationTest.java | 2 +- .../caffeine/cache/ExpireAfterAccessTest.java | 2 +- .../caffeine/cache/ExpireAfterVarTest.java | 2 +- .../caffeine/cache/ExpireAfterWriteTest.java | 2 +- .../caffeine/cache/FrequencySketchTest.java | 2 +- .../benmanes/caffeine/cache/InternerTest.java | 2 +- .../caffeine/cache/LinkedDequeTest.java | 2 +- .../caffeine/cache/LoadingCacheTest.java | 4 +- .../caffeine/cache/LocalCacheSubject.java | 2 +- .../cache/MpscGrowableArrayQueueTest.java | 2 +- .../benmanes/caffeine/cache/PacerTest.java | 75 +++-- .../caffeine/cache/QueueSanityTest.java | 2 +- .../caffeine/cache/ReferenceTest.java | 2 +- .../caffeine/cache/RefreshAfterWriteTest.java | 2 +- .../caffeine/cache/SchedulerTest.java | 2 +- .../caffeine/cache/TimerWheelTest.java | 132 +++++--- .../caffeine/cache/stats/CacheStatsTest.java | 2 +- .../testing/CacheValidationListener.java | 23 +- .../caffeine/fuzz/CaffeineSpecFuzzer.java | 5 +- examples/hibernate/build.gradle.kts | 2 +- examples/hibernate/gradle/libs.versions.toml | 2 +- gradle/libs.versions.toml | 10 +- .../lifecycle/testing.caffeine.gradle.kts | 10 - guava/build.gradle.kts | 5 +- .../caffeine/guava/CaffeinatedGuavaTest.java | 2 +- .../guava/compatibility/CacheBuilderTest.java | 2 +- .../guava/compatibility/CacheLoadingTest.java | 2 +- .../guava/compatibility/EmptyCachesTest.java | 2 +- .../LocalCacheMapComputeTest.java | 2 +- .../guava/compatibility/NullCacheTest.java | 2 +- .../compatibility/PopulatedCachesTest.java | 2 +- jcache/build.gradle.kts | 24 +- .../caffeine/jcache/CacheProxyTest.java | 2 +- .../JCacheConfigurationTest.java | 2 +- .../TypesafeConfigurationTest.java | 2 +- .../copy/JavaSerializationCopierTest.java | 2 +- .../jcache/event/EventDispatcherTest.java | 284 +++++++++--------- .../event/EventTypeAwareListenerTest.java | 35 +-- .../jcache/event/JCacheEntryEventTest.java | 75 ++--- .../event/JCacheEvictionListenerTest.java | 51 ++-- .../jcache/integration/CacheLoaderTest.java | 2 +- .../jcache/integration/CacheWriterTest.java | 2 +- .../management/JmxRegistrationTest.java | 2 +- .../processor/EntryProcessorEntryTest.java | 2 +- 55 files changed, 433 insertions(+), 402 deletions(-) diff --git a/caffeine/build.gradle.kts b/caffeine/build.gradle.kts index 84c2afdb22..6bbd2bfa26 100644 --- a/caffeine/build.gradle.kts +++ b/caffeine/build.gradle.kts @@ -32,30 +32,30 @@ dependencies { api(libs.jspecify) api(libs.errorprone.annotations) - testImplementation(libs.joor) testImplementation(libs.ycsb) { isTransitive = false } - testImplementation(libs.picocli) testImplementation(libs.jctools) - testImplementation(libs.fastutil) + testImplementation(libs.mockito) + testImplementation(libs.picocli) testImplementation(libs.lincheck) testImplementation(libs.commons.lang3) + testImplementation(libs.guava.testlib) testImplementation(libs.bundles.jazzer) + testImplementation(libs.bundles.awaitility) testImplementation(libs.bundles.slf4j.test) testImplementation(libs.commons.collections4) testImplementation(libs.commons.collections4) { - artifact { - classifier = "tests" - } + artifact { classifier = "tests" } } testImplementation(sourceSets["codeGen"].output) + testImplementation(libs.bundles.osgi.test.compile) testImplementation(libs.eclipse.collections.testutils) + testRuntimeOnly(libs.bundles.osgi.test.runtime) + collections4Sources(libs.commons.collections4) { - artifact { - classifier = "test-sources" - } + artifact { classifier = "test-sources" } } jammAgent(libs.jamm) { 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 9466536d18..7e9226c104 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 @@ -30,7 +30,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; 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 c4c0534b4b..8645f6eb4e 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 @@ -30,7 +30,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; 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 6a0cf023a6..8a4daeebfc 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 @@ -31,7 +31,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; 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 a0f20e2b84..be0efd1871 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 @@ -295,7 +295,7 @@ public void getAll_absent_partial(AsyncLoadingCache cache, CacheContex var expect = new ImmutableMap.Builder() .putAll(Maps.toMap(context.firstMiddleLastKeys(), Int::negate)) .putAll(Maps.toMap(context.absentKeys(), Int::negate)) - .build(); + .buildOrThrow(); var result = cache.getAll(expect.keySet()).join(); assertThat(result).isEqualTo(expect); 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 fd1fc5157a..a2aaa36979 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 @@ -51,7 +51,7 @@ 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.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; 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 975e48afb0..7dddfa14f4 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 @@ -27,7 +27,7 @@ import static com.google.common.truth.Truth.assertWithMessage; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.times; @@ -503,7 +503,7 @@ public void getAll_exceeds(Cache cache, CacheContext context) { var expected = new ImmutableMap.Builder() .putAll(context.original()) .putAll(context.absent()) - .build(); + .buildOrThrow(); assertThat(cache).containsExactlyEntriesIn(expected); assertThat(context).stats().hits(0).misses(result.size()).success(1).failures(0); assertThat(result).containsExactlyEntriesIn(Map.of(context.absentKey(), context.absentValue())); 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 4b01a97910..05219bbd87 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,7 +17,7 @@ import static com.github.benmanes.caffeine.cache.Caffeine.UNSET_INT; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Duration; import java.util.concurrent.TimeUnit; 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 183b7f966a..ba37b23086 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,7 +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 static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Duration; import java.util.ArrayList; 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 7b5edb7131..3d7ddcba11 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 @@ -18,7 +18,7 @@ import static com.github.benmanes.caffeine.testing.LoggingEvents.logEvents; 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.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.verify; import static org.slf4j.event.Level.WARN; 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 6047d5bdb8..408e5573a1 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 @@ -32,7 +32,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.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.slf4j.event.Level.WARN; 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 f66aa1c8a7..64a1d3f9f9 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 @@ -30,7 +30,7 @@ import static com.google.common.base.Functions.identity; import static com.google.common.truth.Truth.assertThat; import static java.util.Map.entry; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; 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 16f92589aa..b6c436f713 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 @@ -28,7 +28,7 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static java.util.Objects.requireNonNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.slf4j.event.Level.WARN; import java.time.Duration; 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 8c2579cf71..16239de406 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 @@ -36,7 +36,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.times; 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 a13a8c190b..3dd06192cb 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 @@ -28,7 +28,7 @@ import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.truth.Truth.assertThat; import static java.util.Objects.requireNonNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.slf4j.event.Level.WARN; import java.time.Duration; 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 c9124e89b6..296ce169a1 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,7 +16,7 @@ package com.github.benmanes.caffeine.cache; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.concurrent.ThreadLocalRandom; 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 c72e9fad5f..8993212672 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,7 +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 static org.junit.jupiter.api.Assertions.assertThrows; import java.lang.ref.WeakReference; import java.util.Arrays; 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 a5e8b2d8db..aee1f65f85 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 @@ -19,7 +19,7 @@ import static com.google.common.collect.Iterators.elementsEqual; import static com.google.common.truth.Truth.assertThat; import static java.util.Objects.requireNonNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; import java.util.Collection; 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 6f7fc11d3b..98743223a5 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 @@ -35,7 +35,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.slf4j.event.Level.TRACE; import static org.slf4j.event.Level.WARN; @@ -300,7 +300,7 @@ public void getAll_absent_partial(LoadingCache cache, CacheContext con var expect = new ImmutableMap.Builder() .putAll(Maps.toMap(context.firstMiddleLastKeys(), Int::negate)) .putAll(Maps.toMap(context.absentKeys(), Int::negate)) - .build(); + .buildOrThrow(); var result = cache.getAll(expect.keySet()); assertThat(result).isEqualTo(expect); diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LocalCacheSubject.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LocalCacheSubject.java index 13890f5654..63c5f7e239 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LocalCacheSubject.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/LocalCacheSubject.java @@ -270,7 +270,7 @@ private void checkEvictionDeque(BoundedLocalCache bounded) { .put("probation", mainProbation, bounded.accessOrderProbationDeque()) .put("protected", bounded.mainProtectedWeightedSize(), bounded.accessOrderProtectedDeque()) - .build(); + .buildOrThrow(); checkLinks(bounded, deques); check("accessOrderWindowDeque()").about(deque()) .that(bounded.accessOrderWindowDeque()).isValid(); 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 290bfc2441..b44479e4c9 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,7 +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 static org.junit.jupiter.api.Assertions.assertThrows; import java.util.concurrent.atomic.AtomicInteger; diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/PacerTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/PacerTest.java index 8d76b4c9a1..32b1c6b21d 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/PacerTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/PacerTest.java @@ -20,7 +20,6 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import static org.mockito.quality.Strictness.STRICT_STUBS; import java.util.Random; import java.util.concurrent.CompletableFuture; @@ -28,11 +27,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import org.mockito.Mock; -import org.mockito.testng.MockitoSettings; -import org.mockito.testng.MockitoTestNGListener; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Listeners; +import org.mockito.Mockito; import org.testng.annotations.Test; import com.google.common.primitives.Ints; @@ -40,28 +35,19 @@ /** * @author ben.manes@gmail.com (Ben Manes) */ -@Test(singleThreaded = true) -@Listeners(MockitoTestNGListener.class) -@MockitoSettings(strictness = STRICT_STUBS) public final class PacerTest { private static final long ONE_MINUTE_IN_NANOS = TimeUnit.MINUTES.toNanos(1); private static final Random random = new Random(); private static final long NOW = random.nextLong(); - @Mock Scheduler scheduler; - @Mock Executor executor; - @Mock Runnable command; - @Mock Future future; - - Pacer pacer; - - @BeforeMethod - public void beforeMethod() { - pacer = new Pacer(scheduler); - } - @Test public void schedule_initialize() { + Scheduler scheduler = Mockito.mock(); + Executor executor = Mockito.mock(); + Runnable command = Mockito.mock(); + Future future = Mockito.mock(); + var pacer = new Pacer(scheduler); + long delay = random.nextInt(Ints.saturatedCast(Pacer.TOLERANCE)); when(scheduler.schedule(executor, command, Pacer.TOLERANCE, TimeUnit.NANOSECONDS)) .then(invocation -> future); @@ -74,6 +60,12 @@ public void schedule_initialize() { @Test public void schedule_initialize_recurse() { + Scheduler scheduler = Mockito.mock(); + Executor executor = Mockito.mock(); + Runnable command = Mockito.mock(); + Future future = Mockito.mock(); + var pacer = new Pacer(scheduler); + long delay = random.nextInt(Ints.saturatedCast(Pacer.TOLERANCE)); when(scheduler.schedule(executor, command, Pacer.TOLERANCE, TimeUnit.NANOSECONDS)) .then(invocation -> { @@ -92,6 +84,12 @@ public void schedule_initialize_recurse() { @Test public void schedule_cancel_schedule() { + Scheduler scheduler = Mockito.mock(); + Executor executor = Mockito.mock(); + Runnable command = Mockito.mock(); + Future future = Mockito.mock(); + var pacer = new Pacer(scheduler); + long fireTime = NOW + Pacer.TOLERANCE; long delay = random.nextInt(Ints.saturatedCast(Pacer.TOLERANCE)); when(scheduler.schedule(executor, command, Pacer.TOLERANCE, TimeUnit.NANOSECONDS)) @@ -116,6 +114,12 @@ public void schedule_cancel_schedule() { @Test public void scheduled_afterNextFireTime_skip() { + Scheduler scheduler = Mockito.mock(); + Executor executor = Mockito.mock(); + Runnable command = Mockito.mock(); + Future future = Mockito.mock(); + var pacer = new Pacer(scheduler); + pacer.nextFireTime = NOW + ONE_MINUTE_IN_NANOS; pacer.future = future; @@ -130,6 +134,12 @@ public void scheduled_afterNextFireTime_skip() { @Test public void schedule_beforeNextFireTime_skip() { + Scheduler scheduler = Mockito.mock(); + Executor executor = Mockito.mock(); + Runnable command = Mockito.mock(); + Future future = Mockito.mock(); + var pacer = new Pacer(scheduler); + pacer.nextFireTime = NOW + ONE_MINUTE_IN_NANOS; pacer.future = future; @@ -146,6 +156,12 @@ public void schedule_beforeNextFireTime_skip() { @Test public void schedule_beforeNextFireTime_minimumDelay() { + Scheduler scheduler = Mockito.mock(); + Executor executor = Mockito.mock(); + Runnable command = Mockito.mock(); + Future future = Mockito.mock(); + var pacer = new Pacer(scheduler); + pacer.nextFireTime = NOW + ONE_MINUTE_IN_NANOS; pacer.future = future; @@ -167,6 +183,12 @@ public void schedule_beforeNextFireTime_minimumDelay() { @Test public void schedule_beforeNextFireTime_customDelay() { + Scheduler scheduler = Mockito.mock(); + Executor executor = Mockito.mock(); + Runnable command = Mockito.mock(); + Future future = Mockito.mock(); + var pacer = new Pacer(scheduler); + pacer.nextFireTime = NOW + ONE_MINUTE_IN_NANOS; pacer.future = future; @@ -188,6 +210,8 @@ public void schedule_beforeNextFireTime_customDelay() { @Test public void cancel_initialize() { + var pacer = new Pacer(Mockito.mock()); + pacer.cancel(); assertThat(pacer.nextFireTime).isEqualTo(0); assertThat(pacer.isScheduled()).isFalse(); @@ -196,6 +220,9 @@ public void cancel_initialize() { @Test public void cancel_scheduled() { + Future future = Mockito.mock(); + var pacer = new Pacer(Mockito.mock()); + pacer.nextFireTime = NOW + ONE_MINUTE_IN_NANOS; pacer.future = future; @@ -208,18 +235,24 @@ public void cancel_scheduled() { @Test public void isScheduled_nullFuture() { + var pacer = new Pacer(Mockito.mock()); + pacer.future = null; assertThat(pacer.isScheduled()).isFalse(); } @Test public void isScheduled_doneFuture() { + var pacer = new Pacer(Mockito.mock()); + pacer.future = DisabledFuture.instance(); assertThat(pacer.isScheduled()).isFalse(); } @Test public void isScheduled_inFlight() { + var pacer = new Pacer(Mockito.mock()); + pacer.future = new CompletableFuture<>(); assertThat(pacer.isScheduled()).isTrue(); } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/QueueSanityTest.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/QueueSanityTest.java index a755a9e385..7539fbf828 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/QueueSanityTest.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/QueueSanityTest.java @@ -22,9 +22,9 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Collection; import java.util.Queue; 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 6a75f03686..6c89d6add6 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 @@ -32,7 +32,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.when; 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 409ac55842..d734846c62 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 @@ -33,7 +33,7 @@ import static java.util.Objects.requireNonNull; import static java.util.function.Function.identity; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.slf4j.event.Level.WARN; import java.time.Duration; 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 8225640a88..ccb42d1776 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 @@ -24,7 +24,7 @@ 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.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; 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 99ac348f83..1cd406df5d 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,7 +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.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doThrow; @@ -29,7 +29,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import static org.mockito.quality.Strictness.LENIENT; import java.lang.ref.ReferenceQueue; import java.time.Duration; @@ -48,53 +47,30 @@ import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; -import org.mockito.testng.MockitoSettings; -import org.mockito.testng.MockitoTestNGListener; -import org.testng.ITestResult; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; +import org.mockito.Mockito; import org.testng.annotations.DataProvider; -import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.github.benmanes.caffeine.cache.TimerWheel.Sentinel; import com.google.common.collect.Streams; -import it.unimi.dsi.fastutil.longs.LongArrayList; -import it.unimi.dsi.fastutil.longs.LongList; - /** * @author ben.manes@gmail.com (Ben Manes) */ -@Test(singleThreaded = true) -@MockitoSettings(strictness = LENIENT) -@Listeners(MockitoTestNGListener.class) @SuppressWarnings({"ClassEscapesDefinedScope", "GuardedBy"}) public final class TimerWheelTest { private static final Random random = new Random(); private static final long[] CLOCKS = { Long.MIN_VALUE, -SPANS[0] + 1, 0L, 0xfffffffc0000000L, Long.MAX_VALUE - SPANS[0] + 1, Long.MAX_VALUE, random.nextLong() }; - @Captor ArgumentCaptor> captor; - @Mock BoundedLocalCache cache; - TimerWheel timerWheel; - - @BeforeMethod - public void beforeMethod() { - timerWheel = new TimerWheel<>(); - } - - @AfterMethod - public void afterMethod(ITestResult testResult) { - if (!testResult.isSuccess()) { - printTimerWheel(); - } - } + // Use printTimerWheel(timerWheel) to debug @Test(dataProvider = "schedule") public void schedule(long clock, long duration, int expired) { + ArgumentCaptor> captor = ArgumentCaptor.captor(); + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; @@ -111,6 +87,10 @@ public void schedule(long clock, long duration, int expired) { @Test(dataProvider = "fuzzySchedule") public void schedule_fuzzy(long clock, long duration, long[] times) { + ArgumentCaptor> captor = ArgumentCaptor.captor(); + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; @@ -127,11 +107,15 @@ public void schedule_fuzzy(long clock, long duration, long[] times) { for (Node node : captor.getAllValues()) { assertThat(node.getVariableTime()).isAtMost(duration); } - checkTimerWheel(duration); + checkTimerWheel(timerWheel, duration); } @Test(dataProvider = "clock") public void advance(long clock) { + ArgumentCaptor> captor = ArgumentCaptor.captor(); + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; @@ -143,6 +127,10 @@ public void advance(long clock) { @Test public void advance_overflow() { + ArgumentCaptor> captor = ArgumentCaptor.captor(); + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); timerWheel.nanos = -TimeUnit.DAYS.toNanos(365) / 2; @@ -154,8 +142,10 @@ public void advance_overflow() { @Test(dataProvider = "clock") public void advance_backwards(long clock) { - timerWheel.nanos = clock; + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + timerWheel.nanos = clock; for (int i = 0; i < 1_000; i++) { long duration = ThreadLocalRandom.current().nextLong(TimeUnit.DAYS.toNanos(10)); timerWheel.schedule(new Timer(clock + duration)); @@ -169,6 +159,10 @@ public void advance_backwards(long clock) { @Test(dataProvider = "clock") public void advance_reschedule(long clock) { + ArgumentCaptor> captor = ArgumentCaptor.captor(); + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; @@ -194,6 +188,10 @@ public void advance_reschedule(long clock) { @Test public void advance_exception() { + ArgumentCaptor> captor = ArgumentCaptor.captor(); + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + doThrow(new IllegalArgumentException()) .when(cache).evictEntry(captor.capture(), any(), anyLong()); var timer = new Timer(timerWheel.nanos + SPANS[1]); @@ -207,12 +205,16 @@ public void advance_exception() { @Test(dataProvider = "clock") public void getExpirationDelay_empty(long clock) { + var timerWheel = new TimerWheel(); + timerWheel.nanos = clock; assertThat(timerWheel.getExpirationDelay()).isEqualTo(Long.MAX_VALUE); } @Test(dataProvider = "clock") public void getExpirationDelay_firstWheel(long clock) { + var timerWheel = new TimerWheel(); + timerWheel.nanos = clock; long delay = Duration.ofSeconds(1).toNanos(); timerWheel.schedule(new Timer(clock + delay)); @@ -221,6 +223,8 @@ public void getExpirationDelay_firstWheel(long clock) { @Test(dataProvider = "clock") public void getExpirationDelay_lastWheel(long clock) { + var timerWheel = new TimerWheel(); + timerWheel.nanos = clock; long delay = Duration.ofDays(14).toNanos(); timerWheel.schedule(new Timer(clock + delay)); @@ -229,6 +233,9 @@ public void getExpirationDelay_lastWheel(long clock) { @Test(dataProvider = "clock") public void getExpirationDelay_hierarchy(long clock) { + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + when(cache.evictEntry(any(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; @@ -250,6 +257,9 @@ public void getExpirationDelay_hierarchy(long clock) { @Test(dataProvider = "fuzzySchedule", invocationCount = 25) public void getExpirationDelay_fuzzy(long clock, long duration, long[] times) { + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + when(cache.evictEntry(any(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; for (long timeout : times) { @@ -263,8 +273,7 @@ public void getExpirationDelay_fuzzy(long clock, long duration, long[] times) { for (int i = 0; i < timerWheel.wheel.length; i++) { for (int j = 0; j < timerWheel.wheel[i].length; j++) { var timers = getTimers(timerWheel.wheel[i][j]); - for (int k = 0; k < timers.size(); k++) { - long delay = timers.getLong(k); + for (long delay : timers) { if (delay < minDelay) { minDelay = delay; minBucket = j; @@ -318,7 +327,7 @@ public Object[][] providesFuzzySchedule() { return new Object[][] {{ clock, duration, times }}; } - private void checkTimerWheel(long duration) { + private static void checkTimerWheel(TimerWheel timerWheel, long duration) { for (int i = 0; i < timerWheel.wheel.length; i++) { for (int j = 0; j < timerWheel.wheel[i].length; j++) { for (long timer : getTimers(timerWheel.wheel[i][j])) { @@ -331,8 +340,8 @@ private void checkTimerWheel(long duration) { } } - private static LongList getTimers(Node sentinel) { - var timers = new LongArrayList(); + private static List getTimers(Node sentinel) { + var timers = new ArrayList(); for (var node = sentinel.getNextInVariableOrder(); node != sentinel; node = node.getNextInVariableOrder()) { timers.add(node.getVariableTime()); @@ -342,6 +351,10 @@ private static LongList getTimers(Node sentinel) { @Test(dataProvider = "clock") public void reschedule(long clock) { + ArgumentCaptor> captor = ArgumentCaptor.captor(); + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + when(cache.evictEntry(captor.capture(), any(), anyLong())).thenReturn(true); timerWheel.nanos = clock; @@ -354,10 +367,10 @@ public void reschedule(long clock) { assertThat(timer.getNextInVariableOrder()).isNotSameInstanceAs(startBucket); timerWheel.advance(cache, clock + TimeUnit.DAYS.toNanos(1)); - checkEmpty(); + checkEmpty(timerWheel); } - private void checkEmpty() { + private static void checkEmpty(TimerWheel timerWheel) { for (var wheel : timerWheel.wheel) { for (var sentinel : wheel) { assertThat(sentinel.getNextInVariableOrder()).isSameInstanceAs(sentinel); @@ -368,6 +381,8 @@ private void checkEmpty() { @Test(dataProvider = "clock") public void deschedule(long clock) { + var timerWheel = new TimerWheel(); + var timer = new Timer(clock + 100); timerWheel.nanos = clock; timerWheel.schedule(timer); @@ -378,12 +393,15 @@ public void deschedule(long clock) { @Test(dataProvider = "clock") public void deschedule_notScheduled(long clock) { + var timerWheel = new TimerWheel(); + timerWheel.nanos = clock; timerWheel.deschedule(new Timer(clock + 100)); } @Test(dataProvider = "fuzzySchedule") public void deschedule_fuzzy(long clock, long nanos, long[] times) { + var timerWheel = new TimerWheel(); var timers = new ArrayList(); timerWheel.nanos = clock; @@ -395,11 +413,15 @@ public void deschedule_fuzzy(long clock, long nanos, long[] times) { for (Timer timer : timers) { timerWheel.deschedule(timer); } - checkTimerWheel(nanos); + checkTimerWheel(timerWheel, nanos); } @Test(dataProvider = "clock") public void expire_reschedule(long clock) { + ArgumentCaptor> captor = ArgumentCaptor.captor(); + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + when(cache.evictEntry(captor.capture(), any(), anyLong())).then(invocation -> { Timer timer = invocation.getArgument(0); timer.setVariableTime(timerWheel.nanos + 100); @@ -417,6 +439,9 @@ public void expire_reschedule(long clock) { @Test(dataProvider = "cascade") public void cascade(long clock, long duration, long timeout, int span) { + BoundedLocalCache cache = Mockito.mock(); + var timerWheel = new TimerWheel(); + timerWheel.nanos = clock; timerWheel.schedule(new Timer(clock + timeout)); timerWheel.advance(cache, clock + duration); @@ -445,7 +470,8 @@ public Iterator providesCascade() { } @Test(dataProvider = "iterator") - public void iterator_hasNext(Iterable> iterable) { + public void iterator_hasNext( + TimerWheel timerWheel, Iterable> iterable) { var iterator = iterable.iterator(); assertThat(iterator.hasNext()).isFalse(); @@ -465,13 +491,17 @@ public void iterator_hasNext(Iterable> iterable) { @DataProvider(name = "iterator") @SuppressWarnings({"MethodReferenceUsage", "PMD.LambdaCanBeMethodReference"}) public Object[][] providesIterators() { - Iterable> descending = () -> timerWheel.descendingIterator(); - Iterable> ascending = () -> timerWheel.iterator(); - return new Object[][] {{ascending}, {descending}}; + var ascendingTimerWheel = new TimerWheel(); + var descendingTimerWheel = new TimerWheel(); + Iterable> ascending = ascendingTimerWheel; + Iterable> descending = descendingTimerWheel::descendingIterator; + return new Object[][] {{ascendingTimerWheel, ascending}, {descendingTimerWheel, descending}}; } @Test(dataProvider = "clock") public void iterator_fixed(long clock) { + var timerWheel = new TimerWheel(); + timerWheel.nanos = clock; var input = IntStream.range(0, 21).mapToLong(i -> { long time = clock + TimeUnit.SECONDS.toNanos(2L << i); @@ -490,6 +520,8 @@ public void iterator_fixed(long clock) { @Test(invocationCount = 25) public void iterator_random() { + var timerWheel = new TimerWheel(); + int range = ThreadLocalRandom.current().nextInt(0, 1000); timerWheel.nanos = ThreadLocalRandom.current().nextLong( TimeUnit.MILLISECONDS.toNanos(500), TimeUnit.DAYS.toNanos(7)); @@ -504,11 +536,13 @@ public void iterator_random() { var ascending = Streams.stream(timerWheel.iterator()) .limit(range + 1).map(Node::getKey).collect(toImmutableList()); assertThat(ascending).containsExactlyElementsIn(input); - assertThat(ascending).containsExactlyElementsIn(snapshot(/* ascending= */ true)).inOrder(); + assertThat(ascending).containsExactlyElementsIn( + snapshot(timerWheel, /* ascending= */ true)).inOrder(); var descending = Streams.stream(timerWheel.descendingIterator()) .limit(range + 1).map(Node::getKey).collect(toImmutableList()); - assertThat(descending).containsExactlyElementsIn(snapshot(/* ascending= */ false)).inOrder(); + assertThat(descending).containsExactlyElementsIn( + snapshot(timerWheel, /* ascending= */ false)).inOrder(); assertThat(descending).containsExactlyElementsIn(input); } @@ -535,7 +569,7 @@ public void sentinel_unsupported() { } /** Returns a snapshot roughly ordered by the expiration time. */ - private List snapshot(boolean ascending) { + private static List snapshot(TimerWheel timerWheel, boolean ascending) { var snapshot = new ArrayList(); int startLevel = ascending ? 0 : timerWheel.wheel.length - 1; Function, Node> successor = @@ -560,7 +594,7 @@ private List snapshot(boolean ascending) { } @SuppressWarnings("SystemOut") - private void printTimerWheel() { + static void printTimerWheel(TimerWheel timerWheel) { var builder = new StringBuilder(); for (int i = 0; i < timerWheel.wheel.length; i++) { int ticks = (int) (timerWheel.nanos >>> SHIFT[i]); 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 e4df7b5901..33c78a007a 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,7 +16,7 @@ package com.github.benmanes.caffeine.cache.stats; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheValidationListener.java b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheValidationListener.java index 3351814974..e0536ec595 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheValidationListener.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/cache/testing/CacheValidationListener.java @@ -33,7 +33,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.lang3.StringUtils; -import org.joor.Reflect; import org.mockito.Mockito; import org.slf4j.bridge.SLF4JBridgeHandler; import org.slf4j.event.Level; @@ -44,8 +43,6 @@ import org.testng.ISuiteListener; import org.testng.ITestContext; import org.testng.ITestResult; -import org.testng.SuiteRunner; -import org.testng.TestListenerAdapter; import org.testng.TestRunner; import org.testng.internal.TestResult; @@ -81,12 +78,6 @@ public final class CacheValidationListener implements ISuiteListener, IInvokedMe @Override public void onStart(ISuite suite) { - if (suite instanceof SuiteRunner) { - var invokedMethods = Reflect.on(suite).fields().get("invokedMethods"); - if ((invokedMethods != null) && (invokedMethods.get() instanceof Collection)) { - resultQueues.add(invokedMethods.get()); - } - } SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); } @@ -102,25 +93,13 @@ public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { return; } - // Remove unused listener that retains all test results - // https://github.com/cbeust/testng/issues/2096#issuecomment-706643074 + // Remove unused test results if (testResult.getTestContext() instanceof TestRunner) { var runner = (TestRunner) testResult.getTestContext(); - runner.getTestListeners().stream() - .filter(listener -> listener.getClass() == TestListenerAdapter.class) - .flatMap(listener -> Reflect.on(listener).fields().values().stream()) - .filter(field -> field.get() instanceof Collection) - .forEach(field -> resultQueues.add(field.get())); - resultQueues.add(runner.getFailedButWithinSuccessPercentageTests().getAllResults()); resultQueues.add(runner.getSkippedTests().getAllResults()); resultQueues.add(runner.getPassedTests().getAllResults()); resultQueues.add(runner.getFailedTests().getAllResults()); - - var invokedMethods = Reflect.on(runner).fields().get("m_invokedMethods"); - if ((invokedMethods != null) && (invokedMethods.get() instanceof Collection)) { - resultQueues.add(invokedMethods.get()); - } } } diff --git a/caffeine/src/test/java/com/github/benmanes/caffeine/fuzz/CaffeineSpecFuzzer.java b/caffeine/src/test/java/com/github/benmanes/caffeine/fuzz/CaffeineSpecFuzzer.java index 67d816986a..b0ba42a767 100644 --- a/caffeine/src/test/java/com/github/benmanes/caffeine/fuzz/CaffeineSpecFuzzer.java +++ b/caffeine/src/test/java/com/github/benmanes/caffeine/fuzz/CaffeineSpecFuzzer.java @@ -15,6 +15,8 @@ */ package com.github.benmanes.caffeine.fuzz; +import static com.google.common.truth.Truth.assertThat; + import com.code_intelligence.jazzer.junit.FuzzTest; import com.code_intelligence.jazzer.mutation.annotation.NotNull; import com.github.benmanes.caffeine.cache.CaffeineSpec; @@ -27,10 +29,9 @@ public final class CaffeineSpecFuzzer { // These tests require the environment variable JAZZER_FUZZ=1 to try new input arguments @FuzzTest(maxDuration = "5m") - @SuppressWarnings("CheckReturnValue") public void parse(@NotNull String specification) { try { - CaffeineSpec.parse(specification); + assertThat(CaffeineSpec.parse(specification)).isNotNull(); } catch (IllegalArgumentException expected) { /* ignored */ } } } diff --git a/examples/hibernate/build.gradle.kts b/examples/hibernate/build.gradle.kts index 85b2448d36..7ea5cdc31d 100644 --- a/examples/hibernate/build.gradle.kts +++ b/examples/hibernate/build.gradle.kts @@ -8,7 +8,7 @@ plugins { } dependencies { - annotationProcessor(libs.hibernate.jpamodelgen) + annotationProcessor(libs.hibernate.processor) implementation(libs.bundles.hibernate) implementation(libs.bundles.log4j2) diff --git a/examples/hibernate/gradle/libs.versions.toml b/examples/hibernate/gradle/libs.versions.toml index 13e3044755..f8c181ca81 100644 --- a/examples/hibernate/gradle/libs.versions.toml +++ b/examples/hibernate/gradle/libs.versions.toml @@ -12,7 +12,7 @@ caffeine = { module = "com.github.ben-manes.caffeine:jcache", version.ref = "caf h2 = { module = "com.h2database:h2", version.ref = "h2" } hibernate-core = { module = "org.hibernate.orm:hibernate-core", version.ref = "hibernate" } hibernate-jcache = { module = "org.hibernate.orm:hibernate-jcache", version.ref = "hibernate" } -hibernate-jpamodelgen = { module = "org.hibernate.orm:hibernate-jpamodelgen", version.ref = "hibernate" } +hibernate-processor = { module = "org.hibernate.orm:hibernate-processor", version.ref = "hibernate" } hibernate-hikaricp = { module = "org.hibernate.orm:hibernate-hikaricp", version.ref = "hibernate" } junit = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" } log4j2-core = { module = "org.apache.logging.log4j:log4j-core", version.ref = "log4j2" } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 02137f4e9c..7c60625e97 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -7,7 +7,7 @@ bnd = "7.1.0" bouncycastle-jdk18on = "1.79" cache2k = "2.6.1.Final" caffeine = "3.1.8" -checkstyle = "10.21.0" +checkstyle = "10.21.1" coherence = "24.09" commons-collections4 = "4.4" commons-compress = "1.27.1" @@ -56,7 +56,6 @@ jgit = "7.1.0.202411261347-r" jmh = "1.37" jmh-plugin = "0.7.2" jmh-report = "0.9.6" -joor = "0.9.15" jspecify = "1.0.0" json-bind = "1.0" jsoup = "1.18.3" @@ -67,7 +66,6 @@ jvm-dependency-conflict-resolution = "2.1.2" kotlin = "2.1.0" lincheck = "2.34" mockito = "5.14.2" -mockito-testng = "0.5.2" nexus-publish = "2.0.0" nullaway = "0.12.2" nullaway-plugin = "2.1.0" @@ -79,7 +77,7 @@ osgi-promise = "1.3.0" pax-exam = "4.14.0" pax-url = "2.6.15" picocli = "4.7.6" -pmd = "7.8.0" +pmd = "7.9.0" protobuf = "4.29.2" slf4j = "2.0.16" slf4j-test = "3.0.1" @@ -161,7 +159,6 @@ jctools = { module = "org.jctools:jctools-core", version.ref = "jctools" } jfreechart = { module = "org.jfree:jfreechart", version.ref = "jfreechart" } jgit = { module = "org.eclipse.jgit:org.eclipse.jgit", version.ref = "jgit" } jmh = { module = "org.openjdk.jmh:jmh-core", version.ref = "jmh" } -joor = { module = "org.jooq:joor", version.ref = "joor" } jspecify = { module = "org.jspecify:jspecify", version.ref = "jspecify" } json-bind = { module = "javax.json.bind:javax.json.bind-api", version.ref = "json-bind" } jsoup = { module = "org.jsoup:jsoup", version.ref = "jsoup" } @@ -174,7 +171,6 @@ junit5-vintage = { module = "org.junit.vintage:junit-vintage-engine", version.re kotlin-bom = { module = "org.jetbrains.kotlin:kotlin-bom", version.ref = "kotlin" } lincheck = { module = "org.jetbrains.kotlinx:lincheck-jvm", version.ref = "lincheck" } mockito = { module = "org.mockito:mockito-core", version.ref = "mockito" } -mockito-testng = { module = "org.mockito:mockito-testng", version.ref = "mockito-testng" } nullaway = { module = "com.uber.nullaway:nullaway", version.ref = "nullaway" } nullaway-annotations = { module = "com.uber.nullaway:nullaway-annotations", version.ref = "nullaway" } okhttp-bom = { module = "com.squareup.okhttp3:okhttp-bom", version.ref = "okhttp-bom" } @@ -210,6 +206,7 @@ zero-allocation-hashing = { module = "net.openhft:zero-allocation-hashing", vers zstd = { module = "com.github.luben:zstd-jni", version.ref = "zstd" } [bundles] +awaitility = ["awaitility", "hamcrest"] coherence = ["coherence", "json-bind"] constraints = ["bcel", "bouncycastle-jdk18on", "commons-compress", "commons-text", "h2", "httpclient", "guava", "jcommander", "jgit", "jsoup", "protobuf", "snakeyaml"] @@ -217,7 +214,6 @@ errorprone-support = ["errorprone-support", "errorprone-support-refaster"] jazzer = ["jazzer", "jazzer-junit"] junit = ["junit4", "junit5"] junit-engines = ["junit5-vintage", "junit5-testng"] -mockito = ["mockito", "mockito-testng"] osgi-test-compile = ["pax-exam-junit4"] osgi-test-runtime = ["felix-framework", "felix-scr", "osgi-function", "osgi-promise", "pax-exam-container-native", "pax-exam-link-mvn", "pax-url-aether"] diff --git a/gradle/plugins/src/main/kotlin/lifecycle/testing.caffeine.gradle.kts b/gradle/plugins/src/main/kotlin/lifecycle/testing.caffeine.gradle.kts index d50e839965..892f3b727a 100644 --- a/gradle/plugins/src/main/kotlin/lifecycle/testing.caffeine.gradle.kts +++ b/gradle/plugins/src/main/kotlin/lifecycle/testing.caffeine.gradle.kts @@ -12,25 +12,15 @@ plugins { val mockitoAgent: Configuration by configurations.creating dependencies { - testImplementation(libs.guava) - testImplementation(libs.guice) testImplementation(libs.truth) testImplementation(libs.testng) - testImplementation(libs.hamcrest) - testImplementation(libs.awaitility) testImplementation(libs.bundles.junit) - testImplementation(libs.guava.testlib) - testImplementation(libs.bundles.mockito) - testImplementation(libs.nullaway.annotations) - testImplementation(libs.bundles.osgi.test.compile) - testImplementation(platform(libs.asm.bom)) testImplementation(platform(libs.kotlin.bom)) testImplementation(platform(libs.junit5.bom)) testRuntimeOnly(libs.junit5.launcher) testRuntimeOnly(libs.bundles.junit.engines) - testRuntimeOnly(libs.bundles.osgi.test.runtime) mockitoAgent(libs.mockito) { isTransitive = false diff --git a/guava/build.gradle.kts b/guava/build.gradle.kts index d494d15d69..12fd63f5e2 100644 --- a/guava/build.gradle.kts +++ b/guava/build.gradle.kts @@ -10,8 +10,11 @@ dependencies { api(project(":caffeine")) api(libs.guava) - testImplementation(libs.jctools) + testImplementation(libs.guava.testlib) testImplementation(libs.bundles.slf4j.nop) + testImplementation(libs.bundles.osgi.test.compile) + + testRuntimeOnly(libs.bundles.osgi.test.runtime) } tasks.named("compileJava").configure { 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 f43d044be0..307fac1ed9 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,8 +16,8 @@ package com.github.benmanes.caffeine.guava; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Constructor; diff --git a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheBuilderTest.java b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheBuilderTest.java index 3b81777439..ef795dfc14 100644 --- a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheBuilderTest.java +++ b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheBuilderTest.java @@ -27,7 +27,7 @@ import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Duration; import java.util.Collections; diff --git a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheLoadingTest.java b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheLoadingTest.java index 959f726311..622e03c5da 100644 --- a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheLoadingTest.java +++ b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/CacheLoadingTest.java @@ -23,7 +23,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Duration; import java.util.List; diff --git a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/EmptyCachesTest.java b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/EmptyCachesTest.java index cfefd324e4..a17b0564af 100644 --- a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/EmptyCachesTest.java +++ b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/EmptyCachesTest.java @@ -19,7 +19,7 @@ import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Collection; import java.util.Map; diff --git a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/LocalCacheMapComputeTest.java b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/LocalCacheMapComputeTest.java index c6247c86ec..cd9f524b7b 100644 --- a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/LocalCacheMapComputeTest.java +++ b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/LocalCacheMapComputeTest.java @@ -16,7 +16,7 @@ package com.github.benmanes.caffeine.guava.compatibility; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.concurrent.TimeUnit; import java.util.function.IntConsumer; diff --git a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/NullCacheTest.java b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/NullCacheTest.java index 50341c3bad..d78ac27959 100644 --- a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/NullCacheTest.java +++ b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/NullCacheTest.java @@ -20,7 +20,7 @@ import static com.github.benmanes.caffeine.guava.compatibility.TestingRemovalListeners.queuingRemovalListener; import static com.google.common.truth.Truth.assertThat; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.jspecify.annotations.NullUnmarked; diff --git a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/PopulatedCachesTest.java b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/PopulatedCachesTest.java index 04cc386861..5a2598e3b7 100644 --- a/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/PopulatedCachesTest.java +++ b/guava/src/test/java/com/github/benmanes/caffeine/guava/compatibility/PopulatedCachesTest.java @@ -20,7 +20,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Arrays; import java.util.Collection; diff --git a/jcache/build.gradle.kts b/jcache/build.gradle.kts index 3b2224368e..72c5b82f93 100644 --- a/jcache/build.gradle.kts +++ b/jcache/build.gradle.kts @@ -30,31 +30,31 @@ dependencies { api(libs.jcache) api(libs.config) + testImplementation(libs.guice) + testImplementation(libs.mockito) testImplementation(libs.jcache.guice) + testImplementation(libs.guava.testlib) testImplementation(libs.bundles.slf4j.nop) testImplementation(files(testResourcesJar)) + testImplementation(libs.bundles.awaitility) + testImplementation(libs.nullaway.annotations) + testImplementation(libs.bundles.osgi.test.compile) testImplementation(libs.jcache.tck) testImplementation(libs.jcache.tck) { - artifact { - classifier = "tests" - } + artifact { classifier = "tests" } } + testRuntimeOnly(libs.bundles.osgi.test.runtime) + jcacheJavadoc(libs.jcache) { - artifact { - classifier = "javadoc" - } + artifact { classifier = "javadoc" } } jcacheTckTests(libs.jcache.tck) { - artifact { - classifier = "tests" - } + artifact { classifier = "tests" } isTransitive = false } jcacheTckSources(libs.jcache.tck) { - artifact { - classifier = "test-sources" - } + artifact { classifier = "test-sources" } isTransitive = false } } 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 15680c6142..7b928d7c80 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,7 +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.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; 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 a17c4ce457..4b40f0b9a1 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,7 +16,7 @@ package com.github.benmanes.caffeine.jcache.configuration; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import javax.cache.Cache; import javax.cache.CacheException; 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 b4f533827f..9457b4954a 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 @@ -18,7 +18,7 @@ import static com.github.benmanes.caffeine.jcache.configuration.TypesafeConfigurator.configSource; import static com.google.common.truth.Truth.assertThat; import static java.util.Objects.requireNonNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.URI; import java.net.URISyntaxException; 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 c8a940e925..28533f8b60 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,7 +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 static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.io.InputStream; diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/EventDispatcherTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/EventDispatcherTest.java index aab392fbc4..69fba9e2fb 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/EventDispatcherTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/EventDispatcherTest.java @@ -25,7 +25,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.quality.Strictness.STRICT_STUBS; import java.util.ArrayList; import java.util.List; @@ -43,14 +42,12 @@ import javax.cache.event.CacheEntryEvent; import javax.cache.event.CacheEntryEventFilter; import javax.cache.event.CacheEntryExpiredListener; +import javax.cache.event.CacheEntryListener; import javax.cache.event.CacheEntryRemovedListener; import javax.cache.event.CacheEntryUpdatedListener; -import org.mockito.Mock; -import org.mockito.testng.MockitoSettings; -import org.mockito.testng.MockitoTestNGListener; +import org.mockito.Mockito; import org.testng.annotations.AfterTest; -import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.google.common.collect.Iterables; @@ -60,20 +57,9 @@ /** * @author ben.manes@gmail.com (Ben Manes) */ -@Test(singleThreaded = true) -@Listeners(MockitoTestNGListener.class) -@MockitoSettings(strictness = STRICT_STUBS) public final class EventDispatcherTest { - @Mock Cache cache; - @Mock CacheEntryCreatedListener createdListener; - @Mock CacheEntryUpdatedListener updatedListener; - @Mock CacheEntryRemovedListener removedListener; - @Mock CacheEntryExpiredListener expiredListener; - - ExecutorService executorService = Executors.newCachedThreadPool( + final ExecutorService executorService = Executors.newCachedThreadPool( new ThreadFactoryBuilder().setDaemon(true).build()); - CacheEntryEventFilter allowFilter = event -> true; - CacheEntryEventFilter rejectFilter = event -> false; @AfterTest public void afterTest() { @@ -92,6 +78,7 @@ public void register_noListener() { @Test public void register_twice() { + CacheEntryCreatedListener createdListener = Mockito.mock(); var dispatcher = new EventDispatcher(Runnable::run); var configuration = new MutableCacheEntryListenerConfiguration<>( () -> createdListener, /* filterFactory= */ null, @@ -103,6 +90,8 @@ public void register_twice() { @Test public void register_equality() { + CacheEntryCreatedListener createdListener = Mockito.mock(); + CacheEntryUpdatedListener updatedListener = Mockito.mock(); var c1 = new MutableCacheEntryListenerConfiguration<>( () -> createdListener, /* filterFactory= */ null, /* isOldValueRequired= */ false, /* isSynchronous= */ false); @@ -126,6 +115,7 @@ public void register_equality() { @Test public void deregister() { + CacheEntryCreatedListener createdListener = Mockito.mock(); var dispatcher = new EventDispatcher(Runnable::run); var configuration = new MutableCacheEntryListenerConfiguration<>( () -> createdListener, /* filterFactory= */ null, @@ -137,10 +127,12 @@ public void deregister() { @Test public void publishCreated() { + CacheEntryCreatedListener createdListener = Mockito.mock(); var dispatcher = new EventDispatcher(Runnable::run); - registerAll(dispatcher); - - dispatcher.publishCreated(cache, 1, 2); + try (Cache cache = Mockito.mock()) { + registerAll(dispatcher, List.of(createdListener)); + dispatcher.publishCreated(cache, 1, 2); + } verify(createdListener, times(4)).onCreated(any()); assertThat(dispatcher.pending.get()).hasSize(2); assertThat(dispatcher.dispatchQueues.values().stream() @@ -149,10 +141,13 @@ public void publishCreated() { @Test public void publishUpdated() { + CacheEntryUpdatedListener updatedListener = Mockito.mock(); var dispatcher = new EventDispatcher(Runnable::run); - registerAll(dispatcher); + try (Cache cache = Mockito.mock()) { + registerAll(dispatcher, List.of(updatedListener)); + dispatcher.publishUpdated(cache, 1, 2, 3); + } - dispatcher.publishUpdated(cache, 1, 2, 3); verify(updatedListener, times(4)).onUpdated(any()); assertThat(dispatcher.pending.get()).hasSize(2); assertThat(dispatcher.dispatchQueues.values().stream() @@ -161,10 +156,13 @@ public void publishUpdated() { @Test public void publishRemoved() { + CacheEntryRemovedListener removedListener = Mockito.mock(); var dispatcher = new EventDispatcher(Runnable::run); - registerAll(dispatcher); + try (Cache cache = Mockito.mock()) { + registerAll(dispatcher, List.of(removedListener)); + dispatcher.publishRemoved(cache, 1, 2); + } - dispatcher.publishRemoved(cache, 1, 2); verify(removedListener, times(4)).onRemoved(any()); assertThat(dispatcher.pending.get()).hasSize(2); assertThat(dispatcher.dispatchQueues.values().stream() @@ -173,10 +171,13 @@ public void publishRemoved() { @Test public void publishExpired() { + CacheEntryExpiredListener expiredListener = Mockito.mock(); var dispatcher = new EventDispatcher(Runnable::run); - registerAll(dispatcher); + try (Cache cache = Mockito.mock()) { + registerAll(dispatcher, List.of(expiredListener)); + dispatcher.publishExpired(cache, 1, 2); + } - dispatcher.publishExpired(cache, 1, 2); verify(expiredListener, times(4)).onExpired(any()); assertThat(dispatcher.pending.get()).hasSize(2); assertThat(dispatcher.dispatchQueues.values().stream() @@ -188,47 +189,49 @@ public void ordered() { var start = new AtomicBoolean(); var next = new AtomicBoolean(); var running = new AtomicBoolean(); - Executor executor = task -> executorService.execute(() -> { - running.set(true); - if (!start.get()) { - await().untilTrue(start); - } else if (!next.get()) { - await().untilTrue(next); - } - task.run(); - }); - var listener = new ConsumingCacheListener(); - var dispatcher = new EventDispatcher(executor); - dispatcher.register(new MutableCacheEntryListenerConfiguration<>( - () -> listener, /* filterFactory= */ null, - /* isOldValueRequired= */ false, /* isSynchronous= */ false)); - - dispatcher.publishCreated(cache, 1, 2); - dispatcher.publishUpdated(cache, 1, 2, 3); - dispatcher.publishUpdated(cache, 1, 3, 4); - dispatcher.publishRemoved(cache, 1, 5); - dispatcher.publishExpired(cache, 1, 6); - - await().untilTrue(running); - start.set(true); - - await().untilAsserted(() -> assertThat(listener.queue).hasSize(1)); - assertThat(dispatcher.dispatchQueues.values().stream() - .flatMap(queue -> queue.entrySet().stream())).isNotEmpty(); - - next.set(true); - await().untilAsserted(() -> assertThat(dispatcher.dispatchQueues.values().stream() - .flatMap(queue -> queue.entrySet().stream())).isEmpty()); - - assertThat(listener.queue).hasSize(5); - assertThat(listener.queue.stream().map(CacheEntryEvent::getKey)) - .containsExactly(1, 1, 1, 1, 1); - assertThat(listener.queue.stream().map(CacheEntryEvent::getValue)) - .containsExactly(2, 3, 4, 5, 6).inOrder(); - assertThat(listener.queue.stream().map(CacheEntryEvent::getOldValue)) - .containsExactly(null, 2, 3, 5, 6).inOrder(); - assertThat(listener.queue.stream().map(CacheEntryEvent::getEventType)) - .containsExactly(CREATED, UPDATED, UPDATED, REMOVED, EXPIRED).inOrder(); + try (Cache cache = Mockito.mock()) { + Executor executor = task -> executorService.execute(() -> { + running.set(true); + if (!start.get()) { + await().untilTrue(start); + } else if (!next.get()) { + await().untilTrue(next); + } + task.run(); + }); + var listener = new ConsumingCacheListener(); + var dispatcher = new EventDispatcher(executor); + dispatcher.register(new MutableCacheEntryListenerConfiguration<>( + () -> listener, /* filterFactory= */ null, + /* isOldValueRequired= */ false, /* isSynchronous= */ false)); + + dispatcher.publishCreated(cache, 1, 2); + dispatcher.publishUpdated(cache, 1, 2, 3); + dispatcher.publishUpdated(cache, 1, 3, 4); + dispatcher.publishRemoved(cache, 1, 5); + dispatcher.publishExpired(cache, 1, 6); + + await().untilTrue(running); + start.set(true); + + await().untilAsserted(() -> assertThat(listener.queue).hasSize(1)); + assertThat(dispatcher.dispatchQueues.values().stream() + .flatMap(queue -> queue.entrySet().stream())).isNotEmpty(); + + next.set(true); + await().untilAsserted(() -> assertThat(dispatcher.dispatchQueues.values().stream() + .flatMap(queue -> queue.entrySet().stream())).isEmpty()); + + assertThat(listener.queue).hasSize(5); + assertThat(listener.queue.stream().map(CacheEntryEvent::getKey)) + .containsExactly(1, 1, 1, 1, 1); + assertThat(listener.queue.stream().map(CacheEntryEvent::getValue)) + .containsExactly(2, 3, 4, 5, 6).inOrder(); + assertThat(listener.queue.stream().map(CacheEntryEvent::getOldValue)) + .containsExactly(null, 2, 3, 5, 6).inOrder(); + assertThat(listener.queue.stream().map(CacheEntryEvent::getEventType)) + .containsExactly(CREATED, UPDATED, UPDATED, REMOVED, EXPIRED).inOrder(); + } } @Test(invocationCount = 25) @@ -240,42 +243,44 @@ public void parallel_keys() { var run2 = new AtomicBoolean(); var done1 = new AtomicBoolean(); var done2 = new AtomicBoolean(); - - Executor executor = task -> executorService.execute(() -> { - await().untilTrue(execute); - task.run(); - }); - CacheEntryCreatedListener listener = events -> { - var event = requireNonNull(Iterables.getOnlyElement(events)); - if (event.getKey().equals(1)) { - received1.set(true); - await().untilTrue(run1); - done1.set(true); - } else if (event.getKey().equals(2)) { - received2.set(true); - await().untilTrue(run2); - done2.set(true); - } - }; - - var dispatcher = new EventDispatcher(executor); - dispatcher.register(new MutableCacheEntryListenerConfiguration<>( - () -> listener, /* filterFactory= */ null, - /* isOldValueRequired= */ false, /* isSynchronous= */ false)); - dispatcher.publishCreated(cache, 1, 1); - dispatcher.publishCreated(cache, 2, 2); - execute.set(true); - - await().untilTrue(received1); - await().untilTrue(received2); - - run1.set(true); - await().untilTrue(done1); - - run2.set(true); - await().untilTrue(done2); - await().untilAsserted(() -> assertThat(dispatcher.dispatchQueues.values().stream() - .flatMap(queue -> queue.entrySet().stream())).isEmpty()); + try (Cache cache = Mockito.mock()) { + Executor executor = task -> executorService.execute(() -> { + await().untilTrue(execute); + task.run(); + }); + CacheEntryCreatedListener listener = events -> { + var event = requireNonNull(Iterables.getOnlyElement(events)); + if (event.getKey().equals(1)) { + received1.set(true); + await().untilTrue(run1); + done1.set(true); + } else if (event.getKey().equals(2)) { + received2.set(true); + await().untilTrue(run2); + done2.set(true); + } + }; + + var dispatcher = new EventDispatcher(executor); + dispatcher.register(new MutableCacheEntryListenerConfiguration<>( + () -> listener, /* filterFactory= */ null, + /* isOldValueRequired= */ false, /* isSynchronous= */ false)); + + dispatcher.publishCreated(cache, 1, 1); + dispatcher.publishCreated(cache, 2, 2); + execute.set(true); + + await().untilTrue(received1); + await().untilTrue(received2); + + run1.set(true); + await().untilTrue(done1); + + run2.set(true); + await().untilTrue(done2); + await().untilAsserted(() -> assertThat(dispatcher.dispatchQueues.values().stream() + .flatMap(queue -> queue.entrySet().stream())).isEmpty()); + } } @Test(invocationCount = 25) @@ -283,34 +288,35 @@ public void parallel_listeners() { var execute = new AtomicBoolean(); var run = new AtomicBoolean(); var done = new AtomicBoolean(); - - Executor executor = task -> executorService.execute(() -> { - await().untilTrue(execute); - task.run(); - }); - var consumer = new ConsumingCacheListener(); - CacheEntryCreatedListener waiter = events -> { - await().untilTrue(run); - done.set(true); - }; - - var dispatcher = new EventDispatcher(executor); - dispatcher.register(new MutableCacheEntryListenerConfiguration<>( - () -> consumer, /* filterFactory= */ null, - /* isOldValueRequired= */ false, /* isSynchronous= */ false)); - dispatcher.register(new MutableCacheEntryListenerConfiguration<>( - () -> waiter, /* filterFactory= */ null, - /* isOldValueRequired= */ false, /* isSynchronous= */ false)); - - dispatcher.publishCreated(cache, 1, 2); - execute.set(true); - - await().untilAsserted(() -> assertThat(consumer.queue).hasSize(1)); - run.set(true); - - await().untilTrue(done); - await().untilAsserted(() -> assertThat(dispatcher.dispatchQueues.values().stream() - .flatMap(queue -> queue.entrySet().stream())).isEmpty()); + try (Cache cache = Mockito.mock()) { + Executor executor = task -> executorService.execute(() -> { + await().untilTrue(execute); + task.run(); + }); + var consumer = new ConsumingCacheListener(); + CacheEntryCreatedListener waiter = events -> { + await().untilTrue(run); + done.set(true); + }; + + var dispatcher = new EventDispatcher(executor); + dispatcher.register(new MutableCacheEntryListenerConfiguration<>( + () -> consumer, /* filterFactory= */ null, + /* isOldValueRequired= */ false, /* isSynchronous= */ false)); + dispatcher.register(new MutableCacheEntryListenerConfiguration<>( + () -> waiter, /* filterFactory= */ null, + /* isOldValueRequired= */ false, /* isSynchronous= */ false)); + + dispatcher.publishCreated(cache, 1, 2); + execute.set(true); + + await().untilAsserted(() -> assertThat(consumer.queue).hasSize(1)); + run.set(true); + + await().untilTrue(done); + await().untilAsserted(() -> assertThat(dispatcher.dispatchQueues.values().stream() + .flatMap(queue -> queue.entrySet().stream())).isEmpty()); + } } @Test @@ -351,9 +357,10 @@ public void awaitSynchronous_nested() { var queue = new CompletableFuture(); dispatchQueue.put(key, queue); - primary.publishCreated(cache, key, -key); - queue.complete(null); - + try (Cache cache = Mockito.mock()) { + primary.publishCreated(cache, key, -key); + queue.complete(null); + } assertThat(pendingFutures).isEmpty(); } @@ -367,14 +374,17 @@ public void ignoreSynchronous() { } /** - * Registers (4 listeners) * (2 synchronous modes) * (3 filter modes) = 24 configurations. For + * Registers (listeners) * (2 synchronous modes) * (3 filter modes) configurations. For * simplicity, an event is published and ignored if the listener is of the wrong type. For a * single event, it should be consumed by (2 filter) * (2 synchronous) = 4 listeners where only * 2 are synchronous. */ - private void registerAll(EventDispatcher dispatcher) { + private static void registerAll(EventDispatcher dispatcher, + List> listeners) { + CacheEntryEventFilter rejectFilter = event -> false; + CacheEntryEventFilter allowFilter = event -> true; + var isOldValueRequired = false; - var listeners = List.of(createdListener, updatedListener, removedListener, expiredListener); for (var listener : listeners) { for (boolean synchronous : List.of(true, false)) { dispatcher.register(new MutableCacheEntryListenerConfiguration<>( diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/EventTypeAwareListenerTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/EventTypeAwareListenerTest.java index bf200bab5d..bb1d4256d7 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/EventTypeAwareListenerTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/EventTypeAwareListenerTest.java @@ -19,7 +19,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import static org.mockito.quality.Strictness.STRICT_STUBS; import java.io.IOException; @@ -31,29 +30,21 @@ import javax.cache.event.CacheEntryUpdatedListener; import javax.cache.event.EventType; -import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.testng.MockitoSettings; -import org.mockito.testng.MockitoTestNGListener; import org.testng.annotations.DataProvider; -import org.testng.annotations.Listeners; import org.testng.annotations.Test; /** * @author ben.manes@gmail.com (Ben Manes) */ -@Test(singleThreaded = true) -@SuppressWarnings("unchecked") -@Listeners(MockitoTestNGListener.class) -@MockitoSettings(strictness = STRICT_STUBS) public final class EventTypeAwareListenerTest { - @Mock Cache cache; @Test public void closed() throws IOException { - when(cache.isClosed()).thenReturn(true); CacheEntryListener listener = Mockito.mock(); - try (var forwarder = new EventTypeAwareListener<>(listener)) { + try (var forwarder = new EventTypeAwareListener<>(listener); + Cache cache = Mockito.mock()) { + when(cache.isClosed()).thenReturn(true); forwarder.dispatch(new JCacheEntryEvent<>(cache, EventType.CREATED, /* key= */ 1, /* hasOldValue= */ false, /* oldValue= */ null, /* newValue= */ 2)); verifyNoInteractions(listener); @@ -62,8 +53,9 @@ public void closed() throws IOException { @Test(dataProvider = "exceptions") public void created_failure(Throwable error) throws IOException { - var listener = Mockito.mock(CacheEntryCreatedListener.class, answer -> { throw error; }); - try (var forwarder = new EventTypeAwareListener<>(listener)) { + CacheEntryCreatedListener listener = Mockito.mock(answer -> { throw error; }); + try (var forwarder = new EventTypeAwareListener<>(listener); + Cache cache = Mockito.mock()) { forwarder.dispatch(new JCacheEntryEvent<>(cache, EventType.CREATED, /* key= */ 1, /* hasOldValue= */ false, /* oldValue= */ null, /* newValue= */ 2)); } @@ -72,8 +64,9 @@ public void created_failure(Throwable error) throws IOException { @Test(dataProvider = "exceptions") public void updated_failure(Throwable error) throws IOException { - var listener = Mockito.mock(CacheEntryUpdatedListener.class, answer -> { throw error; }); - try (var forwarder = new EventTypeAwareListener<>(listener)) { + CacheEntryUpdatedListener listener = Mockito.mock(answer -> { throw error; }); + try (var forwarder = new EventTypeAwareListener<>(listener); + Cache cache = Mockito.mock()) { forwarder.dispatch(new JCacheEntryEvent<>(cache, EventType.UPDATED, /* key= */ 1, /* hasOldValue= */ true, /* oldValue= */ 2, /* newValue= */ 3)); } @@ -82,8 +75,9 @@ public void updated_failure(Throwable error) throws IOException { @Test(dataProvider = "exceptions") public void removed_failure(Throwable error) throws IOException { - var listener = Mockito.mock(CacheEntryRemovedListener.class, answer -> { throw error; }); - try (var forwarder = new EventTypeAwareListener<>(listener)) { + CacheEntryRemovedListener listener = Mockito.mock(answer -> { throw error; }); + try (var forwarder = new EventTypeAwareListener<>(listener); + Cache cache = Mockito.mock()) { forwarder.dispatch(new JCacheEntryEvent<>(cache, EventType.REMOVED, /* key= */ 1, /* hasOldValue= */ true, /* oldValue= */ 2, /* newValue= */ null)); } @@ -92,8 +86,9 @@ public void removed_failure(Throwable error) throws IOException { @Test(dataProvider = "exceptions") public void expired_failure(Throwable error) throws IOException { - var listener = Mockito.mock(CacheEntryExpiredListener.class, answer -> { throw error; }); - try (var forwarder = new EventTypeAwareListener<>(listener)) { + CacheEntryExpiredListener listener = Mockito.mock(answer -> { throw error; }); + try (var forwarder = new EventTypeAwareListener<>(listener); + Cache cache = Mockito.mock()) { forwarder.dispatch(new JCacheEntryEvent<>(cache, EventType.EXPIRED, /* key= */ 1, /* hasOldValue= */ true, /* oldValue= */ 2, /* newValue= */ null)); } 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 2063ee9697..66ddf4d9ca 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,8 +16,7 @@ package com.github.benmanes.caffeine.jcache.event; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; -import static org.mockito.quality.Strictness.STRICT_STUBS; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Iterator; import java.util.Map; @@ -26,11 +25,7 @@ import javax.cache.event.CacheEntryEvent; import javax.cache.event.EventType; -import org.mockito.Mock; -import org.mockito.testng.MockitoSettings; -import org.mockito.testng.MockitoTestNGListener; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Listeners; +import org.mockito.Mockito; import org.testng.annotations.Test; import com.google.common.collect.testing.IteratorFeature; @@ -39,57 +34,67 @@ /** * @author ben.manes@gmail.com (Ben Manes) */ -@Test(singleThreaded = true) -@Listeners(MockitoTestNGListener.class) -@MockitoSettings(strictness = STRICT_STUBS) public final class JCacheEntryEventTest { - @Mock Cache cache; - - JCacheEntryEvent event; - - @BeforeMethod - public void before() { - event = new JCacheEntryEvent<>(cache, EventType.CREATED, - 1, /* hasOldValue= */ true, 2, 3); - } @Test public void unwrap_fail() { - assertThrows(IllegalArgumentException.class, () -> event.unwrap(Map.Entry.class)); + try (Cache cache = Mockito.mock()) { + var event = new JCacheEntryEvent<>(cache, EventType.CREATED, + 1, /* hasOldValue= */ true, 2, 3); + assertThrows(IllegalArgumentException.class, () -> event.unwrap(Map.Entry.class)); + } } @Test public void unwrap() { - assertThat(event.unwrap(Cache.Entry.class)).isSameInstanceAs(event); + try (Cache cache = Mockito.mock()) { + var event = new JCacheEntryEvent<>(cache, EventType.CREATED, + 1, /* hasOldValue= */ true, 2, 3); + assertThat(event.unwrap(Cache.Entry.class)).isSameInstanceAs(event); + } } @Test public void isOldValueAvailable_false() { - var entry = new JCacheEntryEvent<>(cache, EventType.CREATED, - 1, /* hasOldValue= */ false, null, 3); - assertThat(entry.isOldValueAvailable()).isFalse(); + try (Cache cache = Mockito.mock()) { + var entry = new JCacheEntryEvent<>(cache, EventType.CREATED, + 1, /* hasOldValue= */ false, null, 3); + assertThat(entry.isOldValueAvailable()).isFalse(); + } } @Test public void isOldValueAvailable() { - assertThat(event.isOldValueAvailable()).isTrue(); + try (Cache cache = Mockito.mock()) { + var event = new JCacheEntryEvent<>(cache, EventType.CREATED, + 1, /* hasOldValue= */ true, 2, 3); + assertThat(event.isOldValueAvailable()).isTrue(); + } } @Test public void getOldValue() { - assertThat(event.getOldValue()).isEqualTo(2); + try (Cache cache = Mockito.mock()) { + var event = new JCacheEntryEvent<>(cache, EventType.CREATED, + 1, /* hasOldValue= */ true, 2, 3); + assertThat(event.getOldValue()).isEqualTo(2); + } } @Test public void iterable() { - var tester = new IteratorTester>( - 6, IteratorFeature.UNMODIFIABLE, event, IteratorTester.KnownOrder.KNOWN_ORDER) { - @Override - protected Iterator> newTargetIterator() { - return event.iterator(); - } - }; - tester.test(); - tester.testForEachRemaining(); + try (Cache cache = Mockito.mock()) { + var event = new JCacheEntryEvent<>(cache, EventType.CREATED, + 1, /* hasOldValue= */ true, 2, 3); + var tester = new IteratorTester>( + 6, IteratorFeature.UNMODIFIABLE, event, IteratorTester.KnownOrder.KNOWN_ORDER) { + @Override + protected Iterator> newTargetIterator() { + return event.iterator(); + } + }; + tester.test(); + tester.testForEachRemaining(); + } } } diff --git a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEvictionListenerTest.java b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEvictionListenerTest.java index 44db10fc59..5e75faf172 100644 --- a/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEvictionListenerTest.java +++ b/jcache/src/test/java/com/github/benmanes/caffeine/jcache/event/JCacheEvictionListenerTest.java @@ -19,7 +19,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.quality.Strictness.STRICT_STUBS; import java.util.Arrays; import java.util.Iterator; @@ -29,12 +28,8 @@ import javax.cache.event.CacheEntryExpiredListener; import javax.cache.event.CacheEntryRemovedListener; -import org.mockito.Mock; -import org.mockito.testng.MockitoSettings; -import org.mockito.testng.MockitoTestNGListener; -import org.testng.annotations.BeforeMethod; +import org.mockito.Mockito; import org.testng.annotations.DataProvider; -import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.github.benmanes.caffeine.cache.RemovalCause; @@ -44,41 +39,23 @@ /** * @author ben.manes@gmail.com (Ben Manes) */ -@Test(singleThreaded = true) -@Listeners(MockitoTestNGListener.class) -@MockitoSettings(strictness = STRICT_STUBS) public final class JCacheEvictionListenerTest { - JCacheEvictionListener listener; - JCacheStatisticsMXBean statistics; - @Mock EvictionListener entryListener; - @Mock Cache cache; - - @BeforeMethod - public void before() { - statistics = new JCacheStatisticsMXBean(); + @Test(dataProvider = "notifications") + public void publishIfEvicted(Integer key, Expirable value, RemovalCause cause) { + var statistics = new JCacheStatisticsMXBean(); + EvictionListener entryListener = Mockito.mock(); var dispatcher = new EventDispatcher(Runnable::run); - listener = new JCacheEvictionListener<>(dispatcher, statistics); - listener.setCache(cache); - statistics.enable(true); - + var listener = new JCacheEvictionListener<>(dispatcher, statistics); dispatcher.register(new MutableCacheEntryListenerConfiguration<>( /* listenerFactory= */ () -> entryListener, /* filterFactory= */ null, /* isOldValueRequired= */ false, /* isSynchronous= */ false)); - } - - @DataProvider - public Iterator notifications() { - return Arrays.stream(RemovalCause.values()) - .filter(RemovalCause::wasEvicted) - .map(cause -> new Object[] { 1, new Expirable<>(2, 3), cause }) - .iterator(); - } + try (Cache cache = Mockito.mock()) { + listener.setCache(cache); + } + statistics.enable(true); - @Test(dataProvider = "notifications") - public void publishIfEvicted(Integer key, Expirable value, RemovalCause cause) { listener.onRemoval(key, value, cause); - if (cause.wasEvicted()) { if (cause == RemovalCause.EXPIRED) { verify(entryListener).onExpired(any()); @@ -92,6 +69,14 @@ public void publishIfEvicted(Integer key, Expirable value, RemovalCause } } + @DataProvider(name = "notifications") + public Iterator providesNotifications() { + return Arrays.stream(RemovalCause.values()) + .filter(RemovalCause::wasEvicted) + .map(cause -> new Object[] { 1, new Expirable<>(2, 3), cause }) + .iterator(); + } + interface EvictionListener extends CacheEntryRemovedListener, CacheEntryExpiredListener {} } 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 dfb5151a21..062e01d98b 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,7 +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.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyIterable; import static org.mockito.Mockito.when; 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 d4e971fdce..98c1ce7a86 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,7 +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.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doThrow; 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 9821562058..d47012287c 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,7 +15,7 @@ */ package com.github.benmanes.caffeine.jcache.management; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; 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 2acc029ab1..6ea5fd440d 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,7 +16,7 @@ package com.github.benmanes.caffeine.jcache.processor; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Map; import java.util.Optional;