From 0a7c50c2d9fcca6a8864ac8fb888eab758e584fb Mon Sep 17 00:00:00 2001 From: Jochen Schalanda Date: Wed, 8 Feb 2023 01:09:17 +0100 Subject: [PATCH] Migrate to JUnit Jupiter using OpenRewrite --- metrics-caffeine3/pom.xml | 18 ++- .../caffeine3/MetricsStatsCounterTest.java | 24 +-- metrics-collectd/pom.xml | 18 ++- .../CollectdReporterSecurityTest.java | 20 +-- .../collectd/CollectdReporterTest.java | 47 +++--- .../metrics5/collectd/PacketWriterTest.java | 8 +- .../metrics5/collectd/Receiver.java | 23 +-- .../metrics5/collectd/SanitizeTest.java | 14 +- metrics-core/pom.xml | 24 ++- .../dropwizard/metrics5/CachedGaugeTest.java | 16 +- .../ChunkedAssociativeLongArrayTest.java | 6 +- .../io/dropwizard/metrics5/ClockTest.java | 8 +- .../metrics5/ConsoleReporterTest.java | 26 +-- .../io/dropwizard/metrics5/CounterTest.java | 18 +-- .../dropwizard/metrics5/CsvReporterTest.java | 40 +++-- .../metrics5/DefaultSettableGaugeTest.java | 10 +- .../metrics5/DerivativeGaugeTest.java | 6 +- .../java/io/dropwizard/metrics5/EWMATest.java | 10 +- .../ExponentiallyDecayingReservoirTest.java | 99 +++++++----- .../FixedNameCsvFileProviderTest.java | 31 ++-- .../io/dropwizard/metrics5/HistogramTest.java | 10 +- .../InstrumentedExecutorServiceTest.java | 24 +-- ...trumentedScheduledExecutorServiceTest.java | 22 +-- .../InstrumentedThreadFactoryTest.java | 6 +- .../metrics5/MeterApproximationTest.java | 30 ++-- .../io/dropwizard/metrics5/MeterTest.java | 14 +- .../dropwizard/metrics5/MetricFilterTest.java | 12 +- .../dropwizard/metrics5/MetricNameTest.java | 45 +++--- .../metrics5/MetricRegistryListenerTest.java | 16 +- .../metrics5/MetricRegistryTest.java | 116 ++++++------- .../metrics5/NoopMetricRegistryTest.java | 90 +++++------ .../dropwizard/metrics5/RatioGaugeTest.java | 14 +- .../metrics5/ScheduledReporterTest.java | 91 ++++++----- .../metrics5/SharedMetricRegistriesTest.java | 48 +++--- .../metrics5/SimpleSettableGaugeTest.java | 8 +- .../metrics5/Slf4jReporterTest.java | 36 ++--- .../SlidingTimeWindowArrayReservoirTest.java | 12 +- .../SlidingTimeWindowMovingAveragesTest.java | 28 ++-- .../SlidingTimeWindowReservoirTest.java | 10 +- .../metrics5/SlidingWindowReservoirTest.java | 8 +- .../io/dropwizard/metrics5/TimerTest.java | 26 +-- .../metrics5/UniformReservoirTest.java | 6 +- .../metrics5/UniformSnapshotTest.java | 73 +++++---- .../metrics5/WeightedSnapshotTest.java | 77 +++++---- metrics-ehcache/pom.xml | 12 +- ...InstrumentedCacheDecoratorFactoryTest.java | 20 ++- .../ehcache/InstrumentedEhcacheTest.java | 12 +- metrics-graphite/pom.xml | 18 ++- .../graphite/GraphiteRabbitMQTest.java | 24 +-- .../graphite/GraphiteReporterTest.java | 96 +++++------ .../graphite/GraphiteSanitizeTest.java | 6 +- .../metrics5/graphite/GraphiteTest.java | 36 ++--- .../metrics5/graphite/GraphiteUDPTest.java | 10 +- .../graphite/PickledGraphiteTest.java | 26 +-- metrics-healthchecks/pom.xml | 18 ++- .../health/AsyncHealthCheckDecoratorTest.java | 77 +++++---- .../health/HealthCheckFilterTest.java | 6 +- .../health/HealthCheckRegistryTest.java | 57 +++---- .../metrics5/health/HealthCheckTest.java | 32 ++-- .../SharedHealthCheckRegistriesTest.java | 60 +++---- .../jvm/ThreadDeadlockHealthCheckTest.java | 10 +- metrics-httpasyncclient/pom.xml | 24 ++- .../httpasyncclient/HttpClientTestBase.java | 6 +- .../InstrumentedHttpClientsTest.java | 20 +-- .../InstrumentedHttpClientsTimerTest.java | 30 ++-- metrics-httpclient/pom.xml | 18 ++- .../HttpClientMetricNameStrategiesTest.java | 38 ++--- ...mentedHttpClientConnectionManagerTest.java | 14 +- .../InstrumentedHttpClientsTest.java | 16 +- metrics-httpclient5/pom.xml | 24 ++- .../HttpClientMetricNameStrategiesTest.java | 30 ++-- ...entedAsyncClientConnectionManagerTest.java | 14 +- .../InstrumentedHttpAsyncClientsTest.java | 94 ++++++----- ...mentedHttpClientConnectionManagerTest.java | 14 +- .../InstrumentedHttpClientsTest.java | 16 +- metrics-influxdb/pom.xml | 18 ++- .../InfluxDbLineBuilderAssumptionsTest.java | 6 +- .../influxdb/InfluxDbReporterTest.java | 43 ++--- .../metrics5/influxdb/InfluxDbUdpTest.java | 18 +-- metrics-jakarta-servlet/pom.xml | 12 +- ...InstrumentedFilterContextListenerTest.java | 6 +- metrics-jakarta-servlets/pom.xml | 18 ++- .../servlets/AbstractServletTest.java | 8 +- .../servlets/AdminServletExclusionTest.java | 12 +- .../metrics5/servlets/AdminServletTest.java | 12 +- .../servlets/AdminServletUriTest.java | 12 +- .../servlets/CpuProfileServletTest.java | 16 +- .../servlets/HealthCheckServletTest.java | 61 +++---- .../MetricsServletContextListenerTest.java | 14 +- .../metrics5/servlets/MetricsServletTest.java | 43 ++--- .../metrics5/servlets/PingServletTest.java | 18 +-- .../servlets/ThreadDumpServletTest.java | 18 +-- metrics-jcache/pom.xml | 18 ++- .../src/test/java/JCacheGaugeSetTest.java | 18 +-- metrics-jdbi3/pom.xml | 24 ++- .../strategies/AbstractStrategyTest.java | 19 ++- .../strategies/BasicSqlNameStrategyTest.java | 14 +- .../strategies/InstrumentedSqlLoggerTest.java | 8 +- .../strategies/NaiveNameStrategyTest.java | 8 +- .../strategies/SmartNameStrategyTest.java | 29 ++-- .../TimedAnnotationNameStrategyTest.java | 20 +-- metrics-jersey2/pom.xml | 30 +++- .../CustomReservoirImplementationTest.java | 16 +- .../SingletonFilterMetricsJerseyTest.java | 84 +++++----- ...icsExceptionMeteredPerClassJerseyTest.java | 40 ++--- .../jersey2/SingletonMetricsJerseyTest.java | 80 ++++----- ...letonMetricsMeteredPerClassJerseyTest.java | 20 +-- ...ricsResponseMeteredPerClassJerseyTest.java | 86 +++++----- ...ngletonMetricsTimedPerClassJerseyTest.java | 20 +-- metrics-jersey3/pom.xml | 14 +- .../CustomReservoirImplementationTest.java | 16 +- .../SingletonFilterMetricsJerseyTest.java | 84 +++++----- ...icsExceptionMeteredPerClassJerseyTest.java | 40 ++--- .../jersey3/SingletonMetricsJerseyTest.java | 80 ++++----- ...letonMetricsMeteredPerClassJerseyTest.java | 20 +-- ...ricsResponseMeteredPerClassJerseyTest.java | 86 +++++----- ...ngletonMetricsTimedPerClassJerseyTest.java | 20 +-- metrics-jersey31/pom.xml | 14 +- .../CustomReservoirImplementationTest.java | 16 +- .../SingletonFilterMetricsJerseyTest.java | 84 +++++----- ...icsExceptionMeteredPerClassJerseyTest.java | 40 ++--- .../jersey31/SingletonMetricsJerseyTest.java | 80 ++++----- ...letonMetricsMeteredPerClassJerseyTest.java | 20 +-- ...ricsResponseMeteredPerClassJerseyTest.java | 86 +++++----- ...ngletonMetricsTimedPerClassJerseyTest.java | 20 +-- metrics-jetty10/pom.xml | 18 ++- .../InstrumentedConnectionFactoryTest.java | 26 +-- .../jetty10/InstrumentedHandlerTest.java | 28 ++-- .../InstrumentedHttpChannelListenerTest.java | 22 +-- .../InstrumentedQueuedThreadPoolTest.java | 14 +- metrics-jetty11/pom.xml | 18 ++- .../InstrumentedConnectionFactoryTest.java | 26 +-- .../jetty11/InstrumentedHandlerTest.java | 28 ++-- .../InstrumentedHttpChannelListenerTest.java | 22 +-- .../InstrumentedQueuedThreadPoolTest.java | 14 +- metrics-jmx/pom.xml | 18 ++- .../jmx/DefaultObjectNameFactoryTest.java | 12 +- .../metrics5/jmx/JmxReporterTest.java | 34 ++-- metrics-json/pom.xml | 18 ++- .../metrics5/json/HealthCheckModuleTest.java | 152 +++++++++--------- .../metrics5/json/MetricsModuleTest.java | 18 +-- metrics-jvm/pom.xml | 18 ++- .../metrics5/jvm/BufferPoolMetricSetTest.java | 26 +-- .../jvm/ClassLoadingGaugeSetTest.java | 14 +- .../metrics5/jvm/CpuTimeClockTest.java | 6 +- ...rRatioGaugeSunManagementNotExistsTest.java | 117 -------------- .../jvm/FileDescriptorRatioGaugeTest.java | 18 +-- .../jvm/GarbageCollectorMetricSetTest.java | 18 +-- .../metrics5/jvm/JmxAttributeGaugeTest.java | 26 +-- .../jvm/JvmAttributeGaugeSetTest.java | 20 +-- .../metrics5/jvm/MemoryUsageGaugeSetTest.java | 56 +++---- .../jvm/ThreadDeadlockDetectorTest.java | 40 ++--- .../metrics5/jvm/ThreadDumpTest.java | 22 +-- .../jvm/ThreadStatesGaugeSetTest.java | 60 +++---- metrics-legacy-adapter-healthchecks/pom.xml | 6 - metrics-legacy-adapter/pom.xml | 18 ++- .../com/codahale/metrics/CachedGaugeTest.java | 8 +- .../java/com/codahale/metrics/ClockTest.java | 10 +- .../codahale/metrics/ConsoleReporterTest.java | 12 +- .../com/codahale/metrics/CounterTest.java | 12 +- .../codahale/metrics/DerivativeGaugeTest.java | 6 +- .../ExponentiallyDecayingReservoirTest.java | 10 +- .../metrics/FixedNameCsvFileProviderTest.java | 18 +-- .../java/com/codahale/metrics/GaugeTest.java | 6 +- .../com/codahale/metrics/HistogramTest.java | 6 +- .../InstrumentedExecutorServiceTest.java | 7 +- ...trumentedScheduledExecutorServiceTest.java | 12 +- .../InstrumentedThreadFactoryTest.java | 6 +- .../java/com/codahale/metrics/MeterTest.java | 10 +- .../codahale/metrics/MetricRegistryTest.java | 68 ++++---- .../com/codahale/metrics/RatioGaugeTest.java | 8 +- .../metrics/ScheduledReporterTest.java | 26 +-- .../metrics/SharedMetricRegistriesTest.java | 20 +-- .../codahale/metrics/Slf4jReporterTest.java | 18 +-- .../SlidingTimeWindowArrayReservoirTest.java | 8 +- .../SlidingTimeWindowReservoirTest.java | 8 +- .../metrics/SlidingWindowReservoirTest.java | 8 +- .../com/codahale/metrics/SnapshotTest.java | 6 +- .../java/com/codahale/metrics/TimerTest.java | 20 +-- .../metrics/UniformReservoirTest.java | 8 +- metrics-log4j2/pom.xml | 18 ++- .../InstrumentedAppenderConfigTest.java | 20 +-- .../log4j2/InstrumentedAppenderTest.java | 28 ++-- metrics-logback13/pom.xml | 18 ++- .../logback13/InstrumentedAppenderTest.java | 30 ++-- metrics-logback14/pom.xml | 18 ++- .../logback14/InstrumentedAppenderTest.java | 30 ++-- metrics-servlet/pom.xml | 12 +- ...InstrumentedFilterContextListenerTest.java | 6 +- metrics-servlets/pom.xml | 18 ++- .../servlets/AbstractServletTest.java | 8 +- .../metrics5/servlets/AdminServletTest.java | 12 +- .../servlets/AdminServletUriTest.java | 12 +- .../servlets/CpuProfileServletTest.java | 16 +- .../servlets/HealthCheckServletTest.java | 57 +++---- .../MetricsServletContextListenerTest.java | 14 +- .../metrics5/servlets/MetricsServletTest.java | 43 ++--- .../metrics5/servlets/PingServletTest.java | 18 +-- .../servlets/ThreadDumpServletTest.java | 18 +-- pom.xml | 19 ++- 200 files changed, 2810 insertions(+), 2614 deletions(-) delete mode 100644 metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java diff --git a/metrics-caffeine3/pom.xml b/metrics-caffeine3/pom.xml index f39680b8ee..d7c9356f82 100644 --- a/metrics-caffeine3/pom.xml +++ b/metrics-caffeine3/pom.xml @@ -57,17 +57,23 @@ org.checkerframework checker-qual - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + diff --git a/metrics-caffeine3/src/test/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounterTest.java b/metrics-caffeine3/src/test/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounterTest.java index 5b2b6153ca..3a4808ab47 100644 --- a/metrics-caffeine3/src/test/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounterTest.java +++ b/metrics-caffeine3/src/test/java/io/dropwizard/metrics5/caffeine3/MetricsStatsCounterTest.java @@ -19,11 +19,11 @@ import com.github.benmanes.caffeine.cache.LoadingCache; import com.github.benmanes.caffeine.cache.RemovalCause; import io.dropwizard.metrics5.MetricRegistry; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * An example of exporting stats to Dropwizard Metrics (http://metrics.dropwizard.io). @@ -31,21 +31,21 @@ * @author ben.manes@gmail.com (Ben Manes) * @author John Karp */ -public final class MetricsStatsCounterTest { +final class MetricsStatsCounterTest { private static final String PREFIX = "foo"; private MetricsStatsCounter stats; private MetricRegistry registry; - @Before - public void setUp() { + @BeforeEach + void setUp() { registry = new MetricRegistry(); stats = new MetricsStatsCounter(registry, PREFIX); } @Test - public void basicUsage() { + void basicUsage() { LoadingCache cache = Caffeine.newBuilder() .recordStats(() -> new MetricsStatsCounter(registry, PREFIX)) .build(key -> key); @@ -60,31 +60,31 @@ public void basicUsage() { } @Test - public void hit() { + void hit() { stats.recordHits(2); assertThat(registry.counter(PREFIX + ".hits").getCount()).isEqualTo(2); } @Test - public void miss() { + void miss() { stats.recordMisses(2); assertThat(registry.counter(PREFIX + ".misses").getCount()).isEqualTo(2); } @Test - public void loadSuccess() { + void loadSuccess() { stats.recordLoadSuccess(256); assertThat(registry.timer(PREFIX + ".loads-success").getCount()).isEqualTo(1); } @Test - public void loadFailure() { + void loadFailure() { stats.recordLoadFailure(256); assertThat(registry.timer(PREFIX + ".loads-failure").getCount()).isEqualTo(1); } @Test - public void evictionWithCause() { + void evictionWithCause() { // With JUnit 5, this would be better done with @ParameterizedTest + @EnumSource for (RemovalCause cause : RemovalCause.values()) { stats.recordEviction(3, cause); diff --git a/metrics-collectd/pom.xml b/metrics-collectd/pom.xml index fa18114ea2..85bd6717ee 100644 --- a/metrics-collectd/pom.xml +++ b/metrics-collectd/pom.xml @@ -39,18 +39,24 @@ slf4j-api ${slf4j.version} - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java index 74fbbb92cb..e8b61bc02c 100644 --- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java +++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterSecurityTest.java @@ -1,28 +1,28 @@ package io.dropwizard.metrics5.collectd; import io.dropwizard.metrics5.MetricRegistry; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -public class CollectdReporterSecurityTest { +class CollectdReporterSecurityTest { private final MetricRegistry registry = new MetricRegistry(); @Test - public void testUnableSetSecurityLevelToSignWithoutUsername() { - assertThatIllegalArgumentException().isThrownBy(()-> + void testUnableSetSecurityLevelToSignWithoutUsername() { + assertThatIllegalArgumentException().isThrownBy(() -> CollectdReporter.forRegistry(registry) - .withHostName("eddie") - .withSecurityLevel(SecurityLevel.SIGN) - .withPassword("t1_g3r") - .build(new Sender("localhost", 25826))) + .withHostName("eddie") + .withSecurityLevel(SecurityLevel.SIGN) + .withPassword("t1_g3r") + .build(new Sender("localhost", 25826))) .withMessage("username is required for securityLevel: SIGN"); } @Test - public void testUnableSetSecurityLevelToSignWithoutPassword() { - assertThatIllegalArgumentException().isThrownBy(()-> + void testUnableSetSecurityLevelToSignWithoutPassword() { + assertThatIllegalArgumentException().isThrownBy(() -> CollectdReporter.forRegistry(registry) .withHostName("eddie") .withSecurityLevel(SecurityLevel.SIGN) diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java index 022497030a..07bd2bbe06 100644 --- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java +++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/CollectdReporterTest.java @@ -9,9 +9,9 @@ import io.dropwizard.metrics5.Snapshot; import io.dropwizard.metrics5.Timer; import org.collectd.api.ValueList; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.util.Collections; import java.util.EnumSet; @@ -27,47 +27,46 @@ import static org.mockito.Mockito.when; public class CollectdReporterTest { - - @ClassRule + @RegisterExtension public static Receiver receiver = new Receiver(25826); private final MetricRegistry registry = new MetricRegistry(); private CollectdReporter reporter; - @Before - public void setUp() { + @BeforeEach + void setUp() { reporter = CollectdReporter.forRegistry(registry) .withHostName("eddie") .build(new Sender("localhost", 25826)); } @Test - public void reportsByteGauges() throws Exception { + void reportsByteGauges() throws Exception { reportsGauges((byte) 128); } @Test - public void reportsShortGauges() throws Exception { + void reportsShortGauges() throws Exception { reportsGauges((short) 2048); } @Test - public void reportsIntegerGauges() throws Exception { + void reportsIntegerGauges() throws Exception { reportsGauges(42); } @Test - public void reportsLongGauges() throws Exception { + void reportsLongGauges() throws Exception { reportsGauges(Long.MAX_VALUE); } @Test - public void reportsFloatGauges() throws Exception { + void reportsFloatGauges() throws Exception { reportsGauges(0.25); } @Test - public void reportsDoubleGauges() throws Exception { + void reportsDoubleGauges() throws Exception { reportsGauges(0.125d); } @@ -83,7 +82,7 @@ private void reportsGauges(T value) throws Exception { } @Test - public void reportsBooleanGauges() throws Exception { + void reportsBooleanGauges() throws Exception { reporter.report( map(MetricName.build("gauge"), () -> true), map(), @@ -104,7 +103,7 @@ public void reportsBooleanGauges() throws Exception { } @Test - public void doesNotReportStringGauges() throws Exception { + void doesNotReportStringGauges() throws Exception { reporter.report( map(MetricName.build("unsupported"), () -> "value"), map(), @@ -116,7 +115,7 @@ public void doesNotReportStringGauges() throws Exception { } @Test - public void reportsCounters() throws Exception { + void reportsCounters() throws Exception { Counter counter = mock(Counter.class); when(counter.getCount()).thenReturn(42L); @@ -131,7 +130,7 @@ public void reportsCounters() throws Exception { } @Test - public void reportsMeters() throws Exception { + void reportsMeters() throws Exception { Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getOneMinuteRate()).thenReturn(2.0); @@ -154,7 +153,7 @@ public void reportsMeters() throws Exception { } @Test - public void reportsHistograms() throws Exception { + void reportsHistograms() throws Exception { Histogram histogram = mock(Histogram.class); Snapshot snapshot = mock(Snapshot.class); when(histogram.getCount()).thenReturn(1L); @@ -183,7 +182,7 @@ public void reportsHistograms() throws Exception { } @Test - public void reportsTimers() throws Exception { + void reportsTimers() throws Exception { Timer timer = mock(Timer.class); Snapshot snapshot = mock(Snapshot.class); when(timer.getSnapshot()).thenReturn(snapshot); @@ -229,7 +228,7 @@ public void reportsTimers() throws Exception { } @Test - public void doesNotReportDisabledMetricAttributes() throws Exception { + void doesNotReportDisabledMetricAttributes() throws Exception { final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getOneMinuteRate()).thenReturn(2.0); @@ -259,7 +258,7 @@ public void doesNotReportDisabledMetricAttributes() throws Exception { } @Test - public void sanitizesMetricName() throws Exception { + void sanitizesMetricName() throws Exception { Counter counter = registry.counter("dash-illegal.slash/illegal"); counter.inc(); @@ -270,7 +269,7 @@ public void sanitizesMetricName() throws Exception { } @Test - public void testUnableSetSecurityLevelToSignWithoutUsername() { + void testUnableSetSecurityLevelToSignWithoutUsername() { assertThatIllegalArgumentException().isThrownBy(() -> CollectdReporter.forRegistry(registry) .withHostName("eddie") @@ -281,7 +280,7 @@ public void testUnableSetSecurityLevelToSignWithoutUsername() { } @Test - public void testUnableSetSecurityLevelToSignWithoutPassword() { + void testUnableSetSecurityLevelToSignWithoutPassword() { assertThatIllegalArgumentException().isThrownBy(() -> CollectdReporter.forRegistry(registry) .withHostName("eddie") @@ -301,7 +300,7 @@ private SortedMap map(MetricName name, T metric) { } @Test - public void sanitizesMetricNameWithCustomMaxLength() throws Exception { + void sanitizesMetricNameWithCustomMaxLength() throws Exception { CollectdReporter customReporter = CollectdReporter.forRegistry(registry) .withHostName("eddie") .withMaxLength(20) diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java index e6a85d7cb9..5cd83a335e 100644 --- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java +++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/PacketWriterTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5.collectd; import io.dropwizard.metrics5.collectd.SecurityLevel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.crypto.Cipher; import javax.crypto.Mac; @@ -19,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.Offset.offset; -public class PacketWriterTest { +class PacketWriterTest { private MetaData metaData = new MetaData.Builder("nw-1.alpine.example.com", 1520961345L, 100) .type("gauge") @@ -29,7 +29,7 @@ public class PacketWriterTest { private String password = "t1_g$r"; @Test - public void testSignRequest() throws Exception { + void testSignRequest() throws Exception { AtomicBoolean packetVerified = new AtomicBoolean(); Sender sender = new Sender("localhost", 4009) { @Override @@ -75,7 +75,7 @@ private byte[] sign(byte[] input, String password) { } @Test - public void testEncryptRequest() throws Exception { + void testEncryptRequest() throws Exception { AtomicBoolean packetVerified = new AtomicBoolean(); Sender sender = new Sender("localhost", 4009) { @Override diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/Receiver.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/Receiver.java index eddef62929..451a496ffe 100644 --- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/Receiver.java +++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/Receiver.java @@ -4,7 +4,9 @@ import org.collectd.api.ValueList; import org.collectd.protocol.Dispatcher; import org.collectd.protocol.UdpReceiver; -import org.junit.rules.ExternalResource; +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; import java.net.DatagramSocket; import java.net.InetAddress; @@ -13,20 +15,27 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -public final class Receiver extends ExternalResource { +public final class Receiver implements BeforeAllCallback, AfterAllCallback { private final int port; private UdpReceiver receiver; private DatagramSocket socket; - private BlockingQueue queue = new LinkedBlockingQueue<>(); + private final BlockingQueue queue = new LinkedBlockingQueue<>(); public Receiver(int port) { this.port = port; } + + @Override + public void afterAll(ExtensionContext context) throws Exception { + receiver.shutdown(); + socket.close(); + } + @Override - protected void before() throws Throwable { + public void beforeAll(ExtensionContext context) throws Exception { socket = new DatagramSocket(null); socket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), port)); @@ -54,10 +63,4 @@ public void dispatch(Notification notification) { public ValueList next() throws InterruptedException { return queue.poll(2, TimeUnit.SECONDS); } - - @Override - protected void after() { - receiver.shutdown(); - socket.close(); - } } diff --git a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java index 2a315fc98c..58dd4c634d 100644 --- a/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java +++ b/metrics-collectd/src/test/java/io/dropwizard/metrics5/collectd/SanitizeTest.java @@ -1,38 +1,38 @@ package io.dropwizard.metrics5.collectd; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class SanitizeTest { +class SanitizeTest { private Sanitize sanitize = new Sanitize(Sanitize.DEFAULT_MAX_LENGTH); @Test - public void replacesIllegalCharactersInName() throws Exception { + void replacesIllegalCharactersInName() throws Exception { assertThat(sanitize.name("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz_quux"); } @Test - public void replacesIllegalCharactersInInstanceName() throws Exception { + void replacesIllegalCharactersInInstanceName() throws Exception { assertThat(sanitize.instanceName("foo\u0000bar/baz-quux")).isEqualTo("foo_bar_baz-quux"); } @Test - public void truncatesNamesExceedingMaxLength() throws Exception { + void truncatesNamesExceedingMaxLength() throws Exception { String longName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; assertThat(sanitize.name(longName)).isEqualTo(longName.substring(0, (Sanitize.DEFAULT_MAX_LENGTH))); } @Test - public void truncatesNamesExceedingCustomMaxLength() throws Exception { + void truncatesNamesExceedingCustomMaxLength() throws Exception { Sanitize customSanitize = new Sanitize(70); String longName = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; assertThat(customSanitize.name(longName)).isEqualTo(longName.substring(0, 70)); } @Test - public void replacesNonASCIICharacters() throws Exception { + void replacesNonASCIICharacters() throws Exception { assertThat(sanitize.name("M" + '\u00FC' + "nchen")).isEqualTo("M_nchen"); } diff --git a/metrics-core/pom.xml b/metrics-core/pom.xml index 929e47bdbc..4329e945d3 100644 --- a/metrics-core/pom.xml +++ b/metrics-core/pom.xml @@ -36,18 +36,30 @@ slf4j-api ${slf4j.version} - - junit - junit - ${junit.version} - test - org.hamcrest hamcrest-core ${hamcrest.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.assertj assertj-core diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java index e20b5f5600..36b116e7a4 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CachedGaugeTest.java @@ -1,6 +1,6 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,9 +14,9 @@ import java.util.concurrent.atomic.AtomicLong; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class CachedGaugeTest { +class CachedGaugeTest { private static final Logger LOGGER = LoggerFactory.getLogger(CachedGaugeTest.class); private static final int THREAD_COUNT = 10; private static final long RUNNING_TIME_MILLIS = TimeUnit.SECONDS.toMillis(10); @@ -42,7 +42,7 @@ protected Integer loadValue() { private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); @Test - public void cachesTheValueForTheGivenPeriod() { + void cachesTheValueForTheGivenPeriod() { assertThat(gauge.getValue()) .isEqualTo(1); assertThat(gauge.getValue()) @@ -50,7 +50,7 @@ public void cachesTheValueForTheGivenPeriod() { } @Test - public void reloadsTheCachedValueAfterTheGivenPeriod() throws Exception { + void reloadsTheCachedValueAfterTheGivenPeriod() throws Exception { assertThat(gauge.getValue()) .isEqualTo(1); @@ -64,7 +64,7 @@ public void reloadsTheCachedValueAfterTheGivenPeriod() throws Exception { } @Test - public void reloadsCachedValueInNegativeTime() throws Exception { + void reloadsCachedValueInNegativeTime() throws Exception { AtomicLong time = new AtomicLong(-2L); Clock clock = new Clock() { @Override @@ -92,7 +92,7 @@ protected Integer loadValue() { } @Test - public void multipleThreadAccessReturnsConsistentResults() throws Exception { + void multipleThreadAccessReturnsConsistentResults() throws Exception { List> futures = new ArrayList<>(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { @@ -123,7 +123,7 @@ public void multipleThreadAccessReturnsConsistentResults() throws Exception { } for (int i = 0; i < futures.size(); i++) { - assertTrue("Future " + i + " failed", futures.get(i).get()); + assertTrue(futures.get(i).get(), "Future " + i + " failed"); } executor.shutdown(); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java index 1e69227ee4..6473c17007 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ChunkedAssociativeLongArrayTest.java @@ -2,12 +2,12 @@ import static org.assertj.core.api.BDDAssertions.then; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ChunkedAssociativeLongArrayTest { +class ChunkedAssociativeLongArrayTest { @Test - public void testTrim() { + void testTrim() { ChunkedAssociativeLongArray array = new ChunkedAssociativeLongArray(3); array.put(-3, 3); array.put(-2, 1); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java index 01c70ac7e8..da3e53713d 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ClockTest.java @@ -1,14 +1,14 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.offset; -public class ClockTest { +class ClockTest { @Test - public void userTimeClock() { + void userTimeClock() { final Clock.UserTimeClock clock = new Clock.UserTimeClock(); assertThat((double) clock.getTime()) @@ -21,7 +21,7 @@ public void userTimeClock() { } @Test - public void defaultsToUserTime() { + void defaultsToUserTime() { assertThat(Clock.defaultClock()) .isInstanceOf(Clock.UserTimeClock.class); } diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java index a51efb4d95..a7b6e38383 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ConsoleReporterTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; @@ -18,7 +18,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ConsoleReporterTest { +class ConsoleReporterTest { private final Locale locale = Locale.US; private final TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); @@ -37,8 +37,8 @@ public class ConsoleReporterTest { .build(); private String dateHeader; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(clock.getTime()).thenReturn(1363568676000L); // JDK9 has changed the java.text.DateFormat API implementation according to Unicode. // See http://mail.openjdk.java.net/pipermail/jdk9-dev/2017-April/005732.html @@ -48,7 +48,7 @@ public void setUp() throws Exception { } @Test - public void reportsGaugeValues() throws Exception { + void reportsGaugeValues() throws Exception { final Gauge gauge = () -> 1; reporter.report(map(MetricName.build("gauge"), gauge), @@ -70,7 +70,7 @@ public void reportsGaugeValues() throws Exception { } @Test - public void reportsCounterValues() throws Exception { + void reportsCounterValues() throws Exception { final Counter counter = mock(Counter.class); when(counter.getCount()).thenReturn(100L); @@ -93,7 +93,7 @@ public void reportsCounterValues() throws Exception { } @Test - public void reportsHistogramValues() throws Exception { + void reportsHistogramValues() throws Exception { final Histogram histogram = mock(Histogram.class); when(histogram.getCount()).thenReturn(1L); when(histogram.getSum()).thenReturn(4L); @@ -142,7 +142,7 @@ public void reportsHistogramValues() throws Exception { } @Test - public void reportsMeterValues() throws Exception { + void reportsMeterValues() throws Exception { final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getSum()).thenReturn(3L); @@ -175,7 +175,7 @@ public void reportsMeterValues() throws Exception { } @Test - public void reportsTimerValues() throws Exception { + void reportsTimerValues() throws Exception { final Timer timer = mock(Timer.class); when(timer.getCount()).thenReturn(1L); when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(5)); @@ -233,7 +233,7 @@ public void reportsTimerValues() throws Exception { } @Test - public void reportMeterWithDisabledAttributes() throws Exception { + void reportMeterWithDisabledAttributes() throws Exception { Set disabledMetricAttributes = EnumSet.of(MetricAttribute.M15_RATE, MetricAttribute.M5_RATE, MetricAttribute.COUNT, MetricAttribute.SUM); final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) @@ -275,7 +275,7 @@ public void reportMeterWithDisabledAttributes() throws Exception { } @Test - public void reportTimerWithDisabledAttributes() throws Exception { + void reportTimerWithDisabledAttributes() throws Exception { Set disabledMetricAttributes = EnumSet.of(MetricAttribute.P50, MetricAttribute.P999, MetricAttribute.M5_RATE, MetricAttribute.MAX); final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) @@ -342,7 +342,7 @@ public void reportTimerWithDisabledAttributes() throws Exception { } @Test - public void reportHistogramWithDisabledAttributes() throws Exception { + void reportHistogramWithDisabledAttributes() throws Exception { Set disabledMetricAttributes = EnumSet.of(MetricAttribute.MIN, MetricAttribute.MAX, MetricAttribute.STDDEV, MetricAttribute.P95); final ConsoleReporter customReporter = ConsoleReporter.forRegistry(registry) diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java index e22eecf2b9..9a53b2b702 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CounterTest.java @@ -1,20 +1,20 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class CounterTest { +class CounterTest { private final Counter counter = new Counter(); @Test - public void startsAtZero() { + void startsAtZero() { assertThat(counter.getCount()) .isZero(); } @Test - public void incrementsByOne() { + void incrementsByOne() { counter.inc(); assertThat(counter.getCount()) @@ -22,7 +22,7 @@ public void incrementsByOne() { } @Test - public void incrementsByAnArbitraryDelta() { + void incrementsByAnArbitraryDelta() { counter.inc(12); assertThat(counter.getCount()) @@ -30,7 +30,7 @@ public void incrementsByAnArbitraryDelta() { } @Test - public void decrementsByOne() { + void decrementsByOne() { counter.dec(); assertThat(counter.getCount()) @@ -38,7 +38,7 @@ public void decrementsByOne() { } @Test - public void decrementsByAnArbitraryDelta() { + void decrementsByAnArbitraryDelta() { counter.dec(12); assertThat(counter.getCount()) @@ -46,7 +46,7 @@ public void decrementsByAnArbitraryDelta() { } @Test - public void incrementByNegativeDelta() { + void incrementByNegativeDelta() { counter.inc(-12); assertThat(counter.getCount()) @@ -54,7 +54,7 @@ public void incrementByNegativeDelta() { } @Test - public void decrementByNegativeDelta() { + void decrementByNegativeDelta() { counter.dec(-12); assertThat(counter.getCount()) diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java index cf35750811..a9d5984623 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/CsvReporterTest.java @@ -1,9 +1,8 @@ package io.dropwizard.metrics5; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -20,8 +19,8 @@ import static org.mockito.Mockito.when; public class CsvReporterTest { - @Rule - public final TemporaryFolder folder = new TemporaryFolder(); + @TempDir + public File folder; private final MetricRegistry registry = mock(MetricRegistry.class); private final Clock clock = mock(Clock.class); @@ -29,11 +28,11 @@ public class CsvReporterTest { private File dataDirectory; private CsvReporter reporter; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(clock.getTime()).thenReturn(19910191000L); - this.dataDirectory = folder.newFolder(); + this.dataDirectory = newFolder(folder, "junit"); this.reporter = CsvReporter.forRegistry(registry) .formatFor(Locale.US) @@ -45,7 +44,7 @@ public void setUp() throws Exception { } @Test - public void reportsGaugeValues() throws Exception { + void reportsGaugeValues() throws Exception { final Gauge gauge = () -> 1; reporter.report(map(MetricName.build("gauge"), gauge), @@ -62,7 +61,7 @@ public void reportsGaugeValues() throws Exception { } @Test - public void reportsCounterValues() throws Exception { + void reportsCounterValues() throws Exception { final Counter counter = mock(Counter.class); when(counter.getCount()).thenReturn(100L); @@ -80,7 +79,7 @@ public void reportsCounterValues() throws Exception { } @Test - public void reportsHistogramValues() throws Exception { + void reportsHistogramValues() throws Exception { final Histogram histogram = mock(Histogram.class); when(histogram.getCount()).thenReturn(1L); when(histogram.getSum()).thenReturn(12L); @@ -113,7 +112,7 @@ public void reportsHistogramValues() throws Exception { } @Test - public void reportsMeterValues() throws Exception { + void reportsMeterValues() throws Exception { final Meter meter = mockMeter(); reporter.report(map(), @@ -130,7 +129,7 @@ public void reportsMeterValues() throws Exception { } @Test - public void reportsTimerValues() throws Exception { + void reportsTimerValues() throws Exception { final Timer timer = mock(Timer.class); when(timer.getCount()).thenReturn(1L); when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); @@ -167,7 +166,7 @@ public void reportsTimerValues() throws Exception { } @Test - public void testCsvFileProviderIsUsed() { + void testCsvFileProviderIsUsed() { CsvFileProvider fileProvider = mock(CsvFileProvider.class); when(fileProvider.getFile(dataDirectory, "gauge")).thenReturn(new File(dataDirectory, "guage.csv")); @@ -187,7 +186,7 @@ public void testCsvFileProviderIsUsed() { } @Test - public void itFormatsWithCustomSeparator() throws Exception { + void itFormatsWithCustomSeparator() throws Exception { final Meter meter = mockMeter(); CsvReporter customSeparatorReporter = CsvReporter.forRegistry(registry) @@ -245,4 +244,13 @@ private SortedMap map(MetricName name, T metric) { map.put(name, metric); return map; } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java index 94a600cc0b..1b2dc5d11f 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DefaultSettableGaugeTest.java @@ -1,24 +1,24 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class DefaultSettableGaugeTest { +class DefaultSettableGaugeTest { @Test - public void newSettableGaugeWithoutDefaultReturnsNull() { + void newSettableGaugeWithoutDefaultReturnsNull() { DefaultSettableGauge gauge = new DefaultSettableGauge<>(); assertThat(gauge.getValue()).isNull(); } @Test - public void newSettableGaugeWithDefaultReturnsDefault() { + void newSettableGaugeWithDefaultReturnsDefault() { DefaultSettableGauge gauge = new DefaultSettableGauge<>("default"); assertThat(gauge.getValue()).isEqualTo("default"); } @Test - public void setValueOverwritesExistingValue() { + void setValueOverwritesExistingValue() { DefaultSettableGauge gauge = new DefaultSettableGauge<>("default"); gauge.setValue("test"); assertThat(gauge.getValue()).isEqualTo("test"); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java index 5ae6d5a99f..8430cc3b59 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/DerivativeGaugeTest.java @@ -1,10 +1,10 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class DerivativeGaugeTest { +class DerivativeGaugeTest { private final Gauge gauge1 = () -> "woo"; private final Gauge gauge2 = new DerivativeGauge(gauge1) { @Override @@ -14,7 +14,7 @@ protected Integer transform(String value) { }; @Test - public void returnsATransformedValue() { + void returnsATransformedValue() { assertThat(gauge2.getValue()) .isEqualTo(3); } diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java index 04615aaf37..df83e60868 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/EWMATest.java @@ -1,15 +1,15 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.offset; -public class EWMATest { +class EWMATest { @Test - public void aOneMinuteEWMAWithAValueOfThree() { + void aOneMinuteEWMAWithAValueOfThree() { final EWMA ewma = EWMA.oneMinuteEWMA(); ewma.update(3); ewma.tick(); @@ -78,7 +78,7 @@ public void aOneMinuteEWMAWithAValueOfThree() { } @Test - public void aFiveMinuteEWMAWithAValueOfThree() { + void aFiveMinuteEWMAWithAValueOfThree() { final EWMA ewma = EWMA.fiveMinuteEWMA(); ewma.update(3); ewma.tick(); @@ -147,7 +147,7 @@ public void aFiveMinuteEWMAWithAValueOfThree() { } @Test - public void aFifteenMinuteEWMAWithAValueOfThree() { + void aFifteenMinuteEWMAWithAValueOfThree() { final EWMA ewma = EWMA.fifteenMinuteEWMA(); ewma.update(3); ewma.tick(); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java index 29bc2b2af6..52025a97bc 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ExponentiallyDecayingReservoirTest.java @@ -1,8 +1,7 @@ package io.dropwizard.metrics5; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collection; @@ -13,16 +12,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ExponentiallyDecayingReservoirTest { public enum ReservoirFactory { EXPONENTIALLY_DECAYING() { - @Override - Reservoir create(int size, double alpha, Clock clock) { - return new ExponentiallyDecayingReservoir(size, alpha, clock); - } - }, + @Override + Reservoir create(int size, double alpha, Clock clock) { + return new ExponentiallyDecayingReservoir(size, alpha, clock); + } + }, LOCK_FREE_EXPONENTIALLY_DECAYING() { @Override @@ -42,21 +40,22 @@ Reservoir create(int size, double alpha) { } } - @Parameterized.Parameters(name = "{index}: {0}") public static Collection reservoirs() { return Arrays.stream(ReservoirFactory.values()) - .map(value -> new Object[] {value}) + .map(value -> new Object[]{value}) .collect(Collectors.toList()); } - private final ReservoirFactory reservoirFactory; + private ReservoirFactory reservoirFactory; - public ExponentiallyDecayingReservoirTest(ReservoirFactory reservoirFactory) { + public void initExponentiallyDecayingReservoirTest(ReservoirFactory reservoirFactory) { this.reservoirFactory = reservoirFactory; } - @Test - public void aReservoirOf100OutOf1000Elements() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void aReservoirOf100OutOf1000Elements(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); final Reservoir reservoir = reservoirFactory.create(100, 0.99); for (int i = 0; i < 1000; i++) { reservoir.update(i); @@ -73,8 +72,10 @@ public void aReservoirOf100OutOf1000Elements() { assertAllValuesBetween(reservoir, 0, 1000); } - @Test - public void aReservoirOf100OutOf10Elements() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void aReservoirOf100OutOf10Elements(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); final Reservoir reservoir = reservoirFactory.create(100, 0.99); for (int i = 0; i < 10; i++) { reservoir.update(i); @@ -91,8 +92,10 @@ public void aReservoirOf100OutOf10Elements() { assertAllValuesBetween(reservoir, 0, 10); } - @Test - public void aHeavilyBiasedReservoirOf100OutOf1000Elements() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void aHeavilyBiasedReservoirOf100OutOf1000Elements(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); final Reservoir reservoir = reservoirFactory.create(1000, 0.01); for (int i = 0; i < 100; i++) { reservoir.update(i); @@ -110,8 +113,10 @@ public void aHeavilyBiasedReservoirOf100OutOf1000Elements() { assertAllValuesBetween(reservoir, 0, 100); } - @Test - public void longPeriodsOfInactivityShouldNotCorruptSamplingState() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void longPeriodsOfInactivityShouldNotCorruptSamplingState(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); final ManualClock clock = new ManualClock(); final Reservoir reservoir = reservoirFactory.create(10, 0.15, clock); @@ -144,8 +149,10 @@ public void longPeriodsOfInactivityShouldNotCorruptSamplingState() { assertAllValuesBetween(reservoir, 3000, 4000); } - @Test - public void longPeriodsOfInactivity_fetchShouldResample() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void longPeriodsOfInactivity_fetchShouldResample(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); final ManualClock clock = new ManualClock(); final Reservoir reservoir = reservoirFactory.create(10, 0.015, @@ -171,8 +178,10 @@ public void longPeriodsOfInactivity_fetchShouldResample() { assertThat(snapshot.size()).isEqualTo(0); } - @Test - public void emptyReservoirSnapshot_shouldReturnZeroForAllValues() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void emptyReservoirSnapshot_shouldReturnZeroForAllValues(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); final Reservoir reservoir = reservoirFactory.create(100, 0.015, new ManualClock()); @@ -183,8 +192,10 @@ public void emptyReservoirSnapshot_shouldReturnZeroForAllValues() { assertThat(snapshot.size()).isEqualTo(0); } - @Test - public void removeZeroWeightsInSamplesToPreventNaNInMeanValues() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void removeZeroWeightsInSamplesToPreventNaNInMeanValues(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); final ManualClock clock = new ManualClock(); final Reservoir reservoir = reservoirFactory.create(1028, 0.015, clock); Timer timer = new Timer(reservoir, clock); @@ -199,8 +210,10 @@ public void removeZeroWeightsInSamplesToPreventNaNInMeanValues() { } } - @Test - public void multipleUpdatesAfterlongPeriodsOfInactivityShouldNotCorruptSamplingState() throws Exception { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void multipleUpdatesAfterlongPeriodsOfInactivityShouldNotCorruptSamplingState(ReservoirFactory reservoirFactory) throws Exception { + initExponentiallyDecayingReservoirTest(reservoirFactory); // This test illustrates the potential race condition in rescale that // can lead to a corrupt state. Note that while this test uses updates // exclusively to trigger the race condition, two concurrent updates @@ -295,8 +308,10 @@ public void multipleUpdatesAfterlongPeriodsOfInactivityShouldNotCorruptSamplingS } } - @Test - public void spotLift() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void spotLift(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); final ManualClock clock = new ManualClock(); final Reservoir reservoir = reservoirFactory.create(1000, 0.015, @@ -321,8 +336,10 @@ public void spotLift() { .isEqualTo(9999); } - @Test - public void spotFall() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void spotFall(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); final ManualClock clock = new ManualClock(); final Reservoir reservoir = reservoirFactory.create(1000, 0.015, @@ -347,8 +364,10 @@ public void spotFall() { .isEqualTo(178); } - @Test - public void quantiliesShouldBeBasedOnWeights() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void quantiliesShouldBeBasedOnWeights(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); final ManualClock clock = new ManualClock(); final Reservoir reservoir = reservoirFactory.create(1000, 0.015, @@ -375,8 +394,10 @@ public void quantiliesShouldBeBasedOnWeights() { .isEqualTo(9999); } - @Test - public void clockWrapShouldNotRescale() { + @MethodSource("reservoirs") + @ParameterizedTest(name = "{index}: {0}") + void clockWrapShouldNotRescale(ReservoirFactory reservoirFactory) { + initExponentiallyDecayingReservoirTest(reservoirFactory); // First verify the test works as expected given low values testShortPeriodShouldNotRescale(0); // Now revalidate using an edge case nanoTime value just prior to wrapping @@ -404,8 +425,8 @@ private void testShortPeriodShouldNotRescale(long startTimeNanos) { } private static void assertAllValuesBetween(Reservoir reservoir, - double min, - double max) { + double min, + double max) { for (double i : reservoir.getSnapshot().getValues()) { assertThat(i) .isLessThan(max) diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java index 511f86c80e..9d84b50d22 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/FixedNameCsvFileProviderTest.java @@ -1,27 +1,27 @@ package io.dropwizard.metrics5; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; +import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; public class FixedNameCsvFileProviderTest { - @Rule - public final TemporaryFolder folder = new TemporaryFolder(); + @TempDir + public File folder; private File dataDirectory; - @Before - public void setUp() throws Exception { - this.dataDirectory = folder.newFolder(); + @BeforeEach + void setUp() throws Exception { + this.dataDirectory = newFolder(folder, "junit"); } @Test - public void testGetFile() { + void testGetFile() { FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); File file = provider.getFile(dataDirectory, "test"); assertThat(file.getParentFile()).isEqualTo(dataDirectory); @@ -29,10 +29,19 @@ public void testGetFile() { } @Test - public void testGetFileSanitize() { + void testGetFileSanitize() { FixedNameCsvFileProvider provider = new FixedNameCsvFileProvider(); File file = provider.getFile(dataDirectory, "/myfake/uri"); assertThat(file.getParentFile()).isEqualTo(dataDirectory); assertThat(file.getName()).isEqualTo("myfake.uri.csv"); } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } } \ No newline at end of file diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java index 7a7d35230c..7442ef3188 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/HistogramTest.java @@ -1,18 +1,18 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class HistogramTest { +class HistogramTest { private final Reservoir reservoir = mock(Reservoir.class); private final Histogram histogram = new Histogram(reservoir); @Test - public void updatesTheCountAndSumOnUpdates() { + void updatesTheCountAndSumOnUpdates() { assertThat(histogram.getCount()) .isZero(); assertThat(histogram.getSum()) @@ -28,7 +28,7 @@ public void updatesTheCountAndSumOnUpdates() { } @Test - public void returnsTheSnapshotFromTheReservoir() { + void returnsTheSnapshotFromTheReservoir() { final Snapshot snapshot = mock(Snapshot.class); when(reservoir.getSnapshot()).thenReturn(snapshot); @@ -37,7 +37,7 @@ public void returnsTheSnapshotFromTheReservoir() { } @Test - public void updatesTheReservoir() throws Exception { + void updatesTheReservoir() throws Exception { histogram.update(1); verify(reservoir).update(1); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java index fb9e35eefc..1c66c409b9 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedExecutorServiceTest.java @@ -1,8 +1,8 @@ package io.dropwizard.metrics5; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -18,7 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class InstrumentedExecutorServiceTest { +class InstrumentedExecutorServiceTest { private static final Logger LOGGER = LoggerFactory.getLogger(InstrumentedExecutorServiceTest.class); private ExecutorService executor; @@ -30,8 +30,8 @@ public class InstrumentedExecutorServiceTest { private Timer duration; private Timer idle; - @Before - public void setup() { + @BeforeEach + void setup() { executor = Executors.newCachedThreadPool(); registry = new MetricRegistry(); instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "xs"); @@ -42,8 +42,8 @@ public void setup() { idle = registry.timer("xs.idle"); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { instrumentedExecutorService.shutdown(); if (!instrumentedExecutorService.awaitTermination(2, TimeUnit.SECONDS)) { LOGGER.error("InstrumentedExecutorService did not terminate."); @@ -51,7 +51,7 @@ public void tearDown() throws Exception { } @Test - public void reportsTasksInformationForRunnable() throws Exception { + void reportsTasksInformationForRunnable() throws Exception { assertThat(submitted.getCount()).isEqualTo(0); assertThat(running.getCount()).isEqualTo(0); @@ -81,7 +81,7 @@ public void reportsTasksInformationForRunnable() throws Exception { } @Test - public void reportsTasksInformationForCallable() throws Exception { + void reportsTasksInformationForCallable() throws Exception { assertThat(submitted.getCount()).isEqualTo(0); assertThat(running.getCount()).isEqualTo(0); @@ -113,7 +113,7 @@ public void reportsTasksInformationForCallable() throws Exception { @Test @SuppressWarnings("unchecked") - public void reportsTasksInformationForThreadPoolExecutor() throws Exception { + void reportsTasksInformationForThreadPoolExecutor() throws Exception { executor = new ThreadPoolExecutor(4, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(32)); instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "tp"); @@ -169,7 +169,7 @@ public void reportsTasksInformationForThreadPoolExecutor() throws Exception { @Test @SuppressWarnings("unchecked") - public void reportsTasksInformationForForkJoinPool() throws Exception { + void reportsTasksInformationForForkJoinPool() throws Exception { executor = Executors.newWorkStealingPool(4); instrumentedExecutorService = new InstrumentedExecutorService(executor, registry, "fjp"); submitted = registry.meter("fjp.submitted"); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java index c543daa3d1..3cb278b819 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedScheduledExecutorServiceTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,7 +14,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class InstrumentedScheduledExecutorServiceTest { +class InstrumentedScheduledExecutorServiceTest { private static final Logger LOGGER = LoggerFactory.getLogger(InstrumentedScheduledExecutorServiceTest.class); private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); @@ -33,7 +33,7 @@ public class InstrumentedScheduledExecutorServiceTest { private final Histogram percentOfPeriod = registry.histogram("xs.scheduled.percent-of-period"); @Test - public void testSubmitRunnable() throws Exception { + void testSubmitRunnable() throws Exception { assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isZero(); @@ -74,7 +74,7 @@ public void testSubmitRunnable() throws Exception { } @Test - public void testScheduleRunnable() throws Exception { + void testScheduleRunnable() throws Exception { assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isZero(); @@ -115,7 +115,7 @@ public void testScheduleRunnable() throws Exception { } @Test - public void testSubmitCallable() throws Exception { + void testSubmitCallable() throws Exception { assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isZero(); @@ -160,7 +160,7 @@ public void testSubmitCallable() throws Exception { } @Test - public void testScheduleCallable() throws Exception { + void testScheduleCallable() throws Exception { assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isZero(); @@ -205,7 +205,7 @@ public void testScheduleCallable() throws Exception { } @Test - public void testScheduleFixedRateCallable() throws Exception { + void testScheduleFixedRateCallable() throws Exception { assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isZero(); @@ -252,7 +252,7 @@ public void testScheduleFixedRateCallable() throws Exception { } @Test - public void testScheduleFixedDelayCallable() throws Exception { + void testScheduleFixedDelayCallable() throws Exception { assertThat(submitted.getCount()).isZero(); assertThat(running.getCount()).isZero(); @@ -294,8 +294,8 @@ public void testScheduleFixedDelayCallable() throws Exception { assertThat(duration.getSnapshot().size()).isNotEqualTo(0); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { instrumentedScheduledExecutor.shutdown(); if (!instrumentedScheduledExecutor.awaitTermination(2, TimeUnit.SECONDS)) { LOGGER.error("InstrumentedScheduledExecutorService did not terminate."); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java index 9350f785bb..9d0b515e2d 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/InstrumentedThreadFactoryTest.java @@ -10,9 +10,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class InstrumentedThreadFactoryTest { +class InstrumentedThreadFactoryTest { private static final int THREAD_COUNT = 10; private final ThreadFactory factory = Executors.defaultThreadFactory(); @@ -26,7 +26,7 @@ public class InstrumentedThreadFactoryTest { * TODO: Try not using real threads in a unit test? */ @Test - public void reportsThreadInformation() throws Exception { + void reportsThreadInformation() throws Exception { final CountDownLatch allTasksAreCreated = new CountDownLatch(THREAD_COUNT); final CountDownLatch allTasksAreCounted = new CountDownLatch(1); final AtomicInteger interrupted = new AtomicInteger(); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java index f5636a9b57..662e83a0a1 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterApproximationTest.java @@ -1,9 +1,7 @@ package io.dropwizard.metrics5; -import org.junit.Test; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runner.RunWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; import java.util.Collection; @@ -12,10 +10,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.offset; -@RunWith(value = Parameterized.class) public class MeterApproximationTest { - @Parameters public static Collection ratesPerMinute() { Object[][] data = new Object[][]{ {15}, {60}, {600}, {6000} @@ -23,14 +19,16 @@ public static Collection ratesPerMinute() { return Arrays.asList(data); } - private final long ratePerMinute; + private long ratePerMinute; - public MeterApproximationTest(long ratePerMinute) { + public void initMeterApproximationTest(long ratePerMinute) { this.ratePerMinute = ratePerMinute; } - @Test - public void controlMeter1MinuteMeanApproximation() { + @MethodSource("ratesPerMinute") + @ParameterizedTest + void controlMeter1MinuteMeanApproximation(long ratePerMinute) { + initMeterApproximationTest(ratePerMinute); final Meter meter = simulateMetronome( 62934, TimeUnit.MILLISECONDS, 3, TimeUnit.MINUTES); @@ -39,8 +37,10 @@ public void controlMeter1MinuteMeanApproximation() { .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); } - @Test - public void controlMeter5MinuteMeanApproximation() { + @MethodSource("ratesPerMinute") + @ParameterizedTest + void controlMeter5MinuteMeanApproximation(long ratePerMinute) { + initMeterApproximationTest(ratePerMinute); final Meter meter = simulateMetronome( 62934, TimeUnit.MILLISECONDS, 13, TimeUnit.MINUTES); @@ -49,8 +49,10 @@ public void controlMeter5MinuteMeanApproximation() { .isEqualTo(ratePerMinute, offset(0.1 * ratePerMinute)); } - @Test - public void controlMeter15MinuteMeanApproximation() { + @MethodSource("ratesPerMinute") + @ParameterizedTest + void controlMeter15MinuteMeanApproximation(long ratePerMinute) { + initMeterApproximationTest(ratePerMinute); final Meter meter = simulateMetronome( 62934, TimeUnit.MILLISECONDS, 38, TimeUnit.MINUTES); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java index a0c4cfc653..4c30d38957 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MeterTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; @@ -10,18 +10,18 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class MeterTest { +class MeterTest { private final Clock clock = mock(Clock.class); private final Meter meter = new Meter(clock); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(clock.getTick()).thenReturn(0L, TimeUnit.SECONDS.toNanos(10)); } @Test - public void startsOutWithNoRatesOrCount() { + void startsOutWithNoRatesOrCount() { assertThat(meter.getCount()) .isZero(); @@ -42,7 +42,7 @@ public void startsOutWithNoRatesOrCount() { } @Test - public void marksEventsAndUpdatesRatesAndCount() { + void marksEventsAndUpdatesRatesAndCount() { meter.mark(); meter.mark(2); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java index 62017b9da9..5723f3bec7 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricFilterTest.java @@ -1,19 +1,19 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -public class MetricFilterTest { +class MetricFilterTest { @Test - public void theAllFilterMatchesAllMetrics() { + void theAllFilterMatchesAllMetrics() { assertThat(MetricFilter.ALL.matches(MetricName.build(""), mock(Metric.class))) .isTrue(); } @Test - public void theStartsWithFilterMatches() { + void theStartsWithFilterMatches() { assertThat(MetricFilter.startsWith("foo").matches(MetricName.build("foo.bar"), mock(Metric.class))) .isTrue(); assertThat(MetricFilter.startsWith("foo").matches(MetricName.build("bar.foo"), mock(Metric.class))) @@ -21,7 +21,7 @@ public void theStartsWithFilterMatches() { } @Test - public void theEndsWithFilterMatches() { + void theEndsWithFilterMatches() { assertThat(MetricFilter.endsWith("foo").matches(MetricName.build("foo.bar"), mock(Metric.class))) .isFalse(); assertThat(MetricFilter.endsWith("foo").matches(MetricName.build("bar.foo"), mock(Metric.class))) @@ -29,7 +29,7 @@ public void theEndsWithFilterMatches() { } @Test - public void theContainsFilterMatches() { + void theContainsFilterMatches() { assertThat(MetricFilter.contains("foo").matches(MetricName.build("bar.foo.bar"), mock(Metric.class))) .isTrue(); assertThat(MetricFilter.contains("foo").matches(MetricName.build("bar.bar"), mock(Metric.class))) diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java index 2dd3e9a308..892765ad1c 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricNameTest.java @@ -1,48 +1,49 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class MetricNameTest { +class MetricNameTest { @Test - public void testEmpty() { + void testEmpty() { assertThat(MetricName.EMPTY.getTags()).isEmpty(); assertThat(MetricName.EMPTY.getKey()).isEqualTo(""); assertThat(MetricName.build()).isEqualTo(MetricName.EMPTY); - assertThat(MetricName.EMPTY.resolve((String)null)).isEqualTo(MetricName.EMPTY); + assertThat(MetricName.EMPTY.resolve((String) null)).isEqualTo(MetricName.EMPTY); } @Test - public void testEmptyResolve() { + void testEmptyResolve() { final MetricName name = MetricName.build(); assertThat(name.resolve("foo")).isEqualTo(MetricName.build("foo")); } @Test - public void testResolveToEmpty() { + void testResolveToEmpty() { final MetricName name = MetricName.build("foo"); - assertThat(name.resolve((String)null)).isEqualTo(MetricName.build("foo")); + assertThat(name.resolve((String) null)).isEqualTo(MetricName.build("foo")); } @Test - public void testResolve() { + void testResolve() { final MetricName name = MetricName.build("foo"); assertThat(name.resolve("bar")).isEqualTo(MetricName.build("foo.bar")); } @Test - public void testResolveBothEmpty() { + void testResolveBothEmpty() { final MetricName name = MetricName.build(); - assertThat(name.resolve((String)null)).isEqualTo(MetricName.EMPTY); + assertThat(name.resolve((String) null)).isEqualTo(MetricName.EMPTY); } @Test - public void testAddTagsVarious() { + void testAddTagsVarious() { final Map refTags = new HashMap(); refTags.put("foo", "bar"); final MetricName test = MetricName.EMPTY.tagged("foo", "bar"); @@ -56,25 +57,29 @@ public void testAddTagsVarious() { } @Test - public void testTaggedMoreArguments() { + void testTaggedMoreArguments() { final Map refTags = new HashMap(); refTags.put("foo", "bar"); refTags.put("baz", "biz"); assertThat(MetricName.EMPTY.tagged("foo", "bar", "baz", "biz").getTags()).isEqualTo(refTags); } - @Test(expected = IllegalArgumentException.class) - public void testTaggedNotPairs() { - MetricName.EMPTY.tagged("foo"); + @Test + void testTaggedNotPairs() { + assertThrows(IllegalArgumentException.class, () -> { + MetricName.EMPTY.tagged("foo"); + }); } - @Test(expected = IllegalArgumentException.class) - public void testTaggedNotPairs2() { - MetricName.EMPTY.tagged("foo", "bar", "baz"); + @Test + void testTaggedNotPairs2() { + assertThrows(IllegalArgumentException.class, () -> { + MetricName.EMPTY.tagged("foo", "bar", "baz"); + }); } @Test - public void testCompareTo() { + void testCompareTo() { final MetricName a = MetricName.EMPTY.tagged("foo", "bar"); final MetricName b = MetricName.EMPTY.tagged("foo", "baz"); @@ -85,7 +90,7 @@ public void testCompareTo() { } @Test - public void testCompareTo2() { + void testCompareTo2() { final MetricName a = MetricName.EMPTY.tagged("a", "x"); final MetricName b = MetricName.EMPTY.tagged("b", "x"); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java index 1b775c4958..31e338fa5b 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryListenerTest.java @@ -1,11 +1,11 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; -public class MetricRegistryListenerTest { +class MetricRegistryListenerTest { private static final MetricName BLAH = MetricName.build("blah"); private final Counter counter = mock(Counter.class); @@ -17,42 +17,42 @@ public class MetricRegistryListenerTest { }; @Test - public void noOpsOnGaugeAdded() { + void noOpsOnGaugeAdded() { listener.onGaugeAdded(BLAH, () -> { throw new RuntimeException("Should not be called"); }); } @Test - public void noOpsOnCounterAdded() { + void noOpsOnCounterAdded() { listener.onCounterAdded(BLAH, counter); verifyNoInteractions(counter); } @Test - public void noOpsOnHistogramAdded() { + void noOpsOnHistogramAdded() { listener.onHistogramAdded(BLAH, histogram); verifyNoInteractions(histogram); } @Test - public void noOpsOnMeterAdded() { + void noOpsOnMeterAdded() { listener.onMeterAdded(BLAH, meter); verifyNoInteractions(meter); } @Test - public void noOpsOnTimerAdded() { + void noOpsOnTimerAdded() { listener.onTimerAdded(BLAH, timer); verifyNoInteractions(timer); } @Test - public void doesNotExplodeWhenMetricsAreRemoved() { + void doesNotExplodeWhenMetricsAreRemoved() { listener.onGaugeRemoved(BLAH); listener.onCounterRemoved(BLAH); listener.onHistogramRemoved(BLAH); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java index a083f89ff2..1617a7f734 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/MetricRegistryTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -16,7 +16,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -public class MetricRegistryTest { +class MetricRegistryTest { private static class CustomCounter extends Counter { @@ -47,13 +47,13 @@ public void incTheAnswer() { private final Meter meter = mock(Meter.class); private final Timer timer = mock(Timer.class); - @Before - public void setUp() { + @BeforeEach + void setUp() { registry.addListener(listener); } @Test - public void registeringAGaugeTriggersANotification() { + void registeringAGaugeTriggersANotification() { assertThat(registry.register(THING, gauge)) .isEqualTo(gauge); @@ -61,7 +61,7 @@ public void registeringAGaugeTriggersANotification() { } @Test - public void removingAGaugeTriggersANotification() { + void removingAGaugeTriggersANotification() { registry.register(THING, gauge); assertThat(registry.remove(THING)) @@ -71,7 +71,7 @@ public void removingAGaugeTriggersANotification() { } @Test - public void registeringACounterTriggersANotification() { + void registeringACounterTriggersANotification() { assertThat(registry.register(THING, counter)) .isEqualTo(counter); @@ -79,7 +79,7 @@ public void registeringACounterTriggersANotification() { } @Test - public void accessingACounterRegistersAndReusesTheCounter() { + void accessingACounterRegistersAndReusesTheCounter() { final Counter counter1 = registry.counter(THING); final Counter counter2 = registry.counter(THING); @@ -90,7 +90,7 @@ public void accessingACounterRegistersAndReusesTheCounter() { } @Test - public void accessingACustomCounterRegistersAndReusesTheCounter() { + void accessingACustomCounterRegistersAndReusesTheCounter() { final MetricRegistry.MetricSupplier supplier = () -> counter; final Counter counter1 = registry.counter(THING, supplier); final Counter counter2 = registry.counter(THING, supplier); @@ -102,7 +102,7 @@ public void accessingACustomCounterRegistersAndReusesTheCounter() { } @Test - public void createsTypesafeCustomCounter() { + void createsTypesafeCustomCounter() { MetricName name = MetricName.build("custom-counter"); final CustomCounter customCounter = registry.counter(name, CustomCounter::new); customCounter.incTheAnswer(); @@ -111,7 +111,7 @@ public void createsTypesafeCustomCounter() { } @Test - public void removingACounterTriggersANotification() { + void removingACounterTriggersANotification() { registry.register(THING, counter); assertThat(registry.remove(THING)) @@ -121,7 +121,7 @@ public void removingACounterTriggersANotification() { } @Test - public void registeringAHistogramTriggersANotification() { + void registeringAHistogramTriggersANotification() { assertThat(registry.register(THING, histogram)) .isEqualTo(histogram); @@ -129,7 +129,7 @@ public void registeringAHistogramTriggersANotification() { } @Test - public void accessingAHistogramRegistersAndReusesIt() { + void accessingAHistogramRegistersAndReusesIt() { final Histogram histogram1 = registry.histogram(THING); final Histogram histogram2 = registry.histogram(THING); @@ -140,7 +140,7 @@ public void accessingAHistogramRegistersAndReusesIt() { } @Test - public void accessingACustomHistogramRegistersAndReusesIt() { + void accessingACustomHistogramRegistersAndReusesIt() { final MetricRegistry.MetricSupplier supplier = () -> histogram; final Histogram histogram1 = registry.histogram(THING, supplier); final Histogram histogram2 = registry.histogram(THING, supplier); @@ -152,7 +152,7 @@ public void accessingACustomHistogramRegistersAndReusesIt() { } @Test - public void removingAHistogramTriggersANotification() { + void removingAHistogramTriggersANotification() { registry.register(THING, histogram); assertThat(registry.remove(THING)) @@ -162,7 +162,7 @@ public void removingAHistogramTriggersANotification() { } @Test - public void registeringAMeterTriggersANotification() { + void registeringAMeterTriggersANotification() { assertThat(registry.register(THING, meter)) .isEqualTo(meter); @@ -170,7 +170,7 @@ public void registeringAMeterTriggersANotification() { } @Test - public void accessingAMeterRegistersAndReusesIt() { + void accessingAMeterRegistersAndReusesIt() { final Meter meter1 = registry.meter(THING); final Meter meter2 = registry.meter(THING); @@ -181,7 +181,7 @@ public void accessingAMeterRegistersAndReusesIt() { } @Test - public void accessingACustomMeterRegistersAndReusesIt() { + void accessingACustomMeterRegistersAndReusesIt() { final MetricRegistry.MetricSupplier supplier = () -> meter; final Meter meter1 = registry.meter(THING, supplier); final Meter meter2 = registry.meter(THING, supplier); @@ -193,7 +193,7 @@ public void accessingACustomMeterRegistersAndReusesIt() { } @Test - public void removingAMeterTriggersANotification() { + void removingAMeterTriggersANotification() { registry.register(THING, meter); assertThat(registry.remove(THING)) @@ -203,7 +203,7 @@ public void removingAMeterTriggersANotification() { } @Test - public void registeringATimerTriggersANotification() { + void registeringATimerTriggersANotification() { assertThat(registry.register(THING, timer)) .isEqualTo(timer); @@ -211,7 +211,7 @@ public void registeringATimerTriggersANotification() { } @Test - public void accessingATimerRegistersAndReusesIt() { + void accessingATimerRegistersAndReusesIt() { final Timer timer1 = registry.timer(THING); final Timer timer2 = registry.timer(THING); @@ -222,7 +222,7 @@ public void accessingATimerRegistersAndReusesIt() { } @Test - public void accessingACustomTimerRegistersAndReusesIt() { + void accessingACustomTimerRegistersAndReusesIt() { final MetricRegistry.MetricSupplier supplier = () -> timer; final Timer timer1 = registry.timer(THING, supplier); final Timer timer2 = registry.timer(THING, supplier); @@ -235,7 +235,7 @@ public void accessingACustomTimerRegistersAndReusesIt() { @Test - public void removingATimerTriggersANotification() { + void removingATimerTriggersANotification() { registry.register(THING, timer); assertThat(registry.remove(THING)) @@ -245,7 +245,7 @@ public void removingATimerTriggersANotification() { } @Test - public void accessingACustomGaugeRegistersAndReusesIt() { + void accessingACustomGaugeRegistersAndReusesIt() { final MetricRegistry.MetricSupplier> supplier = () -> gauge; final Gauge gauge1 = registry.gauge(THING, supplier); final Gauge gauge2 = registry.gauge(THING, supplier); @@ -257,7 +257,7 @@ public void accessingACustomGaugeRegistersAndReusesIt() { } @Test - public void accessingASettableGaugeRegistersAndReusesIt() { + void accessingASettableGaugeRegistersAndReusesIt() { final SettableGauge gauge1 = registry.gauge(THING); gauge1.setValue("Test"); final Gauge gauge2 = registry.gauge(THING); @@ -269,7 +269,7 @@ public void accessingASettableGaugeRegistersAndReusesIt() { } @Test - public void accessingAnExistingGaugeReusesIt() { + void accessingAnExistingGaugeReusesIt() { final Gauge gauge1 = registry.gauge(THING, () -> () -> "string-gauge"); final Gauge gauge2 = registry.gauge(THING, () -> new DefaultSettableGauge<>("settable-gauge")); @@ -280,7 +280,7 @@ public void accessingAnExistingGaugeReusesIt() { } @Test - public void accessingAnExistingSettableGaugeReusesIt() { + void accessingAnExistingSettableGaugeReusesIt() { final Gauge gauge1 = registry.gauge(THING, () -> new DefaultSettableGauge<>("settable-gauge")); final Gauge gauge2 = registry.gauge(THING); @@ -291,7 +291,7 @@ public void accessingAnExistingSettableGaugeReusesIt() { } @Test - public void settableGaugeIsTreatedLikeAGauge() { + void settableGaugeIsTreatedLikeAGauge() { final MetricRegistry.MetricSupplier> supplier = () -> settableGauge; final SettableGauge gauge1 = registry.gauge(THING, supplier); final SettableGauge gauge2 = registry.gauge(THING, supplier); @@ -303,7 +303,7 @@ public void settableGaugeIsTreatedLikeAGauge() { } @Test - public void addingAListenerWithExistingMetricsCatchesItUp() { + void addingAListenerWithExistingMetricsCatchesItUp() { registry.register(GAUGE2, gauge); registry.register(SETTABLE_GAUGE, settableGauge); registry.register(COUNTER2, counter); @@ -323,7 +323,7 @@ public void addingAListenerWithExistingMetricsCatchesItUp() { } @Test - public void aRemovedListenerDoesNotReceiveUpdates() { + void aRemovedListenerDoesNotReceiveUpdates() { registry.register(GAUGE, gauge); registry.removeListener(listener); registry.register(GAUGE2, gauge); @@ -332,7 +332,7 @@ public void aRemovedListenerDoesNotReceiveUpdates() { } @Test - public void hasAMapOfRegisteredGauges() { + void hasAMapOfRegisteredGauges() { registry.register(GAUGE2, gauge); registry.register(SETTABLE_GAUGE, settableGauge); @@ -342,7 +342,7 @@ public void hasAMapOfRegisteredGauges() { } @Test - public void hasAMapOfRegisteredCounters() { + void hasAMapOfRegisteredCounters() { registry.register(COUNTER2, counter); assertThat(registry.getCounters()) @@ -350,7 +350,7 @@ public void hasAMapOfRegisteredCounters() { } @Test - public void hasAMapOfRegisteredHistograms() { + void hasAMapOfRegisteredHistograms() { registry.register(HISTOGRAM2, histogram); assertThat(registry.getHistograms()) @@ -358,7 +358,7 @@ public void hasAMapOfRegisteredHistograms() { } @Test - public void hasAMapOfRegisteredMeters() { + void hasAMapOfRegisteredMeters() { registry.register(METER2, meter); assertThat(registry.getMeters()) @@ -366,7 +366,7 @@ public void hasAMapOfRegisteredMeters() { } @Test - public void hasAMapOfRegisteredTimers() { + void hasAMapOfRegisteredTimers() { registry.register(TIMER2, timer); assertThat(registry.getTimers()) @@ -374,7 +374,7 @@ public void hasAMapOfRegisteredTimers() { } @Test - public void hasASetOfRegisteredMetricNames() { + void hasASetOfRegisteredMetricNames() { registry.register(GAUGE2, gauge); registry.register(SETTABLE_GAUGE, settableGauge); registry.register(COUNTER2, counter); @@ -387,7 +387,7 @@ public void hasASetOfRegisteredMetricNames() { } @Test - public void registersMultipleMetrics() { + void registersMultipleMetrics() { final MetricSet metrics = () -> { final Map m = new HashMap<>(); m.put(GAUGE2, gauge); @@ -402,7 +402,7 @@ public void registersMultipleMetrics() { } @Test - public void registersMultipleMetricsWithAPrefix() { + void registersMultipleMetricsWithAPrefix() { final MetricName myCounter = MetricName.build("my.counter"); final MetricName myGauge = MetricName.build("my.gauge"); @@ -420,7 +420,7 @@ public void registersMultipleMetricsWithAPrefix() { } @Test - public void registersRecursiveMetricSets() { + void registersRecursiveMetricSets() { final MetricSet inner = () -> { final Map m = new HashMap<>(); m.put(GAUGE, gauge); @@ -444,7 +444,7 @@ public void registersRecursiveMetricSets() { } @Test - public void registersMetricsFromAnotherRegistry() { + void registersMetricsFromAnotherRegistry() { MetricRegistry other = new MetricRegistry(); other.register(GAUGE, gauge); registry.register("nested", other); @@ -452,44 +452,44 @@ public void registersMetricsFromAnotherRegistry() { } @Test - public void concatenatesStringsToFormADottedName() { + void concatenatesStringsToFormADottedName() { assertThat(name("one", "two", "three")) .isEqualTo(MetricName.build("one.two.three")); } @Test @SuppressWarnings("NullArgumentToVariableArgMethod") - public void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() { + void elidesNullValuesFromNamesWhenOnlyOneNullPassedIn() { assertThat(name("one", (String) null)) .isEqualTo(MetricName.build("one")); } @Test - public void elidesNullValuesFromNamesWhenManyNullsPassedIn() { + void elidesNullValuesFromNamesWhenManyNullsPassedIn() { assertThat(name("one", null, null)) .isEqualTo(MetricName.build("one")); } @Test - public void elidesNullValuesFromNamesWhenNullAndNotNullPassedIn() { + void elidesNullValuesFromNamesWhenNullAndNotNullPassedIn() { assertThat(name("one", null, "three")) .isEqualTo(MetricName.build("one.three")); } @Test - public void elidesEmptyStringsFromNames() { + void elidesEmptyStringsFromNames() { assertThat(name("one", "", "three")) .isEqualTo(MetricName.build("one.three")); } @Test - public void concatenatesClassNamesWithStringsToFormADottedName() { + void concatenatesClassNamesWithStringsToFormADottedName() { assertThat(name(MetricRegistryTest.class, "one", "two")) .isEqualTo(MetricName.build("io.dropwizard.metrics5.MetricRegistryTest.one.two")); } @Test - public void concatenatesClassesWithoutCanonicalNamesWithStrings() { + void concatenatesClassesWithoutCanonicalNamesWithStrings() { final Gauge g = () -> null; assertThat(name(g.getClass(), "one", "two")) @@ -497,7 +497,7 @@ public void concatenatesClassesWithoutCanonicalNamesWithStrings() { } @Test - public void removesMetricsMatchingAFilter() { + void removesMetricsMatchingAFilter() { final MetricName timer1 = MetricName.build("timer-1"); final MetricName timer2 = MetricName.build("timer-2"); final MetricName histogram1 = MetricName.build("histogram-1"); @@ -521,7 +521,7 @@ public void removesMetricsMatchingAFilter() { } @Test - public void addingChildMetricAfterRegister() { + void addingChildMetricAfterRegister() { MetricRegistry parent = new MetricRegistry(); MetricRegistry child = new MetricRegistry(); @@ -537,7 +537,7 @@ public void addingChildMetricAfterRegister() { } @Test - public void addingMultipleChildMetricsAfterRegister() { + void addingMultipleChildMetricsAfterRegister() { MetricRegistry parent = new MetricRegistry(); MetricRegistry child = new MetricRegistry(); @@ -555,7 +555,7 @@ public void addingMultipleChildMetricsAfterRegister() { } @Test - public void addingDeepChildMetricsAfterRegister() { + void addingDeepChildMetricsAfterRegister() { MetricRegistry parent = new MetricRegistry(); MetricRegistry child = new MetricRegistry(); MetricRegistry deepChild = new MetricRegistry(); @@ -584,7 +584,7 @@ public void addingDeepChildMetricsAfterRegister() { } @Test - public void removingChildMetricAfterRegister() { + void removingChildMetricAfterRegister() { MetricRegistry parent = new MetricRegistry(); MetricRegistry child = new MetricRegistry(); @@ -604,7 +604,7 @@ public void removingChildMetricAfterRegister() { } @Test - public void removingMultipleChildMetricsAfterRegister() { + void removingMultipleChildMetricsAfterRegister() { MetricRegistry parent = new MetricRegistry(); MetricRegistry child = new MetricRegistry(); @@ -627,7 +627,7 @@ public void removingMultipleChildMetricsAfterRegister() { } @Test - public void removingDeepChildMetricsAfterRegister() { + void removingDeepChildMetricsAfterRegister() { MetricRegistry parent = new MetricRegistry(); MetricRegistry child = new MetricRegistry(); MetricRegistry deepChild = new MetricRegistry(); @@ -659,21 +659,21 @@ public void removingDeepChildMetricsAfterRegister() { } @Test - public void registerNullMetric() { + void registerNullMetric() { MetricRegistry registry = new MetricRegistry(); assertThatThrownBy(() -> registry.register("any_name", null)) .hasMessage("metric == null"); } @Test - public void infersGaugeType() { + void infersGaugeType() { Gauge gauge = registry.registerGauge(GAUGE, () -> 10_000_000_000L); assertThat(gauge.getValue()).isEqualTo(10_000_000_000L); } @Test - public void registersGaugeAsLambda() { + void registersGaugeAsLambda() { registry.registerGauge(GAUGE, () -> 3.14); assertThat(registry.gauge(GAUGE).getValue()).isEqualTo(3.14); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java index 58119033bc..53145acb24 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/NoopMetricRegistryTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -13,7 +13,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -public class NoopMetricRegistryTest { +class NoopMetricRegistryTest { private static final MetricName METRIC_THING = MetricName.build("thing"); private final MetricRegistryListener listener = mock(MetricRegistryListener.class); @@ -24,20 +24,20 @@ public class NoopMetricRegistryTest { private final Meter meter = mock(Meter.class); private final Timer timer = mock(Timer.class); - @Before - public void setUp() { + @BeforeEach + void setUp() { registry.addListener(listener); } @Test - public void registeringAGaugeTriggersNoNotification() { + void registeringAGaugeTriggersNoNotification() { assertThat(registry.register(METRIC_THING, gauge)).isEqualTo(gauge); verify(listener, never()).onGaugeAdded(METRIC_THING, gauge); } @Test - public void removingAGaugeTriggersNoNotification() { + void removingAGaugeTriggersNoNotification() { registry.register(METRIC_THING, gauge); assertThat(registry.remove(METRIC_THING)).isFalse(); @@ -46,14 +46,14 @@ public void removingAGaugeTriggersNoNotification() { } @Test - public void registeringACounterTriggersNoNotification() { + void registeringACounterTriggersNoNotification() { assertThat(registry.register(METRIC_THING, counter)).isEqualTo(counter); verify(listener, never()).onCounterAdded(METRIC_THING, counter); } @Test - public void accessingACounterRegistersAndReusesTheCounter() { + void accessingACounterRegistersAndReusesTheCounter() { final Counter counter1 = registry.counter(METRIC_THING); final Counter counter2 = registry.counter(METRIC_THING); @@ -65,7 +65,7 @@ public void accessingACounterRegistersAndReusesTheCounter() { } @Test - public void accessingACustomCounterRegistersAndReusesTheCounter() { + void accessingACustomCounterRegistersAndReusesTheCounter() { final MetricRegistry.MetricSupplier supplier = () -> counter; final Counter counter1 = registry.counter(METRIC_THING, supplier); final Counter counter2 = registry.counter(METRIC_THING, supplier); @@ -79,7 +79,7 @@ public void accessingACustomCounterRegistersAndReusesTheCounter() { @Test - public void removingACounterTriggersNoNotification() { + void removingACounterTriggersNoNotification() { registry.register(METRIC_THING, counter); assertThat(registry.remove(METRIC_THING)).isFalse(); @@ -88,14 +88,14 @@ public void removingACounterTriggersNoNotification() { } @Test - public void registeringAHistogramTriggersNoNotification() { + void registeringAHistogramTriggersNoNotification() { assertThat(registry.register(METRIC_THING, histogram)).isEqualTo(histogram); verify(listener, never()).onHistogramAdded(METRIC_THING, histogram); } @Test - public void accessingAHistogramRegistersAndReusesIt() { + void accessingAHistogramRegistersAndReusesIt() { final Histogram histogram1 = registry.histogram(METRIC_THING); final Histogram histogram2 = registry.histogram(METRIC_THING); @@ -107,7 +107,7 @@ public void accessingAHistogramRegistersAndReusesIt() { } @Test - public void accessingACustomHistogramRegistersAndReusesIt() { + void accessingACustomHistogramRegistersAndReusesIt() { final MetricRegistry.MetricSupplier supplier = () -> histogram; final Histogram histogram1 = registry.histogram(METRIC_THING, supplier); final Histogram histogram2 = registry.histogram(METRIC_THING, supplier); @@ -120,7 +120,7 @@ public void accessingACustomHistogramRegistersAndReusesIt() { } @Test - public void removingAHistogramTriggersNoNotification() { + void removingAHistogramTriggersNoNotification() { registry.register(METRIC_THING, histogram); assertThat(registry.remove(METRIC_THING)).isFalse(); @@ -129,14 +129,14 @@ public void removingAHistogramTriggersNoNotification() { } @Test - public void registeringAMeterTriggersNoNotification() { + void registeringAMeterTriggersNoNotification() { assertThat(registry.register(METRIC_THING, meter)).isEqualTo(meter); verify(listener, never()).onMeterAdded(METRIC_THING, meter); } @Test - public void accessingAMeterRegistersAndReusesIt() { + void accessingAMeterRegistersAndReusesIt() { final Meter meter1 = registry.meter(METRIC_THING); final Meter meter2 = registry.meter(METRIC_THING); @@ -148,7 +148,7 @@ public void accessingAMeterRegistersAndReusesIt() { } @Test - public void accessingACustomMeterRegistersAndReusesIt() { + void accessingACustomMeterRegistersAndReusesIt() { final MetricRegistry.MetricSupplier supplier = () -> meter; final Meter meter1 = registry.meter(METRIC_THING, supplier); final Meter meter2 = registry.meter(METRIC_THING, supplier); @@ -161,7 +161,7 @@ public void accessingACustomMeterRegistersAndReusesIt() { } @Test - public void removingAMeterTriggersNoNotification() { + void removingAMeterTriggersNoNotification() { registry.register(METRIC_THING, meter); assertThat(registry.remove(METRIC_THING)).isFalse(); @@ -170,14 +170,14 @@ public void removingAMeterTriggersNoNotification() { } @Test - public void registeringATimerTriggersNoNotification() { + void registeringATimerTriggersNoNotification() { assertThat(registry.register(METRIC_THING, timer)).isEqualTo(timer); verify(listener, never()).onTimerAdded(METRIC_THING, timer); } @Test - public void accessingATimerRegistersAndReusesIt() { + void accessingATimerRegistersAndReusesIt() { final Timer timer1 = registry.timer(METRIC_THING); final Timer timer2 = registry.timer(METRIC_THING); @@ -189,7 +189,7 @@ public void accessingATimerRegistersAndReusesIt() { } @Test - public void accessingACustomTimerRegistersAndReusesIt() { + void accessingACustomTimerRegistersAndReusesIt() { final MetricRegistry.MetricSupplier supplier = () -> timer; final Timer timer1 = registry.timer(METRIC_THING, supplier); final Timer timer2 = registry.timer(METRIC_THING, supplier); @@ -203,7 +203,7 @@ public void accessingACustomTimerRegistersAndReusesIt() { @Test - public void removingATimerTriggersNoNotification() { + void removingATimerTriggersNoNotification() { registry.register(METRIC_THING, timer); assertThat(registry.remove(METRIC_THING)).isFalse(); @@ -212,7 +212,7 @@ public void removingATimerTriggersNoNotification() { } @Test - public void accessingAGaugeRegistersAndReusesIt() { + void accessingAGaugeRegistersAndReusesIt() { final Gauge gauge1 = registry.gauge(METRIC_THING); final Gauge gauge2 = registry.gauge(METRIC_THING); @@ -225,7 +225,7 @@ public void accessingAGaugeRegistersAndReusesIt() { @Test @SuppressWarnings("rawtypes") - public void accessingACustomGaugeRegistersAndReusesIt() { + void accessingACustomGaugeRegistersAndReusesIt() { final MetricRegistry.MetricSupplier> supplier = () -> gauge; final Gauge gauge1 = registry.gauge(METRIC_THING, supplier); final Gauge gauge2 = registry.gauge(METRIC_THING, supplier); @@ -239,7 +239,7 @@ public void accessingACustomGaugeRegistersAndReusesIt() { @Test - public void addingAListenerWithExistingMetricsDoesNotNotify() { + void addingAListenerWithExistingMetricsDoesNotNotify() { registry.register(MetricName.build("gauge"), gauge); registry.register(MetricName.build("counter"), counter); registry.register(MetricName.build("histogram"), histogram); @@ -257,7 +257,7 @@ public void addingAListenerWithExistingMetricsDoesNotNotify() { } @Test - public void aRemovedListenerDoesNotReceiveUpdates() { + void aRemovedListenerDoesNotReceiveUpdates() { registry.register(MetricName.build("gauge"), gauge); registry.removeListener(listener); registry.register("gauge2", gauge); @@ -266,42 +266,42 @@ public void aRemovedListenerDoesNotReceiveUpdates() { } @Test - public void hasAMapOfRegisteredGauges() { + void hasAMapOfRegisteredGauges() { registry.register(MetricName.build("gauge"), gauge); assertThat(registry.getGauges()).isEmpty(); } @Test - public void hasAMapOfRegisteredCounters() { + void hasAMapOfRegisteredCounters() { registry.register(MetricName.build("counter"), counter); assertThat(registry.getCounters()).isEmpty(); } @Test - public void hasAMapOfRegisteredHistograms() { + void hasAMapOfRegisteredHistograms() { registry.register(MetricName.build("histogram"), histogram); assertThat(registry.getHistograms()).isEmpty(); } @Test - public void hasAMapOfRegisteredMeters() { + void hasAMapOfRegisteredMeters() { registry.register(MetricName.build("meter"), meter); assertThat(registry.getMeters()).isEmpty(); } @Test - public void hasAMapOfRegisteredTimers() { + void hasAMapOfRegisteredTimers() { registry.register(MetricName.build("timer"), timer); assertThat(registry.getTimers()).isEmpty(); } @Test - public void hasASetOfRegisteredMetricNames() { + void hasASetOfRegisteredMetricNames() { registry.register(MetricName.build("gauge"), gauge); registry.register(MetricName.build("counter"), counter); registry.register(MetricName.build("histogram"), histogram); @@ -312,7 +312,7 @@ public void hasASetOfRegisteredMetricNames() { } @Test - public void doesNotRegisterMultipleMetrics() { + void doesNotRegisterMultipleMetrics() { final MetricSet metrics = () -> { final Map m = new HashMap<>(); m.put(MetricName.build("gauge"), gauge); @@ -326,7 +326,7 @@ public void doesNotRegisterMultipleMetrics() { } @Test - public void doesNotRegisterMultipleMetricsWithAPrefix() { + void doesNotRegisterMultipleMetricsWithAPrefix() { final MetricSet metrics = () -> { final Map m = new HashMap<>(); m.put(MetricName.build("gauge"), gauge); @@ -340,7 +340,7 @@ public void doesNotRegisterMultipleMetricsWithAPrefix() { } @Test - public void doesNotRegisterRecursiveMetricSets() { + void doesNotRegisterRecursiveMetricSets() { final MetricSet inner = () -> { final Map m = new HashMap<>(); m.put(MetricName.build("gauge"), gauge); @@ -360,7 +360,7 @@ public void doesNotRegisterRecursiveMetricSets() { } @Test - public void doesNotRegisterMetricsFromAnotherRegistry() { + void doesNotRegisterMetricsFromAnotherRegistry() { MetricRegistry other = new MetricRegistry(); other.register(MetricName.build("gauge"), gauge); registry.register("nested", other); @@ -368,7 +368,7 @@ public void doesNotRegisterMetricsFromAnotherRegistry() { } @Test - public void removesMetricsMatchingAFilter() { + void removesMetricsMatchingAFilter() { registry.timer("timer-1"); registry.timer("timer-2"); registry.histogram("histogram-1"); @@ -384,7 +384,7 @@ public void removesMetricsMatchingAFilter() { } @Test - public void addingChildMetricAfterRegister() { + void addingChildMetricAfterRegister() { MetricRegistry parent = new NoopMetricRegistry(); MetricRegistry child = new MetricRegistry(); @@ -396,7 +396,7 @@ public void addingChildMetricAfterRegister() { } @Test - public void addingMultipleChildMetricsAfterRegister() { + void addingMultipleChildMetricsAfterRegister() { MetricRegistry parent = new NoopMetricRegistry(); MetricRegistry child = new MetricRegistry(); @@ -410,7 +410,7 @@ public void addingMultipleChildMetricsAfterRegister() { } @Test - public void addingDeepChildMetricsAfterRegister() { + void addingDeepChildMetricsAfterRegister() { MetricRegistry parent = new NoopMetricRegistry(); MetricRegistry child = new MetricRegistry(); MetricRegistry deepChild = new MetricRegistry(); @@ -431,7 +431,7 @@ public void addingDeepChildMetricsAfterRegister() { } @Test - public void removingChildMetricAfterRegister() { + void removingChildMetricAfterRegister() { MetricRegistry parent = new NoopMetricRegistry(); MetricRegistry child = new MetricRegistry(); @@ -446,7 +446,7 @@ public void removingChildMetricAfterRegister() { } @Test - public void removingMultipleChildMetricsAfterRegister() { + void removingMultipleChildMetricsAfterRegister() { MetricRegistry parent = new NoopMetricRegistry(); MetricRegistry child = new MetricRegistry(); @@ -464,7 +464,7 @@ public void removingMultipleChildMetricsAfterRegister() { } @Test - public void removingDeepChildMetricsAfterRegister() { + void removingDeepChildMetricsAfterRegister() { MetricRegistry parent = new NoopMetricRegistry(); MetricRegistry child = new MetricRegistry(); MetricRegistry deepChild = new MetricRegistry(); @@ -488,7 +488,7 @@ public void removingDeepChildMetricsAfterRegister() { } @Test - public void registerNullMetric() { + void registerNullMetric() { MetricRegistry registry = new NoopMetricRegistry(); assertThatNullPointerException() .isThrownBy(() -> registry.register("any_name", null)) diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java index d550e224f9..6dc13e0f51 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/RatioGaugeTest.java @@ -1,12 +1,12 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class RatioGaugeTest { +class RatioGaugeTest { @Test - public void ratiosAreHumanReadable() { + void ratiosAreHumanReadable() { final RatioGauge.Ratio ratio = RatioGauge.Ratio.of(100, 200); assertThat(ratio.toString()) @@ -14,7 +14,7 @@ public void ratiosAreHumanReadable() { } @Test - public void calculatesTheRatioOfTheNumeratorToTheDenominator() { + void calculatesTheRatioOfTheNumeratorToTheDenominator() { final RatioGauge regular = new RatioGauge() { @Override protected Ratio getRatio() { @@ -27,7 +27,7 @@ protected Ratio getRatio() { } @Test - public void handlesDivideByZeroIssues() { + void handlesDivideByZeroIssues() { final RatioGauge divByZero = new RatioGauge() { @Override protected Ratio getRatio() { @@ -40,7 +40,7 @@ protected Ratio getRatio() { } @Test - public void handlesInfiniteDenominators() { + void handlesInfiniteDenominators() { final RatioGauge infinite = new RatioGauge() { @Override protected Ratio getRatio() { @@ -53,7 +53,7 @@ protected Ratio getRatio() { } @Test - public void handlesNaNDenominators() { + void handlesNaNDenominators() { final RatioGauge nan = new RatioGauge() { @Override protected Ratio getRatio() { diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java index 6f809f3243..ab80830232 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/ScheduledReporterTest.java @@ -1,9 +1,8 @@ package io.dropwizard.metrics5; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.SortedMap; import java.util.TreeMap; @@ -15,9 +14,11 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +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 static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; @@ -25,7 +26,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class ScheduledReporterTest { +class ScheduledReporterTest { private final Gauge gauge = () -> ""; private final Counter counter = mock(Counter.class); private final Histogram histogram = mock(Histogram.class); @@ -46,11 +47,11 @@ public class ScheduledReporterTest { private final ScheduledReporter reporterWithCustomMockExecutor = new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, mockExecutor); private final ScheduledReporter reporterWithCustomExecutor = new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, customExecutor); private final DummyReporter reporterWithExternallyManagedExecutor = new DummyReporter(registry, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, externalExecutor, false); - private final ScheduledReporter[] reporters = new ScheduledReporter[] {reporter, reporterWithCustomExecutor, reporterWithExternallyManagedExecutor}; + private final ScheduledReporter[] reporters = new ScheduledReporter[]{reporter, reporterWithCustomExecutor, reporterWithExternallyManagedExecutor}; - @Before + @BeforeEach @SuppressWarnings("unchecked") - public void setUp() throws Exception { + void setUp() throws Exception { registry.register("gauge", gauge); registry.register("counter", counter); registry.register("histogram", histogram); @@ -58,8 +59,8 @@ public void setUp() throws Exception { registry.register("timer", timer); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { customExecutor.shutdown(); externalExecutor.shutdown(); reporter.stop(); @@ -67,14 +68,14 @@ public void tearDown() throws Exception { } @Test - public void createWithNullMetricRegistry() { + void createWithNullMetricRegistry() { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); DummyReporter r = null; try { r = new DummyReporter(null, "example", MetricFilter.ALL, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, executor); - Assert.fail("NullPointerException must be thrown !!!"); + fail("NullPointerException must be thrown !!!"); } catch (NullPointerException e) { - Assert.assertEquals("registry == null", e.getMessage()); + assertEquals("registry == null", e.getMessage()); } finally { if (r != null) { r.close(); @@ -83,7 +84,7 @@ public void createWithNullMetricRegistry() { } @Test - public void pollsPeriodically() throws Exception { + void pollsPeriodically() throws Exception { CountDownLatch latch = new CountDownLatch(2); reporter.start(100, 100, TimeUnit.MILLISECONDS, () -> { if (latch.getCount() > 0) { @@ -103,25 +104,25 @@ public void pollsPeriodically() throws Exception { } @Test - public void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { + void shouldUsePeriodAsInitialDelayIfNotSpecifiedOtherwise() throws Exception { reporterWithCustomMockExecutor.start(200, TimeUnit.MILLISECONDS); verify(mockExecutor, times(1)).scheduleWithFixedDelay( - any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS) + any(Runnable.class), eq(200L), eq(200L), eq(TimeUnit.MILLISECONDS) ); } @Test - public void shouldStartWithSpecifiedInitialDelay() throws Exception { + void shouldStartWithSpecifiedInitialDelay() throws Exception { reporterWithCustomMockExecutor.start(350, 100, TimeUnit.MILLISECONDS); verify(mockExecutor).scheduleWithFixedDelay( - any(Runnable.class), eq(350L), eq(100L), eq(TimeUnit.MILLISECONDS) + any(Runnable.class), eq(350L), eq(100L), eq(TimeUnit.MILLISECONDS) ); } @Test - public void shouldAutoCreateExecutorWhenItNull() throws Exception { + void shouldAutoCreateExecutorWhenItNull() throws Exception { CountDownLatch latch = new CountDownLatch(2); reporterWithNullExecutor.start(100, 100, TimeUnit.MILLISECONDS, () -> { if (latch.getCount() > 0) { @@ -139,33 +140,39 @@ public void shouldAutoCreateExecutorWhenItNull() throws Exception { ); } - @Test(expected = IllegalArgumentException.class) - public void shouldDisallowToStartReportingMultiple() throws Exception { - reporter.start(200, TimeUnit.MILLISECONDS); - reporter.start(200, TimeUnit.MILLISECONDS); + @Test + void shouldDisallowToStartReportingMultiple() throws Exception { + assertThrows(IllegalArgumentException.class, () -> { + reporter.start(200, TimeUnit.MILLISECONDS); + reporter.start(200, TimeUnit.MILLISECONDS); + }); } - @Test(expected = IllegalArgumentException.class) - public void shouldDisallowToStartReportingMultipleTimesOnCustomExecutor() throws Exception { - reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); - reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); + @Test + void shouldDisallowToStartReportingMultipleTimesOnCustomExecutor() throws Exception { + assertThrows(IllegalArgumentException.class, () -> { + reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); + reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); + }); } - @Test(expected = IllegalArgumentException.class) - public void shouldDisallowToStartReportingMultipleTimesOnExternallyManagedExecutor() throws Exception { - reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); - reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); + @Test + void shouldDisallowToStartReportingMultipleTimesOnExternallyManagedExecutor() throws Exception { + assertThrows(IllegalArgumentException.class, () -> { + reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); + reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); + }); } @Test - public void shouldNotFailOnStopIfReporterWasNotStared() { + void shouldNotFailOnStopIfReporterWasNotStared() { for (ScheduledReporter reporter : reporters) { reporter.stop(); } } @Test - public void shouldNotFailWhenStoppingMultipleTimes() { + void shouldNotFailWhenStoppingMultipleTimes() { for (ScheduledReporter reporter : reporters) { reporter.start(200, TimeUnit.MILLISECONDS); reporter.stop(); @@ -175,14 +182,14 @@ public void shouldNotFailWhenStoppingMultipleTimes() { } @Test - public void shouldShutdownExecutorOnStopByDefault() { + void shouldShutdownExecutorOnStopByDefault() { reporterWithCustomExecutor.start(200, TimeUnit.MILLISECONDS); reporterWithCustomExecutor.stop(); assertTrue(customExecutor.isTerminated()); } @Test - public void shouldNotShutdownExternallyManagedExecutorOnStop() { + void shouldNotShutdownExternallyManagedExecutorOnStop() { reporterWithExternallyManagedExecutor.start(200, TimeUnit.MILLISECONDS); reporterWithExternallyManagedExecutor.stop(); assertFalse(mockExecutor.isTerminated()); @@ -190,7 +197,7 @@ public void shouldNotShutdownExternallyManagedExecutorOnStop() { } @Test - public void shouldCancelScheduledFutureWhenStoppingWithExternallyManagedExecutor() throws InterruptedException, ExecutionException, TimeoutException { + void shouldCancelScheduledFutureWhenStoppingWithExternallyManagedExecutor() throws InterruptedException, ExecutionException, TimeoutException { // configure very frequency rate of execution reporterWithExternallyManagedExecutor.start(1, TimeUnit.MILLISECONDS); reporterWithExternallyManagedExecutor.stop(); @@ -203,12 +210,12 @@ public void shouldCancelScheduledFutureWhenStoppingWithExternallyManagedExecutor } @Test - public void shouldConvertDurationToMillisecondsPrecisely() { + void shouldConvertDurationToMillisecondsPrecisely() { assertEquals(2.0E-5, reporter.convertDuration(20), 0.0); } @Test - public void shouldReportMetricsOnShutdown() throws Exception { + void shouldReportMetricsOnShutdown() throws Exception { CountDownLatch latch = new CountDownLatch(1); reporterWithNullExecutor.start(0, 10, TimeUnit.SECONDS, () -> { if (latch.getCount() > 0) { @@ -229,7 +236,7 @@ public void shouldReportMetricsOnShutdown() throws Exception { } @Test - public void shouldRescheduleAfterReportFinish() throws Exception { + void shouldRescheduleAfterReportFinish() throws Exception { // the first report is triggered at T + 0.1 seconds and takes 0.8 seconds // after the first report finishes at T + 0.9 seconds the next report is scheduled to run at T + 1.4 seconds reporter.start(100, 500, TimeUnit.MILLISECONDS, () -> { diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java index e6e90c4c52..02e0785105 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SharedMetricRegistriesTest.java @@ -1,26 +1,24 @@ package io.dropwizard.metrics5; -import org.junit.Before; -import org.junit.Test; -import org.junit.Rule; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.atomic.AtomicReference; -public class SharedMetricRegistriesTest { - @Rule - public ExpectedException exception = ExpectedException.none(); +class SharedMetricRegistriesTest { - @Before - public void setUp() { + @BeforeEach + void setUp() { SharedMetricRegistries.setDefaultRegistryName(new AtomicReference<>()); SharedMetricRegistries.clear(); } @Test - public void memorizesRegistriesByName() { + void memorizesRegistriesByName() { final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); final MetricRegistry two = SharedMetricRegistries.getOrCreate("one"); @@ -29,7 +27,7 @@ public void memorizesRegistriesByName() { } @Test - public void hasASetOfNames() { + void hasASetOfNames() { SharedMetricRegistries.getOrCreate("one"); assertThat(SharedMetricRegistries.names()) @@ -37,7 +35,7 @@ public void hasASetOfNames() { } @Test - public void removesRegistries() { + void removesRegistries() { final MetricRegistry one = SharedMetricRegistries.getOrCreate("one"); SharedMetricRegistries.remove("one"); @@ -50,7 +48,7 @@ public void removesRegistries() { } @Test - public void clearsRegistries() { + void clearsRegistries() { SharedMetricRegistries.getOrCreate("one"); SharedMetricRegistries.getOrCreate("two"); @@ -61,14 +59,15 @@ public void clearsRegistries() { } @Test - public void errorsWhenDefaultUnset() { - exception.expect(IllegalStateException.class); - exception.expectMessage("Default registry name has not been set."); - SharedMetricRegistries.getDefault(); + void errorsWhenDefaultUnset() { + Throwable exception = assertThrows(IllegalStateException.class, () -> { + SharedMetricRegistries.getDefault(); + }); + assertTrue(exception.getMessage().contains("Default registry name has not been set.")); } @Test - public void createsDefaultRegistries() { + void createsDefaultRegistries() { final String defaultName = "default"; final MetricRegistry registry = SharedMetricRegistries.setDefault(defaultName); assertThat(registry).isNotNull(); @@ -77,15 +76,16 @@ public void createsDefaultRegistries() { } @Test - public void errorsWhenDefaultAlreadySet() { - SharedMetricRegistries.setDefault("foobah"); - exception.expect(IllegalStateException.class); - exception.expectMessage("Default metric registry name is already set."); - SharedMetricRegistries.setDefault("borg"); + void errorsWhenDefaultAlreadySet() { + Throwable exception = assertThrows(IllegalStateException.class, () -> { + SharedMetricRegistries.setDefault("foobah"); + SharedMetricRegistries.setDefault("borg"); + }); + assertTrue(exception.getMessage().contains("Default metric registry name is already set.")); } @Test - public void setsDefaultExistingRegistries() { + void setsDefaultExistingRegistries() { final String defaultName = "default"; final MetricRegistry registry = new MetricRegistry(); assertThat(SharedMetricRegistries.setDefault(defaultName, registry)).isEqualTo(registry); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java index eb9fdce7f3..026175d980 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SimpleSettableGaugeTest.java @@ -1,21 +1,21 @@ package io.dropwizard.metrics5; import io.dropwizard.metrics5.DefaultSettableGauge; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class SimpleSettableGaugeTest { +class SimpleSettableGaugeTest { @Test - public void defaultValue() { + void defaultValue() { DefaultSettableGauge settable = new DefaultSettableGauge<>(1); assertThat(settable.getValue()).isEqualTo(1); } @Test - public void setValueAndThenGetValue() { + void setValueAndThenGetValue() { DefaultSettableGauge settable = new DefaultSettableGauge<>("default"); settable.setValue("first"); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java index bbd6dd8690..e37434459f 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/Slf4jReporterTest.java @@ -1,6 +1,6 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.Marker; @@ -21,7 +21,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class Slf4jReporterTest { +class Slf4jReporterTest { private final Logger logger = mock(Logger.class); private final Marker marker = mock(Marker.class); @@ -63,12 +63,12 @@ private Slf4jReporter errorReporter() { } @Test - public void reportsGaugeValuesAtErrorDefault() { + void reportsGaugeValuesAtErrorDefault() { reportsGaugeValuesAtError(); } @Test - public void reportsGaugeValuesAtErrorAllDisabled() { + void reportsGaugeValuesAtErrorAllDisabled() { disabledMetricAttributes = EnumSet.allOf(MetricAttribute.class); // has no effect reportsGaugeValuesAtError(); } @@ -148,12 +148,12 @@ private Counter counter() { } @Test - public void reportsCounterValuesAtErrorDefault() { + void reportsCounterValuesAtErrorDefault() { reportsCounterValuesAtError(); } @Test - public void reportsCounterValuesAtErrorAllDisabled() { + void reportsCounterValuesAtErrorAllDisabled() { disabledMetricAttributes = EnumSet.allOf(MetricAttribute.class); // has no effect reportsCounterValuesAtError(); } @@ -172,13 +172,13 @@ private void reportsCounterValuesAtError() { } @Test - public void reportsHistogramValuesAtErrorDefault() { + void reportsHistogramValuesAtErrorDefault() { reportsHistogramValuesAtError("type=HISTOGRAM, name=test.histogram, count=1, min=4, " + "max=2, mean=3.0, stddev=5.0, p50=6.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); } @Test - public void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { + void reportsHistogramValuesAtErrorWithDisabledMetricAttributes() { disabledMetricAttributes = EnumSet.of(COUNT, MIN, P50); reportsHistogramValuesAtError("type=HISTOGRAM, name=test.histogram, max=2, mean=3.0, " + "stddev=5.0, p75=7.0, p95=8.0, p98=9.0, p99=10.0, p999=11.0"); @@ -198,13 +198,13 @@ private void reportsHistogramValuesAtError(final String expectedLog) { } @Test - public void reportsMeterValuesAtErrorDefault() { + void reportsMeterValuesAtErrorDefault() { reportsMeterValuesAtError("type=METER, name=test.meter, count=1, m1_rate=3.0, m5_rate=4.0, " + "m15_rate=5.0, mean_rate=2.0, rate_unit=events/second"); } @Test - public void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { + void reportsMeterValuesAtErrorWithDisabledMetricAttributes() { disabledMetricAttributes = EnumSet.of(MIN, P50, M1_RATE); reportsMeterValuesAtError("type=METER, name=test.meter, count=1, m5_rate=4.0, m15_rate=5.0, " + "mean_rate=2.0, rate_unit=events/second"); @@ -225,7 +225,7 @@ private void reportsMeterValuesAtError(final String expectedLog) { @Test - public void reportsTimerValuesAtErrorDefault() { + void reportsTimerValuesAtErrorDefault() { reportsTimerValuesAtError("type=TIMER, name=test.another.timer, count=1, min=300.0, max=100.0, " + "mean=200.0, stddev=400.0, p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, p999=1000.0, " + "m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, mean_rate=2.0, rate_unit=events/second, " + @@ -233,7 +233,7 @@ public void reportsTimerValuesAtErrorDefault() { } @Test - public void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { + void reportsTimerValuesAtErrorWithDisabledMetricAttributes() { disabledMetricAttributes = EnumSet.of(MIN, STDDEV, P999, MEAN_RATE); reportsTimerValuesAtError("type=TIMER, name=test.another.timer, count=1, max=100.0, mean=200.0, " + "p50=500.0, p75=600.0, p95=700.0, p98=800.0, p99=900.0, m1_rate=3.0, m5_rate=4.0, m15_rate=5.0, " + @@ -255,7 +255,7 @@ private void reportsTimerValuesAtError(final String expectedLog) { } @Test - public void reportsGaugeValuesDefault() { + void reportsGaugeValuesDefault() { when(logger.isInfoEnabled(marker)).thenReturn(true); infoReporter().report(map("gauge", () -> "value"), map(), @@ -268,7 +268,7 @@ public void reportsGaugeValuesDefault() { @Test - public void reportsCounterValuesDefault() { + void reportsCounterValuesDefault() { final Counter counter = counter(); when(logger.isInfoEnabled(marker)).thenReturn(true); @@ -282,7 +282,7 @@ public void reportsCounterValuesDefault() { } @Test - public void reportsHistogramValuesDefault() { + void reportsHistogramValuesDefault() { final Histogram histogram = histogram(); when(logger.isInfoEnabled(marker)).thenReturn(true); @@ -297,7 +297,7 @@ public void reportsHistogramValuesDefault() { } @Test - public void reportsMeterValuesDefault() { + void reportsMeterValuesDefault() { final Meter meter = meter(); when(logger.isInfoEnabled(marker)).thenReturn(true); @@ -312,7 +312,7 @@ public void reportsMeterValuesDefault() { } @Test - public void reportsTimerValuesDefault() { + void reportsTimerValuesDefault() { final Timer timer = timer(); when(logger.isInfoEnabled(marker)).thenReturn(true); @@ -329,7 +329,7 @@ public void reportsTimerValuesDefault() { @Test - public void reportsAllMetricsDefault() { + void reportsAllMetricsDefault() { when(logger.isInfoEnabled(marker)).thenReturn(true); infoReporter().report(map("test.gauge", () -> "value"), diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java index 9153d568f8..077b6ffa2f 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowArrayReservoirTest.java @@ -5,7 +5,7 @@ import static org.mockito.Mockito.when; import static java.util.concurrent.TimeUnit.NANOSECONDS; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Random; @@ -13,10 +13,10 @@ import java.util.concurrent.atomic.AtomicLong; @SuppressWarnings("Duplicates") -public class SlidingTimeWindowArrayReservoirTest { +class SlidingTimeWindowArrayReservoirTest { @Test - public void storesMeasurementsWithDuplicateTicks() { + void storesMeasurementsWithDuplicateTicks() { final Clock clock = mock(Clock.class); final SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); @@ -30,7 +30,7 @@ public void storesMeasurementsWithDuplicateTicks() { } @Test - public void boundsMeasurementsToATimeWindow() { + void boundsMeasurementsToATimeWindow() { final Clock clock = mock(Clock.class); final SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(10, NANOSECONDS, clock); @@ -54,7 +54,7 @@ public void boundsMeasurementsToATimeWindow() { } @Test - public void comparisonResultsTest() { + void comparisonResultsTest() { int cycles = 1000000; long time = (Long.MAX_VALUE / 256) - (long) (cycles * 0.5); ManualClock manualClock = new ManualClock(); @@ -81,7 +81,7 @@ public void comparisonResultsTest() { } @Test - public void testGetTickOverflow() { + void testGetTickOverflow() { final Random random = new Random(0); final int window = 128; AtomicLong counter = new AtomicLong(0L); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java index 4855257ea3..2504460584 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowMovingAveragesTest.java @@ -8,24 +8,24 @@ import java.time.Instant; import io.dropwizard.metrics5.SlidingTimeWindowMovingAverages; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SlidingTimeWindowMovingAveragesTest { +class SlidingTimeWindowMovingAveragesTest { private ManualClock clock; private SlidingTimeWindowMovingAverages movingAverages; private Meter meter; - @Before - public void init() { + @BeforeEach + void init() { clock = new ManualClock(); movingAverages = new SlidingTimeWindowMovingAverages(clock); meter = new Meter(movingAverages, clock); } @Test - public void normalizeIndex() { + void normalizeIndex() { SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(); @@ -42,7 +42,7 @@ public void normalizeIndex() { } @Test - public void calculateIndexOfTick() { + void calculateIndexOfTick() { SlidingTimeWindowMovingAverages stwm = new SlidingTimeWindowMovingAverages(clock); @@ -51,7 +51,7 @@ public void calculateIndexOfTick() { } @Test - public void mark_max_without_cleanup() { + void mark_max_without_cleanup() { int markCount = NUMBER_OF_BUCKETS; @@ -72,7 +72,7 @@ public void mark_max_without_cleanup() { } @Test - public void mark_first_cleanup() { + void mark_first_cleanup() { int markCount = NUMBER_OF_BUCKETS + 1; @@ -93,7 +93,7 @@ public void mark_first_cleanup() { } @Test - public void mark_10_values() { + void mark_10_values() { // compensate the first addSeconds in the loop; first tick should be at zero clock.addSeconds(-1); @@ -110,7 +110,7 @@ public void mark_10_values() { } @Test - public void mark_1000_values() { + void mark_1000_values() { for (int i = 0; i < 1000; i++) { clock.addSeconds(1); @@ -124,7 +124,7 @@ public void mark_1000_values() { } @Test - public void cleanup_pause_shorter_than_window() { + void cleanup_pause_shorter_than_window() { meter.mark(10); @@ -136,7 +136,7 @@ public void cleanup_pause_shorter_than_window() { } @Test - public void cleanup_window_wrap_around() { + void cleanup_window_wrap_around() { // mark at 14:40 minutes of the 15 minute window... clock.addSeconds(880); @@ -156,7 +156,7 @@ public void cleanup_window_wrap_around() { } @Test - public void cleanup_pause_longer_than_two_windows() { + void cleanup_pause_longer_than_two_windows() { meter.mark(10); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java index c44e7a7d0e..ed33a7f83d 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingTimeWindowReservoirTest.java @@ -1,6 +1,6 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Random; @@ -10,9 +10,9 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class SlidingTimeWindowReservoirTest { +class SlidingTimeWindowReservoirTest { @Test - public void storesMeasurementsWithDuplicateTicks() { + void storesMeasurementsWithDuplicateTicks() { final Clock clock = mock(Clock.class); final SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(10, NANOSECONDS, clock); @@ -26,7 +26,7 @@ public void storesMeasurementsWithDuplicateTicks() { } @Test - public void boundsMeasurementsToATimeWindow() { + void boundsMeasurementsToATimeWindow() { final Clock clock = mock(Clock.class); when(clock.getTick()).thenReturn(0L); @@ -52,7 +52,7 @@ public void boundsMeasurementsToATimeWindow() { } @Test - public void testGetTickOverflow() { + void testGetTickOverflow() { final Random random = new Random(0); final int window = 128; diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java index 8ba626d041..35cf7176a7 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/SlidingWindowReservoirTest.java @@ -1,14 +1,14 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class SlidingWindowReservoirTest { +class SlidingWindowReservoirTest { private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); @Test - public void handlesSmallDataStreams() { + void handlesSmallDataStreams() { reservoir.update(1); reservoir.update(2); @@ -17,7 +17,7 @@ public void handlesSmallDataStreams() { } @Test - public void onlyKeepsTheMostRecentFromBigDataStreams() { + void onlyKeepsTheMostRecentFromBigDataStreams() { reservoir.update(1); reservoir.update(2); reservoir.update(3); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java index 0bf27ca1c6..ab5063a1b5 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/TimerTest.java @@ -1,6 +1,6 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.concurrent.TimeUnit; @@ -13,7 +13,7 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -public class TimerTest { +class TimerTest { private final Reservoir reservoir = mock(Reservoir.class); private final Clock clock = new Clock() { // a mock clock that increments its ticker by 50msec per call @@ -27,7 +27,7 @@ public long getTick() { private final Timer timer = new Timer(reservoir, clock); @Test - public void hasRates() { + void hasRates() { assertThat(timer.getCount()) .isZero(); @@ -48,7 +48,7 @@ public void hasRates() { } @Test - public void updatesTheCountAndSumOnUpdates() { + void updatesTheCountAndSumOnUpdates() { assertThat(timer.getCount()) .isZero(); assertThat(timer.getSum()) @@ -64,7 +64,7 @@ public void updatesTheCountAndSumOnUpdates() { } @Test - public void timesCallableInstances() throws Exception { + void timesCallableInstances() throws Exception { final String value = timer.time(() -> "one"); assertThat(timer.getCount()) @@ -79,7 +79,7 @@ public void timesCallableInstances() throws Exception { } @Test - public void timesSuppliedInstances() { + void timesSuppliedInstances() { final String value = timer.timeSupplier(() -> "one"); assertThat(timer.getCount()) @@ -92,7 +92,7 @@ public void timesSuppliedInstances() { } @Test - public void timesRunnableInstances() { + void timesRunnableInstances() { final AtomicBoolean called = new AtomicBoolean(); timer.time(() -> called.set(true)); @@ -108,7 +108,7 @@ public void timesRunnableInstances() { } @Test - public void timesContexts() { + void timesContexts() { timer.time().stop(); assertThat(timer.getCount()) @@ -120,7 +120,7 @@ public void timesContexts() { } @Test - public void returnsTheSnapshotFromTheReservoir() { + void returnsTheSnapshotFromTheReservoir() { final Snapshot snapshot = mock(Snapshot.class); when(reservoir.getSnapshot()).thenReturn(snapshot); @@ -129,7 +129,7 @@ public void returnsTheSnapshotFromTheReservoir() { } @Test - public void ignoresNegativeValues() { + void ignoresNegativeValues() { timer.update(-1, TimeUnit.SECONDS); assertThat(timer.getCount()) @@ -141,7 +141,7 @@ public void ignoresNegativeValues() { } @Test - public void java8Duration() { + void java8Duration() { timer.update(Duration.ofSeconds(1234)); assertThat(timer.getCount()).isEqualTo(1); @@ -150,7 +150,7 @@ public void java8Duration() { } @Test - public void java8NegativeDuration() { + void java8NegativeDuration() { timer.update(Duration.ofMillis(-5678)); assertThat(timer.getCount()).isZero(); @@ -159,7 +159,7 @@ public void java8NegativeDuration() { } @Test - public void tryWithResourcesWork() { + void tryWithResourcesWork() { assertThat(timer.getCount()).isZero(); assertThat(timer.getSum()).isZero(); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java index 7fccf40880..1976466cea 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformReservoirTest.java @@ -1,13 +1,13 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class UniformReservoirTest { +class UniformReservoirTest { @Test @SuppressWarnings("unchecked") - public void aReservoirOf100OutOf1000Elements() { + void aReservoirOf100OutOf1000Elements() { final UniformReservoir reservoir = new UniformReservoir(100); for (int i = 0; i < 1000; i++) { reservoir.update(i); diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java index 7074b28b89..508574b1e4 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/UniformSnapshotTest.java @@ -1,6 +1,6 @@ package io.dropwizard.metrics5; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.util.Random; @@ -11,81 +11,88 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.offset; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class UniformSnapshotTest { +class UniformSnapshotTest { private final Snapshot snapshot = new UniformSnapshot(new long[]{5, 1, 2, 3, 4}); @Test - public void smallQuantilesAreTheFirstValue() { + void smallQuantilesAreTheFirstValue() { assertThat(snapshot.getValue(0.0)) .isEqualTo(1, offset(0.1)); } @Test - public void bigQuantilesAreTheLastValue() { + void bigQuantilesAreTheLastValue() { assertThat(snapshot.getValue(1.0)) .isEqualTo(5, offset(0.1)); } - @Test(expected = IllegalArgumentException.class) - public void disallowsNotANumberQuantile() { - snapshot.getValue(Double.NaN); + @Test + void disallowsNotANumberQuantile() { + assertThrows(IllegalArgumentException.class, () -> { + snapshot.getValue(Double.NaN); + }); } - @Test(expected = IllegalArgumentException.class) - public void disallowsNegativeQuantile() { - snapshot.getValue(-0.5); + @Test + void disallowsNegativeQuantile() { + assertThrows(IllegalArgumentException.class, () -> { + snapshot.getValue(-0.5); + }); } - @Test(expected = IllegalArgumentException.class) - public void disallowsQuantileOverOne() { - snapshot.getValue(1.5); + @Test + void disallowsQuantileOverOne() { + assertThrows(IllegalArgumentException.class, () -> { + snapshot.getValue(1.5); + }); } @Test - public void hasAMedian() { + void hasAMedian() { assertThat(snapshot.getMedian()).isEqualTo(3, offset(0.1)); } @Test - public void hasAp75() { + void hasAp75() { assertThat(snapshot.get75thPercentile()).isEqualTo(4.5, offset(0.1)); } @Test - public void hasAp95() { + void hasAp95() { assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test - public void hasAp98() { + void hasAp98() { assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test - public void hasAp99() { + void hasAp99() { assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test - public void hasAp999() { + void hasAp999() { assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test - public void hasValues() { + void hasValues() { assertThat(snapshot.getValues()) .containsOnly(1, 2, 3, 4, 5); } @Test - public void hasASize() { + void hasASize() { assertThat(snapshot.size()) .isEqualTo(5); } @Test - public void canAlsoBeCreatedFromACollectionOfLongs() { + void canAlsoBeCreatedFromACollectionOfLongs() { final Snapshot other = new UniformSnapshot(asList(5L, 1L, 2L, 3L, 4L)); assertThat(other.getValues()) @@ -93,7 +100,7 @@ public void canAlsoBeCreatedFromACollectionOfLongs() { } @Test - public void correctlyCreatedFromCollectionWithWeakIterator() throws Exception { + void correctlyCreatedFromCollectionWithWeakIterator() throws Exception { final ConcurrentSkipListSet values = new ConcurrentSkipListSet<>(); // Create a latch to make sure that the background thread has started and @@ -123,7 +130,7 @@ public void correctlyCreatedFromCollectionWithWeakIterator() throws Exception { } @Test - public void dumpsToAStream() { + void dumpsToAStream() { final ByteArrayOutputStream output = new ByteArrayOutputStream(); snapshot.dump(output); @@ -133,31 +140,31 @@ public void dumpsToAStream() { } @Test - public void calculatesTheMinimumValue() { + void calculatesTheMinimumValue() { assertThat(snapshot.getMin()) .isEqualTo(1); } @Test - public void calculatesTheMaximumValue() { + void calculatesTheMaximumValue() { assertThat(snapshot.getMax()) .isEqualTo(5); } @Test - public void calculatesTheMeanValue() { + void calculatesTheMeanValue() { assertThat(snapshot.getMean()) .isEqualTo(3.0); } @Test - public void calculatesTheStdDev() { + void calculatesTheStdDev() { assertThat(snapshot.getStdDev()) .isEqualTo(1.5811, offset(0.0001)); } @Test - public void calculatesAMinOfZeroForAnEmptySnapshot() { + void calculatesAMinOfZeroForAnEmptySnapshot() { final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); assertThat(emptySnapshot.getMin()) @@ -165,7 +172,7 @@ public void calculatesAMinOfZeroForAnEmptySnapshot() { } @Test - public void calculatesAMaxOfZeroForAnEmptySnapshot() { + void calculatesAMaxOfZeroForAnEmptySnapshot() { final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); assertThat(emptySnapshot.getMax()) @@ -173,7 +180,7 @@ public void calculatesAMaxOfZeroForAnEmptySnapshot() { } @Test - public void calculatesAMeanOfZeroForAnEmptySnapshot() { + void calculatesAMeanOfZeroForAnEmptySnapshot() { final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); assertThat(emptySnapshot.getMean()) @@ -181,7 +188,7 @@ public void calculatesAMeanOfZeroForAnEmptySnapshot() { } @Test - public void calculatesAStdDevOfZeroForAnEmptySnapshot() { + void calculatesAStdDevOfZeroForAnEmptySnapshot() { final Snapshot emptySnapshot = new UniformSnapshot(new long[]{}); assertThat(emptySnapshot.getStdDev()) @@ -189,7 +196,7 @@ public void calculatesAStdDevOfZeroForAnEmptySnapshot() { } @Test - public void calculatesAStdDevOfZeroForASingletonSnapshot() { + void calculatesAStdDevOfZeroForASingletonSnapshot() { final Snapshot singleItemSnapshot = new UniformSnapshot(new long[]{1}); assertThat(singleItemSnapshot.getStdDev()) diff --git a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java index 515656eaa8..be651fdba4 100644 --- a/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java +++ b/metrics-core/src/test/java/io/dropwizard/metrics5/WeightedSnapshotTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5; import io.dropwizard.metrics5.WeightedSnapshot.WeightedSample; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import java.io.ByteArrayOutputStream; @@ -10,11 +10,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.offset; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; -public class WeightedSnapshotTest { +class WeightedSnapshotTest { private static List weightedArray(long[] values, double[] weights) { if (values.length != weights.length) { @@ -33,76 +34,82 @@ private static List weightedArray(long[] values weightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2})); @Test - public void smallQuantilesAreTheFirstValue() { + void smallQuantilesAreTheFirstValue() { assertThat(snapshot.getValue(0.0)) .isEqualTo(1.0, offset(0.1)); } @Test - public void bigQuantilesAreTheLastValue() { + void bigQuantilesAreTheLastValue() { assertThat(snapshot.getValue(1.0)) .isEqualTo(5.0, offset(0.1)); } - @Test(expected = IllegalArgumentException.class) - public void disallowsNotANumberQuantile() { - snapshot.getValue(Double.NaN); + @Test + void disallowsNotANumberQuantile() { + assertThrows(IllegalArgumentException.class, () -> { + snapshot.getValue(Double.NaN); + }); } - @Test(expected = IllegalArgumentException.class) - public void disallowsNegativeQuantile() { - snapshot.getValue(-0.5); + @Test + void disallowsNegativeQuantile() { + assertThrows(IllegalArgumentException.class, () -> { + snapshot.getValue(-0.5); + }); } - @Test(expected = IllegalArgumentException.class) - public void disallowsQuantileOverOne() { - snapshot.getValue(1.5); + @Test + void disallowsQuantileOverOne() { + assertThrows(IllegalArgumentException.class, () -> { + snapshot.getValue(1.5); + }); } @Test - public void hasAMedian() { + void hasAMedian() { assertThat(snapshot.getMedian()).isEqualTo(3.0, offset(0.1)); } @Test - public void hasAp75() { + void hasAp75() { assertThat(snapshot.get75thPercentile()).isEqualTo(4.0, offset(0.1)); } @Test - public void hasAp95() { + void hasAp95() { assertThat(snapshot.get95thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test - public void hasAp98() { + void hasAp98() { assertThat(snapshot.get98thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test - public void hasAp99() { + void hasAp99() { assertThat(snapshot.get99thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test - public void hasAp999() { + void hasAp999() { assertThat(snapshot.get999thPercentile()).isEqualTo(5.0, offset(0.1)); } @Test - public void hasValues() { + void hasValues() { assertThat(snapshot.getValues()) .containsOnly(1, 2, 3, 4, 5); } @Test - public void hasASize() { + void hasASize() { assertThat(snapshot.size()) .isEqualTo(5); } @Test - public void worksWithUnderestimatedCollections() { + void worksWithUnderestimatedCollections() { final List originalItems = weightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2}); final List spyItems = spy(originalItems); doReturn(originalItems.toArray(new WeightedSample[]{})).when(spyItems).toArray(ArgumentMatchers.any(WeightedSample[].class)); @@ -115,7 +122,7 @@ public void worksWithUnderestimatedCollections() { } @Test - public void worksWithOverestimatedCollections() { + void worksWithOverestimatedCollections() { final List originalItems = weightedArray(new long[]{5, 1, 2, 3, 4}, new double[]{1, 2, 3, 2, 2}); final List spyItems = spy(originalItems); doReturn(originalItems.toArray(new WeightedSample[]{})).when(spyItems).toArray(ArgumentMatchers.any(WeightedSample[].class)); @@ -128,7 +135,7 @@ public void worksWithOverestimatedCollections() { } @Test - public void dumpsToAStream() { + void dumpsToAStream() { final ByteArrayOutputStream output = new ByteArrayOutputStream(); snapshot.dump(output); @@ -138,31 +145,31 @@ public void dumpsToAStream() { } @Test - public void calculatesTheMinimumValue() { + void calculatesTheMinimumValue() { assertThat(snapshot.getMin()) .isEqualTo(1); } @Test - public void calculatesTheMaximumValue() { + void calculatesTheMaximumValue() { assertThat(snapshot.getMax()) .isEqualTo(5); } @Test - public void calculatesTheMeanValue() { + void calculatesTheMeanValue() { assertThat(snapshot.getMean()) .isEqualTo(2.7); } @Test - public void calculatesTheStdDev() { + void calculatesTheStdDev() { assertThat(snapshot.getStdDev()) .isEqualTo(1.2688, offset(0.0001)); } @Test - public void calculatesAMinOfZeroForAnEmptySnapshot() { + void calculatesAMinOfZeroForAnEmptySnapshot() { final Snapshot emptySnapshot = new WeightedSnapshot( weightedArray(new long[]{}, new double[]{})); @@ -171,7 +178,7 @@ public void calculatesAMinOfZeroForAnEmptySnapshot() { } @Test - public void calculatesAMaxOfZeroForAnEmptySnapshot() { + void calculatesAMaxOfZeroForAnEmptySnapshot() { final Snapshot emptySnapshot = new WeightedSnapshot( weightedArray(new long[]{}, new double[]{})); @@ -180,7 +187,7 @@ public void calculatesAMaxOfZeroForAnEmptySnapshot() { } @Test - public void calculatesAMeanOfZeroForAnEmptySnapshot() { + void calculatesAMeanOfZeroForAnEmptySnapshot() { final Snapshot emptySnapshot = new WeightedSnapshot( weightedArray(new long[]{}, new double[]{})); @@ -189,7 +196,7 @@ public void calculatesAMeanOfZeroForAnEmptySnapshot() { } @Test - public void calculatesAStdDevOfZeroForAnEmptySnapshot() { + void calculatesAStdDevOfZeroForAnEmptySnapshot() { final Snapshot emptySnapshot = new WeightedSnapshot( weightedArray(new long[]{}, new double[]{})); @@ -198,7 +205,7 @@ public void calculatesAStdDevOfZeroForAnEmptySnapshot() { } @Test - public void calculatesAStdDevOfZeroForASingletonSnapshot() { + void calculatesAStdDevOfZeroForASingletonSnapshot() { final Snapshot singleItemSnapshot = new WeightedSnapshot( weightedArray(new long[]{1}, new double[]{1.0})); @@ -207,7 +214,7 @@ public void calculatesAStdDevOfZeroForASingletonSnapshot() { } @Test - public void expectNoOverflowForLowWeights() { + void expectNoOverflowForLowWeights() { final Snapshot scatteredSnapshot = new WeightedSnapshot( weightedArray( new long[]{1, 2, 3}, @@ -220,7 +227,7 @@ public void expectNoOverflowForLowWeights() { } @Test - public void doesNotProduceNaNValues() { + void doesNotProduceNaNValues() { WeightedSnapshot weightedSnapshot = new WeightedSnapshot( weightedArray(new long[]{1, 2, 3}, new double[]{0, 0, 0})); assertThat(weightedSnapshot.getMean()).isEqualTo(0); diff --git a/metrics-ehcache/pom.xml b/metrics-ehcache/pom.xml index 0abf498143..75e3cb7be8 100644 --- a/metrics-ehcache/pom.xml +++ b/metrics-ehcache/pom.xml @@ -49,15 +49,15 @@ - junit - junit - ${junit.version} + org.junit.jupiter + junit-jupiter-api + ${junit5.version} test - org.hamcrest - hamcrest-core - ${hamcrest.version} + org.junit.jupiter + junit-jupiter + ${junit5.version} test diff --git a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java index 571a3fd5fe..35f9a11156 100644 --- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java +++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedCacheDecoratorFactoryTest.java @@ -6,30 +6,28 @@ import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; -import org.hamcrest.CoreMatchers; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assume.assumeThat; +import static org.assertj.core.api.Assumptions.assumeThat; -public class InstrumentedCacheDecoratorFactoryTest { +class InstrumentedCacheDecoratorFactoryTest { private static final CacheManager MANAGER = CacheManager.create(); private MetricRegistry registry; private Ehcache cache; - @Before - public void setUp() { + @BeforeEach + void setUp() { this.cache = MANAGER.getEhcache("test-config"); - assumeThat(cache, is(CoreMatchers.notNullValue())); + assumeThat(cache).isNotNull(); this.registry = SharedMetricRegistries.getOrCreate("cache-metrics"); } @Test - public void measuresGets() { + void measuresGets() { cache.get("woo"); assertThat(registry.timer(MetricRegistry.name(Cache.class, "test-config", "gets")).getCount()) @@ -38,7 +36,7 @@ public void measuresGets() { } @Test - public void measuresPuts() { + void measuresPuts() { cache.put(new Element("woo", "whee")); assertThat(registry.timer(MetricRegistry.name(Cache.class, "test-config", "puts")).getCount()) diff --git a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java index 92b5a9d09f..e6ed0c5ced 100644 --- a/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java +++ b/metrics-ehcache/src/test/java/io/dropwizard/metrics5/ehcache/InstrumentedEhcacheTest.java @@ -7,20 +7,20 @@ import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import net.sf.ehcache.config.CacheConfiguration; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -public class InstrumentedEhcacheTest { +class InstrumentedEhcacheTest { private static final CacheManager MANAGER = CacheManager.create(); private final MetricRegistry registry = new MetricRegistry(); private Ehcache cache; - @Before - public void setUp() { + @BeforeEach + void setUp() { final Cache c = new Cache(new CacheConfiguration("test", 100)); MANAGER.addCache(c); this.cache = InstrumentedEhcache.instrument(registry, c); @@ -48,7 +48,7 @@ public void setUp() { } @Test - public void measuresGetsAndPuts() { + void measuresGetsAndPuts() { cache.get("woo"); cache.put(new Element("woo", "whee")); diff --git a/metrics-graphite/pom.xml b/metrics-graphite/pom.xml index 76111073b5..ea9c85266e 100644 --- a/metrics-graphite/pom.xml +++ b/metrics-graphite/pom.xml @@ -62,18 +62,24 @@ slf4j-api ${slf4j.version} - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java index d6c9fe1fca..5f7a01384e 100755 --- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java +++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteRabbitMQTest.java @@ -3,8 +3,8 @@ import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.UnknownHostException; @@ -21,7 +21,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class GraphiteRabbitMQTest { +class GraphiteRabbitMQTest { private final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); private final Connection connection = mock(Connection.class); private final Channel channel = mock(Channel.class); @@ -32,8 +32,8 @@ public class GraphiteRabbitMQTest { private final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(connectionFactory, "graphite"); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(connectionFactory.newConnection()).thenReturn(connection); when(connection.createChannel()).thenReturn(channel); when(connection.isOpen()).thenReturn(true); @@ -46,7 +46,7 @@ public void setUp() throws Exception { } @Test - public void shouldConnectToGraphiteServer() throws Exception { + void shouldConnectToGraphiteServer() throws Exception { graphite.connect(); verify(connectionFactory, atMost(1)).newConnection(); @@ -55,7 +55,7 @@ public void shouldConnectToGraphiteServer() throws Exception { } @Test - public void measuresFailures() throws Exception { + void measuresFailures() throws Exception { try (final GraphiteRabbitMQ graphite = new GraphiteRabbitMQ(bogusConnectionFactory, "graphite")) { graphite.connect(); try { @@ -68,7 +68,7 @@ public void measuresFailures() throws Exception { } @Test - public void shouldDisconnectsFromGraphiteServer() throws Exception { + void shouldDisconnectsFromGraphiteServer() throws Exception { graphite.connect(); graphite.close(); @@ -76,7 +76,7 @@ public void shouldDisconnectsFromGraphiteServer() throws Exception { } @Test - public void shouldNotConnectToGraphiteServerMoreThenOnce() throws Exception { + void shouldNotConnectToGraphiteServerMoreThenOnce() throws Exception { graphite.connect(); try { graphite.connect(); @@ -87,7 +87,7 @@ public void shouldNotConnectToGraphiteServerMoreThenOnce() throws Exception { } @Test - public void shouldSendMetricsToGraphiteServer() throws Exception { + void shouldSendMetricsToGraphiteServer() throws Exception { graphite.connect(); graphite.send("name", "value", 100); @@ -100,7 +100,7 @@ public void shouldSendMetricsToGraphiteServer() throws Exception { } @Test - public void shouldSanitizeAndSendMetricsToGraphiteServer() throws Exception { + void shouldSanitizeAndSendMetricsToGraphiteServer() throws Exception { graphite.connect(); graphite.send("name to sanitize", "value to sanitize", 100); @@ -113,7 +113,7 @@ public void shouldSanitizeAndSendMetricsToGraphiteServer() throws Exception { } @Test - public void shouldFailWhenGraphiteHostUnavailable() { + void shouldFailWhenGraphiteHostUnavailable() { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("some-unknown-host"); diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java index 0ba9841fec..492456c6b8 100644 --- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java +++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteReporterTest.java @@ -11,8 +11,8 @@ import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.Snapshot; import io.dropwizard.metrics5.Timer; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InOrder; import java.net.UnknownHostException; @@ -34,7 +34,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -public class GraphiteReporterTest { +class GraphiteReporterTest { private static final MetricName GAUGE = MetricName.build("gauge"); private static final MetricName METER = MetricName.build("meter"); private static final MetricName COUNTER = MetricName.build("counter"); @@ -62,13 +62,13 @@ public class GraphiteReporterTest { .disabledMetricAttributes(Collections.emptySet()) .build(graphite); - @Before - public void setUp() { + @BeforeEach + void setUp() { when(clock.getTime()).thenReturn(timestamp * 1000); } @Test - public void doesNotReportStringGaugeValues() throws Exception { + void doesNotReportStringGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge("value")), map(), map(), @@ -85,7 +85,7 @@ public void doesNotReportStringGaugeValues() throws Exception { } @Test - public void reportsByteGaugeValues() throws Exception { + void reportsByteGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge((byte) 1)), map(), map(), @@ -102,7 +102,7 @@ public void reportsByteGaugeValues() throws Exception { } @Test - public void reportsShortGaugeValues() throws Exception { + void reportsShortGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge((short) 1)), map(), map(), @@ -119,7 +119,7 @@ public void reportsShortGaugeValues() throws Exception { } @Test - public void reportsIntegerGaugeValues() throws Exception { + void reportsIntegerGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge(1)), map(), map(), @@ -136,7 +136,7 @@ public void reportsIntegerGaugeValues() throws Exception { } @Test - public void reportsLongGaugeValues() throws Exception { + void reportsLongGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge(1L)), map(), map(), @@ -153,7 +153,7 @@ public void reportsLongGaugeValues() throws Exception { } @Test - public void reportsFloatGaugeValues() throws Exception { + void reportsFloatGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge(1.1f)), map(), map(), @@ -170,7 +170,7 @@ public void reportsFloatGaugeValues() throws Exception { } @Test - public void reportsDoubleGaugeValues() throws Exception { + void reportsDoubleGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge(1.1)), map(), map(), @@ -187,7 +187,7 @@ public void reportsDoubleGaugeValues() throws Exception { } @Test - public void reportsDoubleGaugeValuesWithCustomFormat() throws Exception { + void reportsDoubleGaugeValuesWithCustomFormat() throws Exception { try (final GraphiteReporter graphiteReporter = getReporterWithCustomFormat()) { reportGaugeValue(graphiteReporter, 1.13574); verifyGraphiteSentCorrectMetricValue("prefix.gauge", "1.1357", timestamp); @@ -196,18 +196,18 @@ public void reportsDoubleGaugeValuesWithCustomFormat() throws Exception { } @Test - public void reportDoubleGaugeValuesUsingCustomFormatter() throws Exception { + void reportDoubleGaugeValuesUsingCustomFormatter() throws Exception { DecimalFormat formatter = new DecimalFormat("##.##########", DecimalFormatSymbols.getInstance(Locale.US)); try (GraphiteReporter graphiteReporter = GraphiteReporter.forRegistry(registry) - .withClock(clock) - .prefixedWith("prefix") - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) - .disabledMetricAttributes(Collections.emptySet()) - .withFloatingPointFormatter(formatter::format) - .build(graphite)) { + .withClock(clock) + .prefixedWith("prefix") + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) + .disabledMetricAttributes(Collections.emptySet()) + .withFloatingPointFormatter(formatter::format) + .build(graphite)) { reportGaugeValue(graphiteReporter, 0.000045322); verifyGraphiteSentCorrectMetricValue("prefix.gauge", "0.000045322", timestamp); verifyNoMoreInteractions(graphite); @@ -216,10 +216,10 @@ public void reportDoubleGaugeValuesUsingCustomFormatter() throws Exception { private void reportGaugeValue(GraphiteReporter graphiteReporter, double value) { graphiteReporter.report(map(MetricName.build("gauge"), gauge(value)), - map(), - map(), - map(), - map()); + map(), + map(), + map(), + map()); } private void verifyGraphiteSentCorrectMetricValue(String metricName, String value, long timestamp) throws Exception { @@ -231,7 +231,7 @@ private void verifyGraphiteSentCorrectMetricValue(String metricName, String valu } @Test - public void reportsBooleanGaugeValues() throws Exception { + void reportsBooleanGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge(true)), map(), map(), @@ -257,7 +257,7 @@ public void reportsBooleanGaugeValues() throws Exception { } @Test - public void reportsCounters() throws Exception { + void reportsCounters() throws Exception { final Counter counter = mock(Counter.class); when(counter.getCount()).thenReturn(100L); @@ -277,7 +277,7 @@ public void reportsCounters() throws Exception { } @Test - public void reportsHistograms() throws Exception { + void reportsHistograms() throws Exception { final Histogram histogram = mock(Histogram.class); when(histogram.getCount()).thenReturn(1L); when(histogram.getSum()).thenReturn(12L); @@ -323,7 +323,7 @@ public void reportsHistograms() throws Exception { } @Test - public void reportsMeters() throws Exception { + void reportsMeters() throws Exception { final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getSum()).thenReturn(6L); @@ -353,7 +353,7 @@ public void reportsMeters() throws Exception { } @Test - public void reportsMetersInMinutes() throws Exception { + void reportsMetersInMinutes() throws Exception { final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getSum()).thenReturn(6L); @@ -383,7 +383,7 @@ public void reportsMetersInMinutes() throws Exception { } @Test - public void reportsTimers() throws Exception { + void reportsTimers() throws Exception { final Timer timer = mock(Timer.class); when(timer.getCount()).thenReturn(1L); when(timer.getSum()).thenReturn(TimeUnit.MILLISECONDS.toNanos(6)); @@ -440,7 +440,7 @@ public void reportsTimers() throws Exception { } @Test - public void closesConnectionIfGraphiteIsUnavailable() throws Exception { + void closesConnectionIfGraphiteIsUnavailable() throws Exception { doThrow(new UnknownHostException("UNKNOWN-HOST")).when(graphite).connect(); reporter.report(map(GAUGE, gauge(1)), map(), @@ -457,7 +457,7 @@ public void closesConnectionIfGraphiteIsUnavailable() throws Exception { } @Test - public void closesConnectionOnReporterStop() throws Exception { + void closesConnectionOnReporterStop() throws Exception { reporter.stop(); final InOrder inOrder = inOrder(graphite); @@ -469,7 +469,7 @@ public void closesConnectionOnReporterStop() throws Exception { } @Test - public void disabledMetricsAttribute() throws Exception { + void disabledMetricsAttribute() throws Exception { final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getSum()).thenReturn(6L); @@ -510,15 +510,15 @@ public void disabledMetricsAttribute() throws Exception { } @Test - public void sendsMetricAttributesAsTagsIfEnabled() throws Exception { + void sendsMetricAttributesAsTagsIfEnabled() throws Exception { final Counter counter = mock(Counter.class); when(counter.getCount()).thenReturn(100L); getReporterThatSendsMetricAttributesAsTags().report(map(), - map(COUNTER, counter), - map(), - map(), - map()); + map(COUNTER, counter), + map(), + map(), + map()); final InOrder inOrder = inOrder(graphite); inOrder.verify(graphite).connect(); @@ -542,14 +542,14 @@ protected String format(double v) { private GraphiteReporter getReporterThatSendsMetricAttributesAsTags() { return GraphiteReporter.forRegistry(registry) - .withClock(clock) - .prefixedWith("prefix") - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) - .disabledMetricAttributes(Collections.emptySet()) - .addMetricAttributesAsTags(true) - .build(graphite); + .withClock(clock) + .prefixedWith("prefix") + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) + .disabledMetricAttributes(Collections.emptySet()) + .addMetricAttributesAsTags(true) + .build(graphite); } private SortedMap map() { diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java index 7d0296d969..78203b9385 100644 --- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java +++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteSanitizeTest.java @@ -1,11 +1,11 @@ package io.dropwizard.metrics5.graphite; import org.assertj.core.api.SoftAssertions; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GraphiteSanitizeTest { +class GraphiteSanitizeTest { @Test - public void sanitizeGraphiteValues() { + void sanitizeGraphiteValues() { SoftAssertions softly = new SoftAssertions(); softly.assertThat(GraphiteSanitize.sanitize("Foo Bar")).isEqualTo("Foo-Bar"); diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java index e5a179bf01..fa634a57b6 100644 --- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java +++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5.graphite; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.net.SocketFactory; import java.io.ByteArrayOutputStream; @@ -24,7 +24,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class GraphiteTest { +class GraphiteTest { private final String host = "example.com"; private final int port = 1234; private final SocketFactory socketFactory = mock(SocketFactory.class); @@ -33,8 +33,8 @@ public class GraphiteTest { private final Socket socket = mock(Socket.class); private final ByteArrayOutputStream output = spy(ByteArrayOutputStream.class); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { final AtomicBoolean connected = new AtomicBoolean(true); final AtomicBoolean closed = new AtomicBoolean(false); @@ -61,7 +61,7 @@ public void setUp() throws Exception { } @Test - public void connectsToGraphiteWithInetSocketAddress() throws Exception { + void connectsToGraphiteWithInetSocketAddress() throws Exception { try (Graphite graphite = new Graphite(address, socketFactory)) { graphite.connect(); } @@ -69,7 +69,7 @@ public void connectsToGraphiteWithInetSocketAddress() throws Exception { } @Test - public void connectsToGraphiteWithHostAndPort() throws Exception { + void connectsToGraphiteWithHostAndPort() throws Exception { try (Graphite graphite = new Graphite(host, port, socketFactory)) { graphite.connect(); } @@ -77,14 +77,14 @@ public void connectsToGraphiteWithHostAndPort() throws Exception { } @Test - public void measuresFailures() throws IOException { + void measuresFailures() throws IOException { try (Graphite graphite = new Graphite(address, socketFactory)) { assertThat(graphite.getFailures()).isZero(); } } @Test - public void disconnectsFromGraphite() throws Exception { + void disconnectsFromGraphite() throws Exception { try (Graphite graphite = new Graphite(address, socketFactory)) { graphite.connect(); } @@ -93,17 +93,17 @@ public void disconnectsFromGraphite() throws Exception { } @Test - public void doesNotAllowDoubleConnections() throws Exception { + void doesNotAllowDoubleConnections() throws Exception { try (Graphite graphite = new Graphite(address, socketFactory)) { assertThatNoException().isThrownBy(graphite::connect); assertThatThrownBy(graphite::connect) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Already connected"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("Already connected"); } } @Test - public void writesValuesToGraphite() throws Exception { + void writesValuesToGraphite() throws Exception { try (Graphite graphite = new Graphite(address, socketFactory)) { graphite.connect(); graphite.send("name", "value", 100); @@ -112,7 +112,7 @@ public void writesValuesToGraphite() throws Exception { } @Test - public void sanitizesNames() throws Exception { + void sanitizesNames() throws Exception { try (Graphite graphite = new Graphite(address, socketFactory)) { graphite.connect(); graphite.send("name woo", "value", 100); @@ -121,7 +121,7 @@ public void sanitizesNames() throws Exception { } @Test - public void sanitizesValues() throws Exception { + void sanitizesValues() throws Exception { try (Graphite graphite = new Graphite(address, socketFactory)) { graphite.connect(); graphite.send("name", "value woo", 100); @@ -130,14 +130,14 @@ public void sanitizesValues() throws Exception { } @Test - public void notifiesIfGraphiteIsUnavailable() throws IOException { + void notifiesIfGraphiteIsUnavailable() throws IOException { final String unavailableHost = "unknown-host-10el6m7yg56ge7dmcom"; InetSocketAddress unavailableAddress = new InetSocketAddress(unavailableHost, 1234); try (Graphite unavailableGraphite = new Graphite(unavailableAddress, socketFactory)) { assertThatThrownBy(unavailableGraphite::connect) - .isInstanceOf(UnknownHostException.class) - .hasMessage(unavailableHost); + .isInstanceOf(UnknownHostException.class) + .hasMessage(unavailableHost); } } } diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java index 640aad1e94..80c712e95d 100644 --- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java +++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/GraphiteUDPTest.java @@ -1,6 +1,6 @@ package io.dropwizard.metrics5.graphite; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.net.InetSocketAddress; @@ -10,7 +10,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; -public class GraphiteUDPTest { +class GraphiteUDPTest { private final String host = "example.com"; private final int port = 1234; @@ -18,7 +18,7 @@ public class GraphiteUDPTest { private GraphiteUDP graphiteUDP; @Test - public void connects() throws Exception { + void connects() throws Exception { graphiteUDP = new GraphiteUDP(host, port); graphiteUDP.connect(); @@ -29,7 +29,7 @@ public void connects() throws Exception { } @Test - public void writesValue() throws Exception { + void writesValue() throws Exception { graphiteUDP = new GraphiteUDP(host, port); DatagramChannel mockDatagramChannel = Mockito.mock(DatagramChannel.class); graphiteUDP.setDatagramChannel(mockDatagramChannel); @@ -37,7 +37,7 @@ public void writesValue() throws Exception { graphiteUDP.send("name woo", "value", 100); verify(mockDatagramChannel).send(ByteBuffer.wrap("name-woo value 100\n".getBytes("UTF-8")), - new InetSocketAddress(host, port)); + new InetSocketAddress(host, port)); } } \ No newline at end of file diff --git a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java index b0579e8a0b..296cb26882 100644 --- a/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java +++ b/metrics-graphite/src/test/java/io/dropwizard/metrics5/graphite/PickledGraphiteTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5.graphite; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.python.core.PyList; import org.python.core.PyTuple; @@ -32,7 +32,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class PickledGraphiteTest { +class PickledGraphiteTest { private final SocketFactory socketFactory = mock(SocketFactory.class); private final InetSocketAddress address = new InetSocketAddress("example.com", 1234); private final PickledGraphite graphite = new PickledGraphite(address, socketFactory, UTF_8, 2); @@ -42,8 +42,8 @@ public class PickledGraphiteTest { private CompiledScript unpickleScript; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { final AtomicBoolean connected = new AtomicBoolean(true); final AtomicBoolean closed = new AtomicBoolean(false); @@ -77,7 +77,7 @@ public void setUp() throws Exception { } @Test - public void disconnectsFromGraphite() throws Exception { + void disconnectsFromGraphite() throws Exception { graphite.connect(); graphite.close(); @@ -85,7 +85,7 @@ public void disconnectsFromGraphite() throws Exception { } @Test - public void writesValuesToGraphite() throws Exception { + void writesValuesToGraphite() throws Exception { graphite.connect(); graphite.send("name", "value", 100); graphite.close(); @@ -95,7 +95,7 @@ public void writesValuesToGraphite() throws Exception { } @Test - public void writesFullBatch() throws Exception { + void writesFullBatch() throws Exception { graphite.connect(); graphite.send("name", "value", 100); graphite.send("name", "value2", 100); @@ -106,7 +106,7 @@ public void writesFullBatch() throws Exception { } @Test - public void writesPastFullBatch() throws Exception { + void writesPastFullBatch() throws Exception { graphite.connect(); graphite.send("name", "value", 100); graphite.send("name", "value2", 100); @@ -118,7 +118,7 @@ public void writesPastFullBatch() throws Exception { } @Test - public void sanitizesNames() throws Exception { + void sanitizesNames() throws Exception { graphite.connect(); graphite.send("name woo", "value", 100); graphite.close(); @@ -128,7 +128,7 @@ public void sanitizesNames() throws Exception { } @Test - public void sanitizesValues() throws Exception { + void sanitizesValues() throws Exception { graphite.connect(); graphite.send("name", "value woo", 100); graphite.close(); @@ -138,14 +138,14 @@ public void sanitizesValues() throws Exception { } @Test - public void doesNotAllowDoubleConnections() throws Exception { + void doesNotAllowDoubleConnections() throws Exception { graphite.connect(); try { graphite.connect(); failBecauseExceptionWasNotThrown(IllegalStateException.class); } catch (IllegalStateException e) { assertThat(e.getMessage()) - .isEqualTo("Already connected"); + .isEqualTo("Already connected"); } } diff --git a/metrics-healthchecks/pom.xml b/metrics-healthchecks/pom.xml index 418a1eb575..88c97e0155 100644 --- a/metrics-healthchecks/pom.xml +++ b/metrics-healthchecks/pom.xml @@ -52,18 +52,24 @@ slf4j-api ${slf4j.version} - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java index bc018c9f93..974962da2b 100644 --- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java +++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/AsyncHealthCheckDecoratorTest.java @@ -2,7 +2,7 @@ import io.dropwizard.metrics5.Clock; import io.dropwizard.metrics5.health.annotation.Async; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.util.concurrent.ScheduledExecutorService; @@ -10,6 +10,7 @@ import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentCaptor.forClass; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -18,10 +19,10 @@ /** * Unit tests for {@link AsyncHealthCheckDecorator}. */ -public class AsyncHealthCheckDecoratorTest { +class AsyncHealthCheckDecoratorTest { private static final long CURRENT_TIME = 1551002401000L; - + private static final Clock FIXED_CLOCK = clockWithFixedTime(CURRENT_TIME); private static final HealthCheck.Result EXPECTED_EXPIRED_RESULT = HealthCheck.Result @@ -30,45 +31,57 @@ public class AsyncHealthCheckDecoratorTest { .unhealthy() .withMessage("Result was healthy but it expired 1 milliseconds ago") .build(); - + private final HealthCheck mockHealthCheck = mock(HealthCheck.class); private final ScheduledExecutorService mockExecutorService = mock(ScheduledExecutorService.class); @SuppressWarnings("rawtypes") private final ScheduledFuture mockFuture = mock(ScheduledFuture.class); - @Test(expected = IllegalArgumentException.class) - public void nullHealthCheckTriggersInstantiationFailure() { - new AsyncHealthCheckDecorator(null, mockExecutorService); + @Test + void nullHealthCheckTriggersInstantiationFailure() { + assertThrows(IllegalArgumentException.class, () -> { + new AsyncHealthCheckDecorator(null, mockExecutorService); + }); } - @Test(expected = IllegalArgumentException.class) - public void nullExecutorServiceTriggersInstantiationFailure() { - new AsyncHealthCheckDecorator(mockHealthCheck, null); + @Test + void nullExecutorServiceTriggersInstantiationFailure() { + assertThrows(IllegalArgumentException.class, () -> { + new AsyncHealthCheckDecorator(mockHealthCheck, null); + }); } - @Test(expected = IllegalArgumentException.class) - public void nonAsyncHealthCheckTriggersInstantiationFailure() { - new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); + @Test + void nonAsyncHealthCheckTriggersInstantiationFailure() { + assertThrows(IllegalArgumentException.class, () -> { + new AsyncHealthCheckDecorator(mockHealthCheck, mockExecutorService); + }); } - @Test(expected = IllegalArgumentException.class) - public void negativePeriodTriggersInstantiationFailure() { - new AsyncHealthCheckDecorator(new NegativePeriodAsyncHealthCheck(), mockExecutorService); + @Test + void negativePeriodTriggersInstantiationFailure() { + assertThrows(IllegalArgumentException.class, () -> { + new AsyncHealthCheckDecorator(new NegativePeriodAsyncHealthCheck(), mockExecutorService); + }); } - @Test(expected = IllegalArgumentException.class) - public void zeroPeriodTriggersInstantiationFailure() { - new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); + @Test + void zeroPeriodTriggersInstantiationFailure() { + assertThrows(IllegalArgumentException.class, () -> { + new AsyncHealthCheckDecorator(new ZeroPeriodAsyncHealthCheck(), mockExecutorService); + }); } - @Test(expected = IllegalArgumentException.class) - public void negativeInitialValueTriggersInstantiationFailure() { - new AsyncHealthCheckDecorator(new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); + @Test + void negativeInitialValueTriggersInstantiationFailure() { + assertThrows(IllegalArgumentException.class, () -> { + new AsyncHealthCheckDecorator(new NegativeInitialDelayAsyncHealthCheck(), mockExecutorService); + }); } @Test - public void defaultAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedRateAndHealthyState() throws Exception { + void defaultAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedRateAndHealthyState() throws Exception { HealthCheck asyncHealthCheck = new DefaultAsyncHealthCheck(); AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); @@ -79,7 +92,7 @@ public void defaultAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedRateA } @Test - public void fixedDelayAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedDelay() throws Exception { + void fixedDelayAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedDelay() throws Exception { HealthCheck asyncHealthCheck = new FixedDelayAsyncHealthCheck(); AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); @@ -89,7 +102,7 @@ public void fixedDelayAsyncHealthCheckTriggersSuccessfulInstantiationWithFixedDe } @Test - public void unhealthyAsyncHealthCheckTriggersSuccessfulInstantiationWithUnhealthyState() throws Exception { + void unhealthyAsyncHealthCheckTriggersSuccessfulInstantiationWithUnhealthyState() throws Exception { HealthCheck asyncHealthCheck = new UnhealthyAsyncHealthCheck(); AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(asyncHealthCheck, mockExecutorService); @@ -98,7 +111,7 @@ public void unhealthyAsyncHealthCheckTriggersSuccessfulInstantiationWithUnhealth @Test @SuppressWarnings("unchecked") - public void tearDownTriggersCancellation() throws Exception { + void tearDownTriggersCancellation() throws Exception { when(mockExecutorService.scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))). thenReturn(mockFuture); when(mockFuture.cancel(true)).thenReturn(true); @@ -113,7 +126,7 @@ public void tearDownTriggersCancellation() throws Exception { @Test @SuppressWarnings("unchecked") - public void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { + void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exception { HealthCheck.Result expectedResult = HealthCheck.Result.healthy("AsyncHealthCheckTest"); when(mockExecutorService.scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) .thenReturn(mockFuture); @@ -135,7 +148,7 @@ public void afterFirstExecutionDecoratedHealthCheckResultIsProvided() throws Exc @Test @SuppressWarnings("unchecked") - public void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { + void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exception { Exception exception = new Exception("TestException"); when(mockExecutorService.scheduleAtFixedRate(any(Runnable.class), eq(0L), eq(1L), eq(TimeUnit.SECONDS))) .thenReturn(mockFuture); @@ -155,10 +168,10 @@ public void exceptionInDecoratedHealthCheckWontAffectAsyncDecorator() throws Exc } @Test - public void returnUnhealthyIfPreviousResultIsExpiredBasedOnTtl() throws Exception { + void returnUnhealthyIfPreviousResultIsExpiredBasedOnTtl() throws Exception { HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredExplicitTtlInMilliseconds(); AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); - + ArgumentCaptor runnableCaptor = forClass(Runnable.class); verify(mockExecutorService, times(1)).scheduleAtFixedRate(runnableCaptor.capture(), eq(0L), eq(1000L), eq(TimeUnit.MILLISECONDS)); @@ -171,7 +184,7 @@ public void returnUnhealthyIfPreviousResultIsExpiredBasedOnTtl() throws Exceptio } @Test - public void returnUnhealthyIfPreviousResultIsExpiredBasedOnPeriod() throws Exception { + void returnUnhealthyIfPreviousResultIsExpiredBasedOnPeriod() throws Exception { HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredTtlInMillisecondsBasedOnPeriod(); AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); @@ -187,7 +200,7 @@ public void returnUnhealthyIfPreviousResultIsExpiredBasedOnPeriod() throws Excep } @Test - public void convertTtlToMillisecondsWhenCheckingExpiration() throws Exception { + void convertTtlToMillisecondsWhenCheckingExpiration() throws Exception { HealthCheck healthCheck = new HealthyAsyncHealthCheckWithExpiredExplicitTtlInSeconds(); AsyncHealthCheckDecorator asyncDecorator = new AsyncHealthCheckDecorator(healthCheck, mockExecutorService, FIXED_CLOCK); diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java index 2300433fcb..5fd9b785e6 100644 --- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java +++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckFilterTest.java @@ -3,12 +3,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class HealthCheckFilterTest { +class HealthCheckFilterTest { @Test - public void theAllFilterMatchesAllHealthChecks() { + void theAllFilterMatchesAllHealthChecks() { assertThat(HealthCheckFilter.ALL.matches("", mock(HealthCheck.class))).isTrue(); } } diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java index d160751933..2553b6ee11 100644 --- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java +++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckRegistryTest.java @@ -1,8 +1,8 @@ package io.dropwizard.metrics5.health; import io.dropwizard.metrics5.health.annotation.Async; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import java.util.Map; @@ -16,6 +16,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentCaptor.forClass; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -23,7 +24,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class HealthCheckRegistryTest { +class HealthCheckRegistryTest { private final ScheduledExecutorService executorService = mock(ScheduledExecutorService.class); private final HealthCheckRegistry registry = new HealthCheckRegistry(executorService); private final HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); @@ -40,15 +41,15 @@ public class HealthCheckRegistryTest { @SuppressWarnings("rawtypes") private final ScheduledFuture af = mock(ScheduledFuture.class); - @Before + @BeforeEach @SuppressWarnings("unchecked") - public void setUp() { + void setUp() { registry.addListener(listener); when(hc1.execute()).thenReturn(r1); when(hc2.execute()).thenReturn(r2); when(executorService.scheduleAtFixedRate(any(AsyncHealthCheckDecorator.class), eq(0L), eq(10L), eq(TimeUnit.SECONDS))) - .thenReturn(af); + .thenReturn(af); registry.register("hc1", hc1); registry.register("hc2", hc2); @@ -56,33 +57,35 @@ public void setUp() { } @Test - public void asyncHealthCheckIsScheduledOnExecutor() { + void asyncHealthCheckIsScheduledOnExecutor() { ArgumentCaptor decoratorCaptor = forClass(AsyncHealthCheckDecorator.class); verify(executorService).scheduleAtFixedRate(decoratorCaptor.capture(), eq(0L), eq(10L), eq(TimeUnit.SECONDS)); assertThat(decoratorCaptor.getValue().getHealthCheck()).isEqualTo(ahc); } @Test - public void asyncHealthCheckIsCanceledOnRemove() { + void asyncHealthCheckIsCanceledOnRemove() { registry.unregister("ahc"); verify(af).cancel(true); } - @Test(expected = IllegalArgumentException.class) - public void registeringHealthCheckTwiceThrowsException() { - registry.register("hc1", hc1); + @Test + void registeringHealthCheckTwiceThrowsException() { + assertThrows(IllegalArgumentException.class, () -> { + registry.register("hc1", hc1); + }); } @Test - public void registeringHealthCheckTriggersNotification() { + void registeringHealthCheckTriggersNotification() { verify(listener).onHealthCheckAdded("hc1", hc1); verify(listener).onHealthCheckAdded("hc2", hc2); verify(listener).onHealthCheckAdded(eq("ahc"), any(AsyncHealthCheckDecorator.class)); } @Test - public void removingHealthCheckTriggersNotification() { + void removingHealthCheckTriggersNotification() { registry.unregister("hc1"); registry.unregister("hc2"); registry.unregister("ahc"); @@ -93,7 +96,7 @@ public void removingHealthCheckTriggersNotification() { } @Test - public void addingListenerCatchesExistingHealthChecks() { + void addingListenerCatchesExistingHealthChecks() { HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); HealthCheckRegistry registry = new HealthCheckRegistry(); registry.register("hc1", hc1); @@ -107,7 +110,7 @@ public void addingListenerCatchesExistingHealthChecks() { } @Test - public void removedListenerDoesNotReceiveUpdates() { + void removedListenerDoesNotReceiveUpdates() { HealthCheckRegistryListener listener = mock(HealthCheckRegistryListener.class); HealthCheckRegistry registry = new HealthCheckRegistry(); registry.addListener(listener); @@ -119,7 +122,7 @@ public void removedListenerDoesNotReceiveUpdates() { } @Test - public void runsRegisteredHealthChecks() { + void runsRegisteredHealthChecks() { final Map results = registry.runHealthChecks(); assertThat(results).contains(entry("hc1", r1)); @@ -128,21 +131,21 @@ public void runsRegisteredHealthChecks() { } @Test - public void runsRegisteredHealthChecksWithFilter() { + void runsRegisteredHealthChecksWithFilter() { final Map results = registry.runHealthChecks((name, healthCheck) -> "hc1".equals(name)); assertThat(results).containsOnly(entry("hc1", r1)); } @Test - public void runsRegisteredHealthChecksWithNonMatchingFilter() { + void runsRegisteredHealthChecksWithNonMatchingFilter() { final Map results = registry.runHealthChecks((name, healthCheck) -> false); assertThat(results).isEmpty(); } @Test - public void runsRegisteredHealthChecksInParallel() throws Exception { + void runsRegisteredHealthChecksInParallel() throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(10); final Map results = registry.runHealthChecks(executor); @@ -155,7 +158,7 @@ public void runsRegisteredHealthChecksInParallel() throws Exception { } @Test - public void runsRegisteredHealthChecksInParallelWithNonMatchingFilter() throws Exception { + void runsRegisteredHealthChecksInParallelWithNonMatchingFilter() throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(10); final Map results = registry.runHealthChecks(executor, (name, healthCheck) -> false); @@ -166,10 +169,10 @@ public void runsRegisteredHealthChecksInParallelWithNonMatchingFilter() throws E } @Test - public void runsRegisteredHealthChecksInParallelWithFilter() throws Exception { + void runsRegisteredHealthChecksInParallelWithFilter() throws Exception { final ExecutorService executor = Executors.newFixedThreadPool(10); final Map results = registry.runHealthChecks(executor, - (name, healthCheck) -> "hc2".equals(name)); + (name, healthCheck) -> "hc2".equals(name)); executor.shutdown(); executor.awaitTermination(1, TimeUnit.SECONDS); @@ -178,7 +181,7 @@ public void runsRegisteredHealthChecksInParallelWithFilter() throws Exception { } @Test - public void removesRegisteredHealthChecks() { + void removesRegisteredHealthChecks() { registry.unregister("hc1"); final Map results = registry.runHealthChecks(); @@ -189,23 +192,23 @@ public void removesRegisteredHealthChecks() { } @Test - public void hasASetOfHealthCheckNames() { + void hasASetOfHealthCheckNames() { assertThat(registry.getNames()).containsOnly("hc1", "hc2", "ahc"); } @Test - public void runsHealthChecksByName() { + void runsHealthChecksByName() { assertThat(registry.runHealthCheck("hc1")).isEqualTo(r1); } @Test - public void doesNotRunNonexistentHealthChecks() { + void doesNotRunNonexistentHealthChecks() { try { registry.runHealthCheck("what"); failBecauseExceptionWasNotThrown(NoSuchElementException.class); } catch (NoSuchElementException e) { assertThat(e.getMessage()) - .isEqualTo("No health check named what exists"); + .isEqualTo("No health check named what exists"); } } diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java index 7db9d5abf7..8414ca9385 100644 --- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java +++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/HealthCheckTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5.health; import io.dropwizard.metrics5.Clock; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; @@ -12,7 +12,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class HealthCheckTest { +class HealthCheckTest { private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -34,7 +34,7 @@ public Result check() { private final HealthCheck healthCheck = new ExampleHealthCheck(underlying); @Test - public void canHaveHealthyResults() { + void canHaveHealthyResults() { final HealthCheck.Result result = HealthCheck.Result.healthy(); assertThat(result.isHealthy()) @@ -48,7 +48,7 @@ public void canHaveHealthyResults() { } @Test - public void canHaveHealthyResultsWithMessages() { + void canHaveHealthyResultsWithMessages() { final HealthCheck.Result result = HealthCheck.Result.healthy("woo"); assertThat(result.isHealthy()) @@ -62,7 +62,7 @@ public void canHaveHealthyResultsWithMessages() { } @Test - public void canHaveHealthyResultsWithFormattedMessages() { + void canHaveHealthyResultsWithFormattedMessages() { final HealthCheck.Result result = HealthCheck.Result.healthy("foo %s", "bar"); assertThat(result.isHealthy()) @@ -76,7 +76,7 @@ public void canHaveHealthyResultsWithFormattedMessages() { } @Test - public void canHaveUnhealthyResults() { + void canHaveUnhealthyResults() { final HealthCheck.Result result = HealthCheck.Result.unhealthy("bad"); assertThat(result.isHealthy()) @@ -90,7 +90,7 @@ public void canHaveUnhealthyResults() { } @Test - public void canHaveUnhealthyResultsWithFormattedMessages() { + void canHaveUnhealthyResultsWithFormattedMessages() { final HealthCheck.Result result = HealthCheck.Result.unhealthy("foo %s %d", "bar", 123); assertThat(result.isHealthy()) @@ -104,7 +104,7 @@ public void canHaveUnhealthyResultsWithFormattedMessages() { } @Test - public void canHaveUnhealthyResultsWithExceptions() { + void canHaveUnhealthyResultsWithExceptions() { final RuntimeException e = mock(RuntimeException.class); when(e.getMessage()).thenReturn("oh noes"); @@ -121,7 +121,7 @@ public void canHaveUnhealthyResultsWithExceptions() { } @Test - public void canHaveHealthyBuilderWithFormattedMessage() { + void canHaveHealthyBuilderWithFormattedMessage() { final HealthCheck.Result result = HealthCheck.Result.builder() .healthy() .withMessage("There are %d %s in the %s", 42, "foos", "bar") @@ -135,7 +135,7 @@ public void canHaveHealthyBuilderWithFormattedMessage() { } @Test - public void canHaveHealthyBuilderWithDetail() { + void canHaveHealthyBuilderWithDetail() { final HealthCheck.Result result = HealthCheck.Result.builder() .healthy() .withDetail("detail", "value") @@ -155,7 +155,7 @@ public void canHaveHealthyBuilderWithDetail() { } @Test - public void canHaveUnHealthyBuilderWithDetail() { + void canHaveUnHealthyBuilderWithDetail() { final HealthCheck.Result result = HealthCheck.Result.builder() .unhealthy() .withDetail("detail", "value") @@ -175,7 +175,7 @@ public void canHaveUnHealthyBuilderWithDetail() { } @Test - public void canHaveUnHealthyBuilderWithDetailAndError() { + void canHaveUnHealthyBuilderWithDetailAndError() { final RuntimeException e = mock(RuntimeException.class); when(e.getMessage()).thenReturn("oh noes"); @@ -199,7 +199,7 @@ public void canHaveUnHealthyBuilderWithDetailAndError() { } @Test - public void returnsResultsWhenExecuted() { + void returnsResultsWhenExecuted() { final HealthCheck.Result result = mock(HealthCheck.Result.class); when(underlying.execute()).thenReturn(result); @@ -210,7 +210,7 @@ public void returnsResultsWhenExecuted() { } @Test - public void wrapsExceptionsWhenExecuted() { + void wrapsExceptionsWhenExecuted() { final RuntimeException e = mock(RuntimeException.class); when(e.getMessage()).thenReturn("oh noes"); @@ -230,7 +230,7 @@ public void wrapsExceptionsWhenExecuted() { } @Test - public void canHaveUserSuppliedClockForTimestamp() { + void canHaveUserSuppliedClockForTimestamp() { ZonedDateTime dateTime = ZonedDateTime.now().minusMinutes(10); Clock clock = clockWithFixedTime(dateTime); @@ -248,7 +248,7 @@ public void canHaveUserSuppliedClockForTimestamp() { } @Test - public void toStringWorksEvenForNullAttributes() { + void toStringWorksEvenForNullAttributes() { ZonedDateTime dateTime = ZonedDateTime.now().minusMinutes(25); Clock clock = clockWithFixedTime(dateTime); diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java index c9ee6ac932..fbb6b419df 100644 --- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java +++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/SharedHealthCheckRegistriesTest.java @@ -1,27 +1,24 @@ package io.dropwizard.metrics5.health; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class SharedHealthCheckRegistriesTest { +class SharedHealthCheckRegistriesTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Before - public void setUp() { + @BeforeEach + void setUp() { SharedHealthCheckRegistries.setDefaultRegistryName(new AtomicReference<>()); SharedHealthCheckRegistries.clear(); } @Test - public void savesCreatedRegistry() { + void savesCreatedRegistry() { final HealthCheckRegistry one = SharedHealthCheckRegistries.getOrCreate("db"); final HealthCheckRegistry two = SharedHealthCheckRegistries.getOrCreate("db"); @@ -29,14 +26,14 @@ public void savesCreatedRegistry() { } @Test - public void returnsSetOfCreatedRegistries() { + void returnsSetOfCreatedRegistries() { SharedHealthCheckRegistries.getOrCreate("db"); assertThat(SharedHealthCheckRegistries.names()).containsOnly("db"); } @Test - public void registryCanBeRemoved() { + void registryCanBeRemoved() { final HealthCheckRegistry first = SharedHealthCheckRegistries.getOrCreate("db"); SharedHealthCheckRegistries.remove("db"); @@ -45,7 +42,7 @@ public void registryCanBeRemoved() { } @Test - public void registryCanBeCleared() { + void registryCanBeCleared() { SharedHealthCheckRegistries.getOrCreate("db"); SharedHealthCheckRegistries.getOrCreate("web"); @@ -55,22 +52,23 @@ public void registryCanBeCleared() { } @Test - public void defaultRegistryIsNotSetByDefault() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Default registry name has not been set."); + void defaultRegistryIsNotSetByDefault() { + Throwable exception = assertThrows(IllegalStateException.class, () -> { - SharedHealthCheckRegistries.getDefault(); + SharedHealthCheckRegistries.getDefault(); + }); + assertTrue(exception.getMessage().contains("Default registry name has not been set.")); } @Test - public void defaultRegistryCanBeSet() { + void defaultRegistryCanBeSet() { HealthCheckRegistry registry = SharedHealthCheckRegistries.setDefault("default"); assertThat(SharedHealthCheckRegistries.getDefault()).isEqualTo(registry); } @Test - public void specificRegistryCanBeSetAsDefault() { + void specificRegistryCanBeSetAsDefault() { HealthCheckRegistry registry = new HealthCheckRegistry(); SharedHealthCheckRegistries.setDefault("default", registry); @@ -78,20 +76,22 @@ public void specificRegistryCanBeSetAsDefault() { } @Test - public void unableToSetDefaultRegistryTwice() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Default health check registry is already set."); + void unableToSetDefaultRegistryTwice() { + Throwable exception = assertThrows(IllegalStateException.class, () -> { - SharedHealthCheckRegistries.setDefault("default"); - SharedHealthCheckRegistries.setDefault("default"); + SharedHealthCheckRegistries.setDefault("default"); + SharedHealthCheckRegistries.setDefault("default"); + }); + assertTrue(exception.getMessage().contains("Default health check registry is already set.")); } @Test - public void unableToSetCustomDefaultRegistryTwice() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Default health check registry is already set."); + void unableToSetCustomDefaultRegistryTwice() { + Throwable exception = assertThrows(IllegalStateException.class, () -> { - SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); - SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); + SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); + SharedHealthCheckRegistries.setDefault("default", new HealthCheckRegistry()); + }); + assertTrue(exception.getMessage().contains("Default health check registry is already set.")); } } diff --git a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java index cafc53d7a9..03cd432af5 100644 --- a/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java +++ b/metrics-healthchecks/src/test/java/io/dropwizard/metrics5/health/jvm/ThreadDeadlockHealthCheckTest.java @@ -3,7 +3,7 @@ import io.dropwizard.metrics5.health.HealthCheck; import io.dropwizard.metrics5.jvm.ThreadDeadlockDetector; import org.assertj.core.api.Assertions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Set; @@ -13,9 +13,9 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ThreadDeadlockHealthCheckTest { +class ThreadDeadlockHealthCheckTest { @Test - public void isHealthyIfNoThreadsAreDeadlocked() { + void isHealthyIfNoThreadsAreDeadlocked() { final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(detector); @@ -26,7 +26,7 @@ public void isHealthyIfNoThreadsAreDeadlocked() { } @Test - public void isUnhealthyIfThreadsAreDeadlocked() { + void isUnhealthyIfThreadsAreDeadlocked() { final Set threads = new TreeSet<>(); threads.add("one"); threads.add("two"); @@ -46,7 +46,7 @@ public void isUnhealthyIfThreadsAreDeadlocked() { } @Test - public void automaticallyUsesThePlatformThreadBeans() { + void automaticallyUsesThePlatformThreadBeans() { final ThreadDeadlockHealthCheck healthCheck = new ThreadDeadlockHealthCheck(); Assertions.assertThat(healthCheck.execute().isHealthy()) .isTrue(); diff --git a/metrics-httpasyncclient/pom.xml b/metrics-httpasyncclient/pom.xml index e843252e62..2ac9ffc94f 100644 --- a/metrics-httpasyncclient/pom.xml +++ b/metrics-httpasyncclient/pom.xml @@ -80,24 +80,36 @@ org.apache.httpcomponents httpcore-nio - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core ${mockito.version} test + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + org.slf4j slf4j-simple diff --git a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/HttpClientTestBase.java b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/HttpClientTestBase.java index 2ee9fc1084..8d8df1ca13 100644 --- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/HttpClientTestBase.java +++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/HttpClientTestBase.java @@ -6,7 +6,7 @@ import org.apache.http.nio.protocol.BasicAsyncRequestHandler; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.protocol.HttpRequestHandler; -import org.junit.After; +import org.junit.jupiter.api.AfterEach; import java.io.IOException; import java.net.InetSocketAddress; @@ -36,7 +36,7 @@ public static int findAvailableLocalPort() { /** * Start a local server that uses the {@code handler} to handle requests. *

- * The server will be (if started) terminated in the {@link #tearDown()} {@link After} method. + * The server will be (if started) terminated in the {@link #tearDown()} {@link AfterEach} method. * * @param handler The request handler that will be used to respond to every request. * @return The {@link HttpHost} of the server @@ -62,7 +62,7 @@ public HttpHost startServerWithGlobalRequestHandler(HttpRequestHandler handler) return new HttpHost("localhost", address.getPort(), "http"); } - @After + @AfterEach public void tearDown() { if (server != null) { server.shutdown(5, TimeUnit.SECONDS); diff --git a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java index a0471cd004..0e36f5611b 100644 --- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java +++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTest.java @@ -10,11 +10,11 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.nio.client.HttpAsyncClient; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -22,8 +22,8 @@ import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -public class InstrumentedHttpClientsTest extends HttpClientTestBase { +@ExtendWith(MockitoExtension.class) +class InstrumentedHttpClientsTest extends HttpClientTestBase { private final MetricRegistry metricRegistry = new MetricRegistry(); @@ -35,21 +35,21 @@ public class InstrumentedHttpClientsTest extends HttpClientTestBase { private MetricRegistryListener registryListener; @Test - public void registersExpectedMetricsGivenNameStrategy() throws Exception { + void registersExpectedMetricsGivenNameStrategy() throws Exception { HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); final HttpGet get = new HttpGet("/q=anything"); final MetricName metricName = MetricName.build("some.made.up.metric.name"); when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))) - .thenReturn(metricName); + .thenReturn(metricName); asyncHttpClient.execute(host, get, null).get(); verify(registryListener).onTimerAdded(eq(metricName), any(Timer.class)); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { CloseableHttpAsyncClient chac = new InstrumentedNHttpClientBuilder(metricRegistry, metricNameStrategy).build(); chac.start(); asyncHttpClient = chac; diff --git a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java index 8c251df6d5..e1c8d9dfa8 100644 --- a/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java +++ b/metrics-httpasyncclient/src/test/java/io/dropwizard/metrics5/httpasyncclient/InstrumentedHttpClientsTimerTest.java @@ -9,18 +9,18 @@ import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.nio.client.HttpAsyncClient; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -28,9 +28,9 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -@Ignore("The tests are flaky") -public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { +@ExtendWith(MockitoExtension.class) +@Disabled("The tests are flaky") +class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { private HttpAsyncClient asyncHttpClient; @@ -41,10 +41,10 @@ public class InstrumentedHttpClientsTimerTest extends HttpClientTestBase { private MetricRegistry metricRegistry; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { CloseableHttpAsyncClient chac = new InstrumentedNHttpClientBuilder(metricRegistry, - (name, request) -> MetricName.build("test")).build(); + (name, request) -> MetricName.build("test")).build(); chac.start(); asyncHttpClient = chac; @@ -54,7 +54,7 @@ public void setUp() throws Exception { } @Test - public void timerIsStoppedCorrectly() throws Exception { + void timerIsStoppedCorrectly() throws Exception { HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); HttpGet get = new HttpGet("/?q=anything"); @@ -76,7 +76,7 @@ public void timerIsStoppedCorrectly() throws Exception { @Test @SuppressWarnings("unchecked") - public void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { + void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws Exception { HttpHost host = startServerWithGlobalRequestHandler(STATUS_OK); HttpGet get = new HttpGet("/?q=something"); @@ -103,7 +103,7 @@ public void timerIsStoppedCorrectlyWithProvidedFutureCallbackCompleted() throws @Test @SuppressWarnings("unchecked") - public void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { + void timerIsStoppedCorrectlyWithProvidedFutureCallbackFailed() throws Exception { // There should be nothing listening on this port HttpHost host = HttpHost.create(String.format("http://127.0.0.1:%d", findAvailableLocalPort())); HttpGet get = new HttpGet("/?q=something"); diff --git a/metrics-httpclient/pom.xml b/metrics-httpclient/pom.xml index 98130211de..bc86ec5915 100644 --- a/metrics-httpclient/pom.xml +++ b/metrics-httpclient/pom.xml @@ -57,18 +57,24 @@ httpclient ${http-client.version} - - junit - junit - ${junit.version} - test - org.hamcrest hamcrest-core ${hamcrest.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.assertj assertj-core diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java index 7ce201674a..7c2b77285b 100644 --- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java +++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/HttpClientMetricNameStrategiesTest.java @@ -7,7 +7,7 @@ import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestWrapper; import org.apache.http.client.utils.URIUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.net.URI; import java.net.URISyntaxException; @@ -17,36 +17,36 @@ import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.PATH_AND_METHOD; import static io.dropwizard.metrics5.httpclient.HttpClientMetricNameStrategies.QUERYLESS_URL_AND_METHOD; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; -public class HttpClientMetricNameStrategiesTest { +class HttpClientMetricNameStrategiesTest { @Test - public void methodOnlyWithName() { + void methodOnlyWithName() { assertThat(METHOD_ONLY.getNameFor("some-service", new HttpGet("/whatever")), is(MetricName.build("org.apache.http.client.HttpClient.some-service.get-requests"))); } @Test - public void methodOnlyWithoutName() { + void methodOnlyWithoutName() { assertThat(METHOD_ONLY.getNameFor(null, new HttpGet("/whatever")), is(MetricName.build("org.apache.http.client.HttpClient.get-requests"))); } @Test - public void hostAndMethodWithName() { + void hostAndMethodWithName() { assertThat(HOST_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever")), is(MetricName.build("org.apache.http.client.HttpClient.some-service.my.host.com.post-requests"))); } @Test - public void hostAndMethodWithoutName() { + void hostAndMethodWithoutName() { assertThat(HOST_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever")), is(MetricName.build("org.apache.http.client.HttpClient.my.host.com.post-requests"))); } @Test - public void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { + void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); assertThat(HOST_AND_METHOD.getNameFor("some-service", request), @@ -54,7 +54,7 @@ public void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { } @Test - public void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { + void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); assertThat(HOST_AND_METHOD.getNameFor(null, request), @@ -62,45 +62,45 @@ public void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException } @Test - public void pathAndMethodWithName() { + void pathAndMethodWithName() { assertThat(PATH_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever/happens")), is(MetricName.build("org.apache.http.client.HttpClient.some-service./whatever/happens.post-requests"))); } @Test - public void pathAndMethodWithoutName() { + void pathAndMethodWithoutName() { assertThat(PATH_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever/happens")), is(MetricName.build("org.apache.http.client.HttpClient./whatever/happens.post-requests"))); } @Test - public void pathAndMethodWithNameInWrappedRequest() throws URISyntaxException { + void pathAndMethodWithNameInWrappedRequest() throws URISyntaxException { HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever/happens")); assertThat(PATH_AND_METHOD.getNameFor("some-service", request), is(MetricName.build("org.apache.http.client.HttpClient.some-service./whatever/happens.post-requests"))); } @Test - public void pathAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { + void pathAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever/happens")); assertThat(PATH_AND_METHOD.getNameFor(null, request), is(MetricName.build("org.apache.http.client.HttpClient./whatever/happens.post-requests"))); } @Test - public void querylessUrlAndMethodWithName() { + void querylessUrlAndMethodWithName() { assertThat(QUERYLESS_URL_AND_METHOD.getNameFor( - "some-service", - new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")), + "some-service", + new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")), is(MetricName.build("org.apache.http.client.HttpClient.some-service.https://thing.com:8090/my/path.put-requests"))); } @Test - public void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { + void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { HttpRequest request = rewriteRequestURI(new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")); assertThat(QUERYLESS_URL_AND_METHOD.getNameFor( - "some-service", - request), + "some-service", + request), is(MetricName.build("org.apache.http.client.HttpClient.some-service.https://thing.com:8090/my/path.put-requests"))); } diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java index 40d6ec9502..ee5bfcad45 100644 --- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java +++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientConnectionManagerTest.java @@ -2,22 +2,22 @@ import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import static junit.framework.TestCase.assertTrue; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; -public class InstrumentedHttpClientConnectionManagerTest { +class InstrumentedHttpClientConnectionManagerTest { private final MetricRegistry metricRegistry = new MetricRegistry(); @Test - public void shouldRemoveGauges() { + void shouldRemoveGauges() { final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); assertThat(metricRegistry.getGauges().entrySet().stream() .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) @@ -27,14 +27,14 @@ public void shouldRemoveGauges() { entry("org.apache.http.conn.HttpClientConnectionManager.pending-connections", 0)); instrumentedHttpClientConnectionManager.close(); - Assert.assertEquals(0, metricRegistry.getGauges().size()); + assertEquals(0, metricRegistry.getGauges().size()); // should be able to create another one with the same name ("") InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); } @Test - public void configurableViaBuilder() { + void configurableViaBuilder() { final MetricRegistry registry = Mockito.mock(MetricRegistry.class); InstrumentedHttpClientConnectionManager.builder(registry) diff --git a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java index 0b9014c950..db4f2296dd 100644 --- a/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java +++ b/metrics-httpclient/src/test/java/io/dropwizard/metrics5/httpclient/InstrumentedHttpClientsTest.java @@ -10,20 +10,20 @@ import org.apache.http.NoHttpResponseException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.net.InetSocketAddress; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class InstrumentedHttpClientsTest { +class InstrumentedHttpClientsTest { private final HttpClientMetricNameStrategy metricNameStrategy = mock(HttpClientMetricNameStrategy.class); private final MetricRegistryListener registryListener = @@ -32,13 +32,13 @@ public class InstrumentedHttpClientsTest { private final HttpClient client = InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); - @Before - public void setUp() { + @BeforeEach + void setUp() { metricRegistry.addListener(registryListener); } @Test - public void registersExpectedMetricsGivenNameStrategy() throws Exception { + void registersExpectedMetricsGivenNameStrategy() throws Exception { final HttpGet get = new HttpGet("http://example.com?q=anything"); final MetricName metricName = MetricName.build("some.made.up.metric.name"); @@ -51,7 +51,7 @@ public void registersExpectedMetricsGivenNameStrategy() throws Exception { } @Test - public void registersExpectedExceptionMetrics() throws Exception { + void registersExpectedExceptionMetrics() throws Exception { HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/"); diff --git a/metrics-httpclient5/pom.xml b/metrics-httpclient5/pom.xml index 2645e0b8df..bbe121818b 100644 --- a/metrics-httpclient5/pom.xml +++ b/metrics-httpclient5/pom.xml @@ -67,18 +67,24 @@ org.apache.httpcomponents.core5 httpcore5 - - junit - junit - ${junit.version} - test - org.hamcrest hamcrest-core ${hamcrest.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.assertj assertj-core @@ -91,6 +97,12 @@ ${mockito.version} test + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + org.slf4j slf4j-simple diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java index 5bf43df541..40e9c36315 100644 --- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java +++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/HttpClientMetricNameStrategiesTest.java @@ -7,7 +7,7 @@ import org.apache.hc.client5.http.utils.URIUtils; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.message.HttpRequestWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.net.URI; import java.net.URISyntaxException; @@ -16,36 +16,36 @@ import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.METHOD_ONLY; import static io.dropwizard.metrics5.httpclient5.HttpClientMetricNameStrategies.QUERYLESS_URL_AND_METHOD; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; -public class HttpClientMetricNameStrategiesTest { +class HttpClientMetricNameStrategiesTest { @Test - public void methodOnlyWithName() { + void methodOnlyWithName() { assertThat(METHOD_ONLY.getNameFor("some-service", new HttpGet("/whatever")), is(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.get-requests"))); } @Test - public void methodOnlyWithoutName() { + void methodOnlyWithoutName() { assertThat(METHOD_ONLY.getNameFor(null, new HttpGet("/whatever")), is(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.get-requests"))); } @Test - public void hostAndMethodWithName() { + void hostAndMethodWithName() { assertThat(HOST_AND_METHOD.getNameFor("some-service", new HttpPost("http://my.host.com/whatever")), is(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.my.host.com.post-requests"))); } @Test - public void hostAndMethodWithoutName() { + void hostAndMethodWithoutName() { assertThat(HOST_AND_METHOD.getNameFor(null, new HttpPost("http://my.host.com/whatever")), is(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.my.host.com.post-requests"))); } @Test - public void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { + void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); assertThat(HOST_AND_METHOD.getNameFor("some-service", request), @@ -53,7 +53,7 @@ public void hostAndMethodWithNameInWrappedRequest() throws URISyntaxException { } @Test - public void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { + void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException { HttpRequest request = rewriteRequestURI(new HttpPost("http://my.host.com/whatever")); assertThat(HOST_AND_METHOD.getNameFor(null, request), @@ -61,19 +61,19 @@ public void hostAndMethodWithoutNameInWrappedRequest() throws URISyntaxException } @Test - public void querylessUrlAndMethodWithName() { + void querylessUrlAndMethodWithName() { assertThat(QUERYLESS_URL_AND_METHOD.getNameFor( - "some-service", - new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")), + "some-service", + new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")), is(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.https://thing.com:8090/my/path.put-requests"))); } @Test - public void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { + void querylessUrlAndMethodWithNameInWrappedRequest() throws URISyntaxException { HttpRequest request = rewriteRequestURI(new HttpPut("https://thing.com:8090/my/path?ignore=this&and=this")); assertThat(QUERYLESS_URL_AND_METHOD.getNameFor( - "some-service", - request), + "some-service", + request), is(MetricName.build("org.apache.hc.client5.http.classic.HttpClient.some-service.https://thing.com:8090/my/path.put-requests"))); } diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java index 5f1d79d924..860640e078 100644 --- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java +++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedAsyncClientConnectionManagerTest.java @@ -2,21 +2,21 @@ import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import static junit.framework.TestCase.assertTrue; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; -public class InstrumentedAsyncClientConnectionManagerTest { +class InstrumentedAsyncClientConnectionManagerTest { private final MetricRegistry metricRegistry = new MetricRegistry(); @Test - public void shouldRemoveGauges() { + void shouldRemoveGauges() { final InstrumentedAsyncClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedAsyncClientConnectionManager.builder(metricRegistry).build(); assertThat(metricRegistry.getGauges().entrySet().stream() .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) @@ -26,14 +26,14 @@ public void shouldRemoveGauges() { entry("org.apache.hc.client5.http.nio.AsyncClientConnectionManager.pending-connections", 0)); instrumentedHttpClientConnectionManager.close(); - Assert.assertEquals(0, metricRegistry.getGauges().size()); + assertEquals(0, metricRegistry.getGauges().size()); // should be able to create another one with the same name ("") InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); } @Test - public void configurableViaBuilder() { + void configurableViaBuilder() { final MetricRegistry registry = Mockito.mock(MetricRegistry.class); InstrumentedAsyncClientConnectionManager.builder(registry) diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java index 3933f55ec6..7c9f443013 100644 --- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java +++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpAsyncClientsTest.java @@ -14,13 +14,12 @@ import org.apache.hc.core5.concurrent.FutureCallback; import org.apache.hc.core5.http.ConnectionClosedException; import org.apache.hc.core5.http.HttpRequest; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; import java.net.InetSocketAddress; @@ -32,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; @@ -40,9 +39,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class InstrumentedHttpAsyncClientsTest { - @Rule - public final MockitoRule mockitoRule = MockitoJUnit.rule(); +@ExtendWith(MockitoExtension.class) +class InstrumentedHttpAsyncClientsTest { @Mock private HttpClientMetricNameStrategy metricNameStrategy; @@ -52,16 +50,16 @@ public class InstrumentedHttpAsyncClientsTest { private MetricRegistry metricRegistry; private CloseableHttpAsyncClient client; - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { httpServer = HttpServer.create(new InetSocketAddress(0), 0); metricRegistry = new MetricRegistry(); metricRegistry.addListener(registryListener); } - @After - public void tearDown() throws IOException { + @AfterEach + void tearDown() throws IOException { if (client != null) { client.close(); } @@ -71,7 +69,7 @@ public void tearDown() throws IOException { } @Test - public void registersExpectedMetricsGivenNameStrategy() throws Exception { + void registersExpectedMetricsGivenNameStrategy() throws Exception { client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); client.start(); @@ -110,7 +108,7 @@ public void cancelled() { } @Test - public void registersExpectedExceptionMetrics() throws Exception { + void registersExpectedExceptionMetrics() throws Exception { client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); client.start(); @@ -156,43 +154,43 @@ public void cancelled() { } @Test - public void usesCustomClientConnectionManager() throws Exception { - try(PoolingAsyncClientConnectionManager clientConnectionManager = spy(new PoolingAsyncClientConnectionManager())) { - client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy, clientConnectionManager).disableAutomaticRetries().build(); - client.start(); - - final SimpleHttpRequest request = SimpleHttpRequests.get("http://localhost:" + httpServer.getAddress().getPort() + "/"); - final MetricName metricName = MetricName.build("some.made.up.metric.name"); - - httpServer.createContext("/", exchange -> { - exchange.sendResponseHeaders(200, 0L); - exchange.setStreams(null, null); - exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); - exchange.close(); - }); - httpServer.start(); + void usesCustomClientConnectionManager() throws Exception { + try (PoolingAsyncClientConnectionManager clientConnectionManager = spy(new PoolingAsyncClientConnectionManager())) { + client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy, clientConnectionManager).disableAutomaticRetries().build(); + client.start(); + + final SimpleHttpRequest request = SimpleHttpRequests.get("http://localhost:" + httpServer.getAddress().getPort() + "/"); + final MetricName metricName = MetricName.build("some.made.up.metric.name"); + + httpServer.createContext("/", exchange -> { + exchange.sendResponseHeaders(200, 0L); + exchange.setStreams(null, null); + exchange.getResponseBody().write("TEST".getBytes(StandardCharsets.US_ASCII)); + exchange.close(); + }); + httpServer.start(); - when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); + when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(metricName); - final Future responseFuture = client.execute(request, new FutureCallback() { - @Override - public void completed(SimpleHttpResponse result) { - assertThat(result.getCode()).isEqualTo(200); - } + final Future responseFuture = client.execute(request, new FutureCallback() { + @Override + public void completed(SimpleHttpResponse result) { + assertThat(result.getCode()).isEqualTo(200); + } - @Override - public void failed(Exception ex) { - fail(); - } + @Override + public void failed(Exception ex) { + fail(); + } - @Override - public void cancelled() { - fail(); - } - }); - responseFuture.get(1L, TimeUnit.SECONDS); + @Override + public void cancelled() { + fail(); + } + }); + responseFuture.get(1L, TimeUnit.SECONDS); - verify(clientConnectionManager, atLeastOnce()).connect(any(), any(), any(), any(), any(), any()); + verify(clientConnectionManager, atLeastOnce()).connect(any(), any(), any(), any(), any(), any()); } } } diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java index 613af8b015..1667d8ff6a 100644 --- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java +++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientConnectionManagerTest.java @@ -2,21 +2,21 @@ import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import static junit.framework.TestCase.assertTrue; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; -public class InstrumentedHttpClientConnectionManagerTest { +class InstrumentedHttpClientConnectionManagerTest { private final MetricRegistry metricRegistry = new MetricRegistry(); @Test - public void shouldRemoveGauges() { + void shouldRemoveGauges() { final InstrumentedHttpClientConnectionManager instrumentedHttpClientConnectionManager = InstrumentedHttpClientConnectionManager.builder(metricRegistry).build(); assertThat(metricRegistry.getGauges().entrySet().stream() .map(e -> entry(e.getKey().getKey(), (Integer) e.getValue().getValue()))) @@ -26,14 +26,14 @@ public void shouldRemoveGauges() { entry("org.apache.hc.client5.http.io.HttpClientConnectionManager.pending-connections", 0)); instrumentedHttpClientConnectionManager.close(); - Assert.assertEquals(0, metricRegistry.getGauges().size()); + assertEquals(0, metricRegistry.getGauges().size()); // should be able to create another one with the same name ("") InstrumentedHttpClientConnectionManager.builder(metricRegistry).build().close(); } @Test - public void configurableViaBuilder() { + void configurableViaBuilder() { final MetricRegistry registry = Mockito.mock(MetricRegistry.class); InstrumentedHttpClientConnectionManager.builder(registry) diff --git a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java index 28126fc1cc..bca1d02bf4 100644 --- a/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java +++ b/metrics-httpclient5/src/test/java/io/dropwizard/metrics5/httpclient5/InstrumentedHttpClientsTest.java @@ -10,20 +10,20 @@ import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.NoHttpResponseException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.net.InetSocketAddress; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class InstrumentedHttpClientsTest { +class InstrumentedHttpClientsTest { private final HttpClientMetricNameStrategy metricNameStrategy = mock(HttpClientMetricNameStrategy.class); private final MetricRegistryListener registryListener = @@ -32,13 +32,13 @@ public class InstrumentedHttpClientsTest { private final HttpClient client = InstrumentedHttpClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build(); - @Before - public void setUp() { + @BeforeEach + void setUp() { metricRegistry.addListener(registryListener); } @Test - public void registersExpectedMetricsGivenNameStrategy() throws Exception { + void registersExpectedMetricsGivenNameStrategy() throws Exception { final HttpGet get = new HttpGet("http://example.com?q=anything"); final MetricName metricName = MetricName.build("some.made.up.metric.name"); @@ -51,7 +51,7 @@ public void registersExpectedMetricsGivenNameStrategy() throws Exception { } @Test - public void registersExpectedExceptionMetrics() throws Exception { + void registersExpectedExceptionMetrics() throws Exception { HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/"); diff --git a/metrics-influxdb/pom.xml b/metrics-influxdb/pom.xml index de6157c834..6303a57adb 100644 --- a/metrics-influxdb/pom.xml +++ b/metrics-influxdb/pom.xml @@ -46,18 +46,24 @@ slf4j-api ${slf4j.version} - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core diff --git a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java index f16c88ac6a..bd740a7844 100644 --- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java +++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbLineBuilderAssumptionsTest.java @@ -1,14 +1,14 @@ package io.dropwizard.metrics5.influxdb; import io.dropwizard.metrics5.MetricAttribute; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class InfluxDbLineBuilderAssumptionsTest { +class InfluxDbLineBuilderAssumptionsTest { @Test - public void ensureMetricAttributeCodesAreSafeFieldKeys() { + void ensureMetricAttributeCodesAreSafeFieldKeys() { for (MetricAttribute ma : MetricAttribute.values()) { String code = ma.getCode(); assertThat(code).doesNotContainPattern("[,= ]"); diff --git a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java index 17df53b151..a2646d071d 100644 --- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java +++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbReporterTest.java @@ -11,8 +11,9 @@ import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.Snapshot; import io.dropwizard.metrics5.Timer; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import org.mockito.InOrder; import java.io.IOException; @@ -37,7 +38,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -public class InfluxDbReporterTest { +class InfluxDbReporterTest { private static final MetricName GAUGE = MetricName.build("gauge"); private static final MetricName METER = MetricName.build("meter"); private static final MetricName COUNTER = MetricName.build("counter"); @@ -66,8 +67,8 @@ public class InfluxDbReporterTest { .disabledMetricAttributes(Collections.emptySet()) .build(sender); - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { when(clock.getTime()).thenReturn(timestamp * 1000); send.clear(); doAnswer(invocation -> send.add(invocation.getArgument(0).toString())) @@ -75,7 +76,7 @@ public void setUp() throws IOException { } @Test - public void reportsStringGaugeValues() throws Exception { + void reportsStringGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge("value")), map(), map(), @@ -93,7 +94,7 @@ public void reportsStringGaugeValues() throws Exception { } @Test - public void reportsByteGaugeValues() throws Exception { + void reportsByteGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge((byte) 1)), map(), map(), @@ -111,7 +112,7 @@ public void reportsByteGaugeValues() throws Exception { } @Test - public void reportsShortGaugeValues() throws Exception { + void reportsShortGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge((short) 1)), map(), map(), @@ -129,7 +130,7 @@ public void reportsShortGaugeValues() throws Exception { } @Test - public void reportsIntegerGaugeValues() throws Exception { + void reportsIntegerGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge(1)), map(), map(), @@ -147,7 +148,7 @@ public void reportsIntegerGaugeValues() throws Exception { } @Test - public void reportsLongGaugeValues() throws Exception { + void reportsLongGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge(1L)), map(), map(), @@ -165,7 +166,7 @@ public void reportsLongGaugeValues() throws Exception { } @Test - public void reportsFloatGaugeValues() throws Exception { + void reportsFloatGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge(1.5f)), map(), map(), @@ -183,7 +184,7 @@ public void reportsFloatGaugeValues() throws Exception { } @Test - public void reportsDoubleGaugeValues() throws Exception { + void reportsDoubleGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge(1.1)), map(), map(), @@ -201,7 +202,7 @@ public void reportsDoubleGaugeValues() throws Exception { } @Test - public void reportsBooleanGaugeValues() throws Exception { + void reportsBooleanGaugeValues() throws Exception { reporter.report(map(GAUGE, gauge(true)), map(), map(), @@ -231,7 +232,7 @@ public void reportsBooleanGaugeValues() throws Exception { } @Test - public void reportsCounters() throws Exception { + void reportsCounters() throws Exception { final Counter counter = mock(Counter.class); when(counter.getCount()).thenReturn(100L); @@ -252,7 +253,7 @@ public void reportsCounters() throws Exception { } @Test - public void reportsHistograms() throws Exception { + void reportsHistograms() throws Exception { final Histogram histogram = mock(Histogram.class); when(histogram.getCount()).thenReturn(1L); when(histogram.getSum()).thenReturn(12L); @@ -289,7 +290,7 @@ public void reportsHistograms() throws Exception { } @Test - public void reportsMeters() throws Exception { + void reportsMeters() throws Exception { final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getSum()).thenReturn(6L); @@ -315,7 +316,7 @@ public void reportsMeters() throws Exception { } @Test - public void reportsMetersInMinutes() throws Exception { + void reportsMetersInMinutes() throws Exception { final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getSum()).thenReturn(6L); @@ -341,7 +342,7 @@ public void reportsMetersInMinutes() throws Exception { } @Test - public void reportsTimers() throws Exception { + void reportsTimers() throws Exception { final Timer timer = mock(Timer.class); when(timer.getCount()).thenReturn(1L); when(timer.getSum()).thenReturn(6L); @@ -384,7 +385,7 @@ public void reportsTimers() throws Exception { } @Test - public void disconnectsIfSenderIsUnavailable() throws Exception { + void disconnectsIfSenderIsUnavailable() throws Exception { doThrow(new UnknownHostException("UNKNOWN-HOST")).when(sender).connect(); reporter.report(map(GAUGE, gauge(1)), map(), @@ -401,14 +402,14 @@ public void disconnectsIfSenderIsUnavailable() throws Exception { } @Test - public void closesConnectionOnReporterStop() throws Exception { + void closesConnectionOnReporterStop() throws Exception { reporter.stop(); verify(sender).close(); } @Test - public void disabledMetricsAttribute() throws Exception { + void disabledMetricsAttribute() throws Exception { final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getSum()).thenReturn(6L); diff --git a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java index 381e0cacee..2a48e5dac6 100644 --- a/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java +++ b/metrics-influxdb/src/test/java/io/dropwizard/metrics5/influxdb/InfluxDbUdpTest.java @@ -2,7 +2,9 @@ import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import org.mockito.Mockito; import java.net.SocketAddress; @@ -13,14 +15,12 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Before; - import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.times; -public class InfluxDbUdpTest { +class InfluxDbUdpTest { private final String host = "example.com"; private final int port = 1234; @@ -29,8 +29,8 @@ public class InfluxDbUdpTest { private final DatagramChannel datagramChannel = Mockito.mock(DatagramChannel.class); private final List sent = new ArrayList<>(); - @Before - public void setUp() throws IOException { + @BeforeEach + void setUp() throws IOException { sent.clear(); doAnswer(invocation -> { sent.add(toBytes(invocation.getArgument(0))); @@ -41,7 +41,7 @@ public void setUp() throws IOException { } @Test - public void writesValue() throws Exception { + void writesValue() throws Exception { influxdbUdp.send(new StringBuilder("räksmörgås value=123 456000000000\n")); influxdbUdp.flush(); @@ -51,7 +51,7 @@ public void writesValue() throws Exception { } @Test - public void batchesValues() throws Exception { + void batchesValues() throws Exception { influxdbUdp.send(new StringBuilder("name1 value=111 456000000000\n")); influxdbUdp.send(new StringBuilder("name2 value=222 456000000000\n")); influxdbUdp.flush(); @@ -63,7 +63,7 @@ public void batchesValues() throws Exception { } @Test - public void respectsMTU() throws Exception { + void respectsMTU() throws Exception { influxdbUdp.setMTU(40); influxdbUdp.send(new StringBuilder("name1 value=111 456000000000\n")); influxdbUdp.send(new StringBuilder("name2 value=222 456000000000\n")); diff --git a/metrics-jakarta-servlet/pom.xml b/metrics-jakarta-servlet/pom.xml index 59ba780758..b9977fe12b 100644 --- a/metrics-jakarta-servlet/pom.xml +++ b/metrics-jakarta-servlet/pom.xml @@ -44,9 +44,15 @@ provided - junit - junit - ${junit.version} + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} test diff --git a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java index 04c0fc4102..eff60dae11 100644 --- a/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java +++ b/metrics-jakarta-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java @@ -3,13 +3,13 @@ import io.dropwizard.metrics5.MetricRegistry; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletContextEvent; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class InstrumentedFilterContextListenerTest { +class InstrumentedFilterContextListenerTest { private final MetricRegistry registry = mock(MetricRegistry.class); private final InstrumentedFilterContextListener listener = new InstrumentedFilterContextListener() { @Override @@ -19,7 +19,7 @@ protected MetricRegistry getMetricRegistry() { }; @Test - public void injectsTheMetricRegistryIntoTheServletContext() { + void injectsTheMetricRegistryIntoTheServletContext() { final ServletContext context = mock(ServletContext.class); final ServletContextEvent event = mock(ServletContextEvent.class); diff --git a/metrics-jakarta-servlets/pom.xml b/metrics-jakarta-servlets/pom.xml index caaf2c0eb8..e5d856b90c 100644 --- a/metrics-jakarta-servlets/pom.xml +++ b/metrics-jakarta-servlets/pom.xml @@ -104,12 +104,6 @@ jackson-databind ${jackson.version} - - junit - junit - ${junit.version} - test - org.assertj assertj-core @@ -149,6 +143,18 @@ jetty-util test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.eclipse.jetty jetty-server diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java index d412f899e2..d341826c76 100644 --- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java +++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java @@ -2,15 +2,15 @@ import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; public abstract class AbstractServletTest { private final ServletTester tester = new ServletTester(); protected final HttpTester.Request request = HttpTester.newRequest(); protected HttpTester.Response response; - @Before + @BeforeEach public void setUpTester() throws Exception { setUp(tester); tester.start(); @@ -18,7 +18,7 @@ public void setUpTester() throws Exception { protected abstract void setUp(ServletTester tester); - @After + @AfterEach public void tearDownTester() throws Exception { tester.stop(); } diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java index 7de99acd3a..7765798711 100755 --- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java +++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletExclusionTest.java @@ -5,10 +5,10 @@ import static org.assertj.core.api.Assertions.assertThat; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class AdminServletExclusionTest extends AbstractServletTest { +class AdminServletExclusionTest extends AbstractServletTest { private final MetricRegistry registry = new MetricRegistry(); private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); @@ -23,15 +23,15 @@ protected void setUp(ServletTester tester) { tester.addServlet(AdminServlet.class, "/admin"); } - @Before - public void setUp() { + @BeforeEach + void setUp() { request.setMethod("GET"); request.setURI("/context/admin"); request.setVersion("HTTP/1.0"); } @Test - public void returnsA200() throws Exception { + void returnsA200() throws Exception { processRequest(); assertThat(response.getStatus()) diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java index 90d36c408c..a34753384e 100755 --- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java +++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java @@ -4,12 +4,12 @@ import io.dropwizard.metrics5.health.HealthCheckRegistry; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class AdminServletTest extends AbstractServletTest { +class AdminServletTest extends AbstractServletTest { private final MetricRegistry registry = new MetricRegistry(); private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); @@ -22,15 +22,15 @@ protected void setUp(ServletTester tester) { tester.addServlet(AdminServlet.class, "/admin"); } - @Before - public void setUp() { + @BeforeEach + void setUp() { request.setMethod("GET"); request.setURI("/context/admin"); request.setVersion("HTTP/1.0"); } @Test - public void returnsA200() throws Exception { + void returnsA200() throws Exception { processRequest(); assertThat(response.getStatus()) diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java index cc8f8d1ef8..2473cfa8f0 100755 --- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java +++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java @@ -5,10 +5,10 @@ import static org.assertj.core.api.Assertions.assertThat; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class AdminServletUriTest extends AbstractServletTest { +class AdminServletUriTest extends AbstractServletTest { private final MetricRegistry registry = new MetricRegistry(); private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); @@ -26,15 +26,15 @@ protected void setUp(ServletTester tester) { tester.addServlet(AdminServlet.class, "/admin"); } - @Before - public void setUp() { + @BeforeEach + void setUp() { request.setMethod("GET"); request.setURI("/context/admin"); request.setVersion("HTTP/1.0"); } @Test - public void returnsA200() throws Exception { + void returnsA200() throws Exception { processRequest(); assertThat(response.getStatus()) diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java index da902c190e..ae28b22875 100644 --- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java +++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java @@ -2,20 +2,20 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class CpuProfileServletTest extends AbstractServletTest { +class CpuProfileServletTest extends AbstractServletTest { @Override protected void setUp(ServletTester tester) { tester.addServlet(CpuProfileServlet.class, "/pprof"); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { request.setMethod("GET"); request.setURI("/pprof?duration=1"); request.setVersion("HTTP/1.0"); @@ -24,19 +24,19 @@ public void setUp() throws Exception { } @Test - public void returns200OK() { + void returns200OK() { assertThat(response.getStatus()) .isEqualTo(200); } @Test - public void returnsPprofRaw() { + void returnsPprofRaw() { assertThat(response.get(HttpHeader.CONTENT_TYPE)) .isEqualTo("pprof/raw"); } @Test - public void returnsUncacheable() { + void returnsUncacheable() { assertThat(response.get(HttpHeader.CACHE_CONTROL)) .isEqualTo("must-revalidate,no-cache,no-store"); diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java index 148cf7f00a..1fcec12442 100644 --- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java @@ -10,9 +10,9 @@ import jakarta.servlet.ServletException; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; @@ -21,13 +21,14 @@ import java.util.concurrent.Executors; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class HealthCheckServletTest extends AbstractServletTest { +class HealthCheckServletTest extends AbstractServletTest { private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); @@ -62,20 +63,20 @@ protected void setUp(ServletTester tester) { (HealthCheckFilter) (name, healthCheck) -> !"filtered".equals(name)); } - @Before - public void setUp() { + @BeforeEach + void setUp() { request.setMethod("GET"); request.setURI("/healthchecks"); request.setVersion("HTTP/1.0"); } - @After - public void tearDown() { + @AfterEach + void tearDown() { threadPool.shutdown(); } @Test - public void returns501IfNoHealthChecksAreRegistered() throws Exception { + void returns501IfNoHealthChecksAreRegistered() throws Exception { processRequest(); assertThat(response.getStatus()).isEqualTo(501); @@ -84,7 +85,7 @@ public void returns501IfNoHealthChecksAreRegistered() throws Exception { } @Test - public void returnsA200IfAllHealthChecksAreHealthy() throws Exception { + void returnsA200IfAllHealthChecksAreHealthy() throws Exception { registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); processRequest(); @@ -98,7 +99,7 @@ public void returnsA200IfAllHealthChecksAreHealthy() throws Exception { } @Test - public void returnsASubsetOfHealthChecksIfFiltered() throws Exception { + void returnsASubsetOfHealthChecksIfFiltered() throws Exception { registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); registry.register("filtered", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); @@ -113,7 +114,7 @@ public void returnsASubsetOfHealthChecksIfFiltered() throws Exception { } @Test - public void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { + void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); @@ -122,12 +123,12 @@ public void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { assertThat(response.getStatus()).isEqualTo(500); assertThat(response.get(HttpHeader.CONTENT_TYPE)).isEqualTo("application/json"); assertThat(response.getContent()).contains( - "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}", - ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}}"); + "{\"fun\":{\"healthy\":true,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}", + ",\"notFun\":{\"healthy\":false,\"message\":\"whee\",\"duration\":0,\"timestamp\":\"" + EXPECTED_TIMESTAMP + "\"}}"); } @Test - public void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { + void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); request.setURI("/healthchecks?httpStatusIndicator=false"); @@ -142,7 +143,7 @@ public void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisa } @Test - public void optionallyPrettyPrintsTheJson() throws Exception { + void optionallyPrettyPrintsTheJson() throws Exception { registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("foo bar 123"))); request.setURI("/healthchecks?pretty=true"); @@ -178,7 +179,7 @@ private static HealthCheck.Result unhealthyResultWithMessage(String message) { } @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); @@ -192,7 +193,7 @@ public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig } @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); @@ -207,20 +208,22 @@ public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); } - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { - final ServletContext servletContext = mock(ServletContext.class); - final ServletConfig servletConfig = mock(ServletConfig.class); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); - - final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); - healthCheckServlet.init(servletConfig); + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { + assertThrows(ServletException.class, () -> { + final ServletContext servletContext = mock(ServletContext.class); + final ServletConfig servletConfig = mock(ServletConfig.class); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); + + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); + healthCheckServlet.init(servletConfig); + }); } @Test - public void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { + void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); when(servletConfig.getServletContext()).thenReturn(servletContext); diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java index 5c450f0d20..8516154324 100644 --- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java +++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java @@ -8,8 +8,8 @@ import io.dropwizard.metrics5.Timer; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; @@ -17,7 +17,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class MetricsServletContextListenerTest extends AbstractServletTest { +class MetricsServletContextListenerTest extends AbstractServletTest { private final Clock clock = mock(Clock.class); private final MetricRegistry registry = new MetricRegistry(); private final String allowedOrigin = "some.other.origin"; @@ -49,8 +49,8 @@ protected String getAllowedOrigin() { }); } - @Before - public void setUp() { + @BeforeEach + void setUp() { // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves // will call getTick again several times and always get the same value (the last specified here) when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); @@ -68,7 +68,7 @@ public void setUp() { } @Test - public void returnsA200() throws Exception { + void returnsA200() throws Exception { processRequest(); assertThat(response.getStatus()) @@ -96,7 +96,7 @@ public void returnsA200() throws Exception { } @Test - public void optionallyPrettyPrintsTheJson() throws Exception { + void optionallyPrettyPrintsTheJson() throws Exception { request.setURI("/metrics?pretty=true"); processRequest(); diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java index ab81c538a1..7d3db566bf 100644 --- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java @@ -11,12 +11,13 @@ import jakarta.servlet.ServletException; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -24,7 +25,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class MetricsServletTest extends AbstractServletTest { +class MetricsServletTest extends AbstractServletTest { private final Clock clock = mock(Clock.class); private final MetricRegistry registry = new MetricRegistry(); private ServletTester tester; @@ -37,8 +38,8 @@ protected void setUp(ServletTester tester) { tester.getContext().setInitParameter(MetricsServlet.class.getCanonicalName() + ".allowedOrigin", "*"); } - @Before - public void setUp() { + @BeforeEach + void setUp() { // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves // will call getTick again several times and always get the same value (the last specified here) when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); @@ -56,7 +57,7 @@ public void setUp() { } @Test - public void returnsA200() throws Exception { + void returnsA200() throws Exception { processRequest(); assertThat(response.getStatus()) @@ -84,7 +85,7 @@ public void returnsA200() throws Exception { } @Test - public void returnsJsonWhenJsonpInitParamNotSet() throws Exception { + void returnsJsonWhenJsonpInitParamNotSet() throws Exception { String callbackParamName = "callbackParam"; String callbackParamVal = "callbackParamVal"; request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); @@ -115,7 +116,7 @@ public void returnsJsonWhenJsonpInitParamNotSet() throws Exception { } @Test - public void returnsJsonpWhenInitParamSet() throws Exception { + void returnsJsonpWhenInitParamSet() throws Exception { String callbackParamName = "callbackParam"; String callbackParamVal = "callbackParamVal"; request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); @@ -146,7 +147,7 @@ public void returnsJsonpWhenInitParamSet() throws Exception { } @Test - public void optionallyPrettyPrintsTheJson() throws Exception { + void optionallyPrettyPrintsTheJson() throws Exception { request.setURI("/metrics?pretty=true"); processRequest(); @@ -220,7 +221,7 @@ public void optionallyPrettyPrintsTheJson() throws Exception { } @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { final MetricRegistry metricRegistry = mock(MetricRegistry.class); final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); @@ -234,7 +235,7 @@ public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig } @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { final MetricRegistry metricRegistry = mock(MetricRegistry.class); final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); @@ -249,15 +250,17 @@ public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); } - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { - final ServletContext servletContext = mock(ServletContext.class); - final ServletConfig servletConfig = mock(ServletConfig.class); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) - .thenReturn("IRELLEVANT_STRING"); + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { + assertThrows(ServletException.class, () -> { + final ServletContext servletContext = mock(ServletContext.class); + final ServletConfig servletConfig = mock(ServletConfig.class); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) + .thenReturn("IRELLEVANT_STRING"); - final MetricsServlet metricsServlet = new MetricsServlet(null); - metricsServlet.init(servletConfig); + final MetricsServlet metricsServlet = new MetricsServlet(null); + metricsServlet.init(servletConfig); + }); } } diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java index b079d71b80..669f126417 100644 --- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java +++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java @@ -2,19 +2,19 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class PingServletTest extends AbstractServletTest { +class PingServletTest extends AbstractServletTest { @Override protected void setUp(ServletTester tester) { tester.addServlet(PingServlet.class, "/ping"); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { request.setMethod("GET"); request.setURI("/ping"); request.setVersion("HTTP/1.0"); @@ -23,25 +23,25 @@ public void setUp() throws Exception { } @Test - public void returns200OK() { + void returns200OK() { assertThat(response.getStatus()) .isEqualTo(200); } @Test - public void returnsPong() { + void returnsPong() { assertThat(response.getContent()) .isEqualTo(String.format("pong%n")); } @Test - public void returnsTextPlain() { + void returnsTextPlain() { assertThat(response.get(HttpHeader.CONTENT_TYPE)) .isEqualTo("text/plain;charset=ISO-8859-1"); } @Test - public void returnsUncacheable() { + void returnsUncacheable() { assertThat(response.get(HttpHeader.CACHE_CONTROL)) .isEqualTo("must-revalidate,no-cache,no-store"); diff --git a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java index 6880b4c4eb..34e69f7bc2 100644 --- a/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java +++ b/metrics-jakarta-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java @@ -2,19 +2,19 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class ThreadDumpServletTest extends AbstractServletTest { +class ThreadDumpServletTest extends AbstractServletTest { @Override protected void setUp(ServletTester tester) { tester.addServlet(ThreadDumpServlet.class, "/threads"); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { request.setMethod("GET"); request.setURI("/threads"); request.setVersion("HTTP/1.0"); @@ -23,25 +23,25 @@ public void setUp() throws Exception { } @Test - public void returns200OK() { + void returns200OK() { assertThat(response.getStatus()) .isEqualTo(200); } @Test - public void returnsAThreadDump() { + void returnsAThreadDump() { assertThat(response.getContent()) .contains("Finalizer"); } @Test - public void returnsTextPlain() { + void returnsTextPlain() { assertThat(response.get(HttpHeader.CONTENT_TYPE)) .isEqualTo("text/plain"); } @Test - public void returnsUncacheable() { + void returnsUncacheable() { assertThat(response.get(HttpHeader.CACHE_CONTROL)) .isEqualTo("must-revalidate,no-cache,no-store"); diff --git a/metrics-jcache/pom.xml b/metrics-jcache/pom.xml index 493457c4a9..c836abc0fb 100644 --- a/metrics-jcache/pom.xml +++ b/metrics-jcache/pom.xml @@ -54,12 +54,6 @@ ${cache-api.version} provided - - junit - junit - ${junit.version} - test - org.assertj assertj-core @@ -104,6 +98,18 @@ 2.3.8 test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + javax.activation activation diff --git a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java index f57c360e98..ac4b62dac4 100644 --- a/metrics-jcache/src/test/java/JCacheGaugeSetTest.java +++ b/metrics-jcache/src/test/java/JCacheGaugeSetTest.java @@ -1,9 +1,9 @@ import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.jcache.JCacheGaugeSet; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.cache.Cache; import javax.cache.CacheManager; @@ -12,15 +12,15 @@ import static org.assertj.core.api.Assertions.assertThat; -public class JCacheGaugeSetTest { +class JCacheGaugeSetTest { private MetricRegistry registry; private Cache myCache; private Cache myOtherCache; private CacheManager cacheManager; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { CachingProvider provider = Caching.getCachingProvider(); cacheManager = provider.getCacheManager( @@ -35,7 +35,7 @@ public void setUp() throws Exception { } @Test - public void measuresGauges() throws Exception { + void measuresGauges() throws Exception { myOtherCache.get("woo"); assertThat(registry.getGauges().get(MetricName.build("jcache.statistics.myOtherCache.cache-misses")) @@ -79,8 +79,8 @@ public void measuresGauges() throws Exception { } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { cacheManager.destroyCache("myCache"); cacheManager.destroyCache("myOtherCache"); cacheManager.close(); diff --git a/metrics-jdbi3/pom.xml b/metrics-jdbi3/pom.xml index 2caeaab2c5..d1cc0f500a 100644 --- a/metrics-jdbi3/pom.xml +++ b/metrics-jdbi3/pom.xml @@ -57,24 +57,36 @@ - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core ${mockito.version} test + + org.mockito + mockito-junit-jupiter + ${mockito.version} + test + org.slf4j slf4j-simple diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/AbstractStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/AbstractStrategyTest.java index aa92a9aca1..b9d42c7523 100644 --- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/AbstractStrategyTest.java +++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/AbstractStrategyTest.java @@ -3,18 +3,25 @@ import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; import org.jdbi.v3.core.statement.StatementContext; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class AbstractStrategyTest { +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class AbstractStrategyTest { MetricRegistry registry = new MetricRegistry(); - StatementContext ctx = mock(StatementContext.class); + @Mock + StatementContext ctx; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(ctx.getRawSql()).thenReturn("SELECT 1"); } diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java index c2dbadfdc1..f9700edb5a 100644 --- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java +++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/BasicSqlNameStrategyTest.java @@ -2,21 +2,23 @@ import io.dropwizard.metrics5.MetricName; import org.jdbi.v3.core.extension.ExtensionMethod; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static io.dropwizard.metrics5.MetricRegistry.name; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; -public class BasicSqlNameStrategyTest extends AbstractStrategyTest { +class BasicSqlNameStrategyTest extends AbstractStrategyTest { - private BasicSqlNameStrategy basicSqlNameStrategy = new BasicSqlNameStrategy(); + private final BasicSqlNameStrategy basicSqlNameStrategy = new BasicSqlNameStrategy(); @Test - public void producesMethodNameAsMetric() throws Exception { - when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(getClass(), getClass().getMethod("producesMethodNameAsMetric"))); + void producesMethodNameAsMetric() throws Exception { + when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); MetricName name = basicSqlNameStrategy.getStatementName(ctx); - assertThat(name).isEqualTo(name(getClass(), "producesMethodNameAsMetric")); + assertThat(name).isEqualTo(name(getClass(), "someMethod")); } + public void someMethod() { + } } diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java index 03148ebe14..fbf701843e 100755 --- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java +++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/InstrumentedSqlLoggerTest.java @@ -6,7 +6,7 @@ import io.dropwizard.metrics5.jdbi3.InstrumentedSqlLogger; import io.dropwizard.metrics5.jdbi3.strategies.StatementNameStrategy; import org.jdbi.v3.core.statement.StatementContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.sql.SQLException; import java.time.temporal.ChronoUnit; @@ -14,9 +14,9 @@ import static org.mockito.Mockito.*; -public class InstrumentedSqlLoggerTest { +class InstrumentedSqlLoggerTest { @Test - public void logsExecutionTime() { + void logsExecutionTime() { final MetricRegistry mockRegistry = mock(MetricRegistry.class); final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); @@ -38,7 +38,7 @@ public void logsExecutionTime() { } @Test - public void logsExceptionTime() { + void logsExceptionTime() { final MetricRegistry mockRegistry = mock(MetricRegistry.class); final StatementNameStrategy mockNameStrategy = mock(StatementNameStrategy.class); final InstrumentedSqlLogger logger = new InstrumentedSqlLogger(mockRegistry, mockNameStrategy); diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java index 959667514b..39cbedbdd6 100644 --- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java +++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/NaiveNameStrategyTest.java @@ -1,16 +1,16 @@ package io.dropwizard.metrics5.jdbi3.strategies; import io.dropwizard.metrics5.MetricName; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class NaiveNameStrategyTest extends AbstractStrategyTest { +class NaiveNameStrategyTest extends AbstractStrategyTest { - private NaiveNameStrategy naiveNameStrategy = new NaiveNameStrategy(); + private final NaiveNameStrategy naiveNameStrategy = new NaiveNameStrategy(); @Test - public void producesSqlRawMetrics() throws Exception { + void producesSqlRawMetrics() throws Exception { MetricName name = naiveNameStrategy.getStatementName(ctx); assertThat(name.getKey()).isEqualToIgnoringCase("SELECT 1"); } diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java index 5a16b1e0cd..f575729a2c 100644 --- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java +++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/SmartNameStrategyTest.java @@ -3,8 +3,8 @@ import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.jdbi3.InstrumentedTimingCollector; import org.jdbi.v3.core.extension.ExtensionMethod; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; @@ -13,12 +13,12 @@ import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; -public class SmartNameStrategyTest extends AbstractStrategyTest { +class SmartNameStrategyTest extends AbstractStrategyTest { - private StatementNameStrategy smartNameStrategy = new SmartNameStrategy(); + private final StatementNameStrategy smartNameStrategy = new SmartNameStrategy(); private InstrumentedTimingCollector collector; - @Before + @BeforeEach @Override public void setUp() throws Exception { super.setUp(); @@ -26,19 +26,19 @@ public void setUp() throws Exception { } @Test - public void updatesTimerForSqlObjects() throws Exception { + void updatesTimerForSqlObjects() throws Exception { when(ctx.getExtensionMethod()).thenReturn( - new ExtensionMethod(getClass(), getClass().getMethod("updatesTimerForSqlObjects"))); + new ExtensionMethod(getClass(), getClass().getMethod("someMethod"))); collector.collect(TimeUnit.SECONDS.toNanos(1), ctx); MetricName name = smartNameStrategy.getStatementName(ctx); - assertThat(name).isEqualTo(name(getClass(), "updatesTimerForSqlObjects")); + assertThat(name).isEqualTo(name(getClass(), "someMethod")); assertThat(getTimerMaxValue(name)).isEqualTo(1000000000); } @Test - public void updatesTimerForRawSql() throws Exception { + void updatesTimerForRawSql() throws Exception { collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); MetricName name = smartNameStrategy.getStatementName(ctx); @@ -47,7 +47,7 @@ public void updatesTimerForRawSql() throws Exception { } @Test - public void updatesTimerForNoRawSql() throws Exception { + void updatesTimerForNoRawSql() throws Exception { reset(ctx); collector.collect(TimeUnit.SECONDS.toNanos(2), ctx); @@ -58,13 +58,16 @@ public void updatesTimerForNoRawSql() throws Exception { } @Test - public void updatesTimerForContextClass() throws Exception { + void updatesTimerForContextClass() throws Exception { when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(getClass(), - getClass().getMethod("updatesTimerForContextClass"))); + getClass().getMethod("someMethod"))); collector.collect(TimeUnit.SECONDS.toNanos(3), ctx); MetricName name = smartNameStrategy.getStatementName(ctx); - assertThat(name).isEqualTo(name(getClass(), "updatesTimerForContextClass")); + assertThat(name).isEqualTo(name(getClass(), "someMethod")); assertThat(getTimerMaxValue(name)).isEqualTo(3000000000L); } + + public void someMethod() { + } } diff --git a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java index b3e305efce..2191f8ebbe 100644 --- a/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java +++ b/metrics-jdbi3/src/test/java/io/dropwizard/metrics5/jdbi3/strategies/TimedAnnotationNameStrategyTest.java @@ -3,14 +3,14 @@ import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.annotation.Timed; import org.jdbi.v3.core.extension.ExtensionMethod; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; -public class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { +class TimedAnnotationNameStrategyTest extends AbstractStrategyTest { - private TimedAnnotationNameStrategy timedAnnotationNameStrategy = new TimedAnnotationNameStrategy(); + private final TimedAnnotationNameStrategy timedAnnotationNameStrategy = new TimedAnnotationNameStrategy(); public interface Foo { @@ -44,46 +44,46 @@ public interface Dummy { } @Test - public void testAnnotationOnMethod() throws Exception { + void testAnnotationOnMethod() throws Exception { when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("update"))); assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) .isEqualTo(MetricName.build("io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Foo.update")); } @Test - public void testAnnotationOnMethodWithCustomName() throws Exception { + void testAnnotationOnMethodWithCustomName() throws Exception { when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("customUpdate"))); assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) .isEqualTo(MetricName.build("io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Foo.custom-update")); } @Test - public void testAnnotationOnMethodWithCustomAbsoluteName() throws Exception { + void testAnnotationOnMethodWithCustomAbsoluteName() throws Exception { when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Foo.class, Foo.class.getMethod("absoluteUpdate"))); assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isEqualTo(MetricName.build("absolute-update")); } @Test - public void testAnnotationOnClass() throws Exception { + void testAnnotationOnClass() throws Exception { when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Bar.class, Bar.class.getMethod("update"))); assertThat(timedAnnotationNameStrategy.getStatementName(ctx)) .isEqualTo(MetricName.build("io.dropwizard.metrics5.jdbi3.strategies.TimedAnnotationNameStrategyTest$Bar.update")); } @Test - public void testAnnotationOnMethodAndClassWithCustomNames() throws Exception { + void testAnnotationOnMethodAndClassWithCustomNames() throws Exception { when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(CustomBar.class, CustomBar.class.getMethod("find", String.class))); assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isEqualTo(MetricName.build("custom-bar.find-by-id")); } @Test - public void testNoAnnotations() throws Exception { + void testNoAnnotations() throws Exception { when(ctx.getExtensionMethod()).thenReturn(new ExtensionMethod(Dummy.class, Dummy.class.getMethod("show"))); assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); } @Test - public void testNoMethod() { + void testNoMethod() { assertThat(timedAnnotationNameStrategy.getStatementName(ctx)).isNull(); } } \ No newline at end of file diff --git a/metrics-jersey2/pom.xml b/metrics-jersey2/pom.xml index 34e927810e..50670527b7 100644 --- a/metrics-jersey2/pom.xml +++ b/metrics-jersey2/pom.xml @@ -63,12 +63,6 @@ org.glassfish.jersey.core jersey-server - - junit - junit - ${junit.version} - test - org.assertj assertj-core @@ -95,11 +89,35 @@ org.glassfish.jersey.test-framework jersey-test-framework-core test + + + junit + junit + + org.glassfish.jersey.test-framework.providers jersey-test-framework-provider-inmemory test + + + junit + junit + + + + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java index d92baab8c1..c0c763fe9f 100644 --- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java +++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/CustomReservoirImplementationTest.java @@ -7,7 +7,7 @@ import io.dropwizard.metrics5.jersey2.resources.InstrumentedResourceTimedPerClass; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.ws.rs.core.Application; import java.util.logging.Level; @@ -16,7 +16,7 @@ import static io.dropwizard.metrics5.MetricRegistry.name; import static org.assertj.core.api.Assertions.assertThat; -public class CustomReservoirImplementationTest extends JerseyTest { +class CustomReservoirImplementationTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -28,18 +28,18 @@ protected Application configure() { this.registry = new MetricRegistry(); return new ResourceConfig() - .register(new MetricsFeature(this.registry, UniformReservoir::new)) - .register(InstrumentedResourceTimedPerClass.class); + .register(new MetricsFeature(this.registry, UniformReservoir::new)) + .register(InstrumentedResourceTimedPerClass.class); } @Test - public void timerHistogramIsUsingCustomReservoirImplementation() { + void timerHistogramIsUsingCustomReservoirImplementation() { assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); assertThat(timer) - .extracting("histogram") - .extracting("reservoir") - .isInstanceOf(UniformReservoir.class); + .extracting("histogram") + .extracting("reservoir") + .isInstanceOf(UniformReservoir.class); } } diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java index bcd3202de6..15c2c34be3 100644 --- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java +++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonFilterMetricsJerseyTest.java @@ -6,8 +6,8 @@ import io.dropwizard.metrics5.jersey2.resources.TestRequestFilter; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.ws.rs.core.Application; import java.util.logging.Level; @@ -19,7 +19,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} with filter tracking */ -public class SingletonFilterMetricsJerseyTest extends JerseyTest { +class SingletonFilterMetricsJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -39,17 +39,17 @@ protected Application configure() { return config; } - @Before - public void resetClock() { + @BeforeEach + void resetClock() { testClock.tick = 0; } @Test - public void timedMethodsAreTimed() { + void timedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed")); @@ -58,11 +58,11 @@ public void timedMethodsAreTimed() { } @Test - public void explicitNamesAreTimed() { + void explicitNamesAreTimed() { assertThat(target("named") - .request() - .get(String.class)) - .isEqualTo("fancy"); + .request() + .get(String.class)) + .isEqualTo("fancy"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "fancyName")); @@ -71,11 +71,11 @@ public void explicitNamesAreTimed() { } @Test - public void absoluteNamesAreTimed() { + void absoluteNamesAreTimed() { assertThat(target("absolute") - .request() - .get(String.class)) - .isEqualTo("absolute"); + .request() + .get(String.class)) + .isEqualTo("absolute"); final Timer timer = registry.timer("absolutelyFancy"); @@ -84,11 +84,11 @@ public void absoluteNamesAreTimed() { } @Test - public void requestFiltersOfTimedMethodsAreTimed() { + void requestFiltersOfTimedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); @@ -97,11 +97,11 @@ public void requestFiltersOfTimedMethodsAreTimed() { } @Test - public void responseFiltersOfTimedMethodsAreTimed() { + void responseFiltersOfTimedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); @@ -109,11 +109,11 @@ public void responseFiltersOfTimedMethodsAreTimed() { } @Test - public void totalTimeOfTimedMethodsIsTimed() { + void totalTimeOfTimedMethodsIsTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "timed", "total")); @@ -122,11 +122,11 @@ public void totalTimeOfTimedMethodsIsTimed() { } @Test - public void requestFiltersOfNamedMethodsAreTimed() { + void requestFiltersOfNamedMethodsAreTimed() { assertThat(target("named") - .request() - .get(String.class)) - .isEqualTo("fancy"); + .request() + .get(String.class)) + .isEqualTo("fancy"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); @@ -135,11 +135,11 @@ public void requestFiltersOfNamedMethodsAreTimed() { } @Test - public void requestFiltersOfAbsoluteMethodsAreTimed() { + void requestFiltersOfAbsoluteMethodsAreTimed() { assertThat(target("absolute") - .request() - .get(String.class)) - .isEqualTo("absolute"); + .request() + .get(String.class)) + .isEqualTo("absolute"); final Timer timer = registry.timer(MetricRegistry.name("absolutelyFancy", "request", "filtering")); assertThat(timer.getCount()).isEqualTo(1); @@ -147,14 +147,14 @@ public void requestFiltersOfAbsoluteMethodsAreTimed() { } @Test - public void subResourcesFromLocatorsRegisterMetrics() { + void subResourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, - "timed")); + "timed")); assertThat(timer.getCount()).isEqualTo(1); } diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java index 967370ea5f..655da19c61 100644 --- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsExceptionMeteredPerClassJerseyTest.java @@ -6,7 +6,7 @@ import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceExceptionMeteredPerClass; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.ws.rs.ProcessingException; import javax.ws.rs.core.Application; @@ -21,7 +21,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { +class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -41,23 +41,23 @@ protected Application configure() { } @Test - public void exceptionMeteredMethodsAreExceptionMetered() { + void exceptionMeteredMethodsAreExceptionMetered() { final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResourceExceptionMeteredPerClass.class, - "exceptionMetered", - "exceptions")); + "exceptionMetered", + "exceptions")); assertThat(target("exception-metered") - .request() - .get(String.class)) - .isEqualTo("fuh"); + .request() + .get(String.class)) + .isEqualTo("fuh"); assertThat(meter.getCount()).isZero(); try { target("exception-metered") - .queryParam("splode", true) - .request() - .get(String.class); + .queryParam("splode", true) + .request() + .get(String.class); failBecauseExceptionWasNotThrown(ProcessingException.class); } catch (ProcessingException e) { @@ -68,23 +68,23 @@ public void exceptionMeteredMethodsAreExceptionMetered() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { final Meter meter = registry.meter(MetricRegistry.name(InstrumentedSubResourceExceptionMeteredPerClass.class, - "exceptionMetered", - "exceptions")); + "exceptionMetered", + "exceptions")); assertThat(target("subresource/exception-metered") - .request() - .get(String.class)) - .isEqualTo("fuh"); + .request() + .get(String.class)) + .isEqualTo("fuh"); assertThat(meter.getCount()).isZero(); try { target("subresource/exception-metered") - .queryParam("splode", true) - .request() - .get(String.class); + .queryParam("splode", true) + .request() + .get(String.class); failBecauseExceptionWasNotThrown(ProcessingException.class); } catch (ProcessingException e) { diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java index c2ffacf309..9ee0cf6930 100644 --- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java +++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsJerseyTest.java @@ -8,7 +8,7 @@ import org.glassfish.jersey.client.ClientResponse; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.ws.rs.NotFoundException; import javax.ws.rs.ProcessingException; @@ -25,7 +25,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link org.glassfish.jersey.server.ResourceConfig} */ -public class SingletonMetricsJerseyTest extends JerseyTest { +class SingletonMetricsJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -44,11 +44,11 @@ protected Application configure() { } @Test - public void timedMethodsAreTimed() { + void timedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedResource.class, "timed")); @@ -56,34 +56,34 @@ public void timedMethodsAreTimed() { } @Test - public void meteredMethodsAreMetered() { + void meteredMethodsAreMetered() { assertThat(target("metered") - .request() - .get(String.class)) - .isEqualTo("woo"); + .request() + .get(String.class)) + .isEqualTo("woo"); final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResource.class, "metered")); assertThat(meter.getCount()).isEqualTo(1); } @Test - public void exceptionMeteredMethodsAreExceptionMetered() { + void exceptionMeteredMethodsAreExceptionMetered() { final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResource.class, - "exceptionMetered", - "exceptions")); + "exceptionMetered", + "exceptions")); assertThat(target("exception-metered") - .request() - .get(String.class)) - .isEqualTo("fuh"); + .request() + .get(String.class)) + .isEqualTo("fuh"); assertThat(meter.getCount()).isZero(); try { target("exception-metered") - .queryParam("splode", true) - .request() - .get(String.class); + .queryParam("splode", true) + .request() + .get(String.class); failBecauseExceptionWasNotThrown(ProcessingException.class); } catch (ProcessingException e) { @@ -94,34 +94,34 @@ public void exceptionMeteredMethodsAreExceptionMetered() { } @Test - public void responseMeteredMethodsAreMetered() { + void responseMeteredMethodsAreMetered() { final Meter meter2xx = registry.meter(MetricRegistry.name(InstrumentedResource.class, - "response2xxMetered", - "2xx-responses")); + "response2xxMetered", + "2xx-responses")); final Meter meter4xx = registry.meter(MetricRegistry.name(InstrumentedResource.class, - "response4xxMetered", - "4xx-responses")); + "response4xxMetered", + "4xx-responses")); final Meter meter5xx = registry.meter(MetricRegistry.name(InstrumentedResource.class, - "response5xxMetered", - "5xx-responses")); + "response5xxMetered", + "5xx-responses")); assertThat(meter2xx.getCount()).isZero(); assertThat(target("response-2xx-metered") - .request() - .get().getStatus()) - .isEqualTo(200); + .request() + .get().getStatus()) + .isEqualTo(200); assertThat(meter4xx.getCount()).isZero(); assertThat(target("response-4xx-metered") - .request() - .get().getStatus()) - .isEqualTo(400); + .request() + .get().getStatus()) + .isEqualTo(400); assertThat(meter5xx.getCount()).isZero(); assertThat(target("response-5xx-metered") - .request() - .get().getStatus()) - .isEqualTo(500); + .request() + .get().getStatus()) + .isEqualTo(500); assertThat(meter2xx.getCount()).isEqualTo(1); assertThat(meter4xx.getCount()).isEqualTo(1); @@ -129,7 +129,7 @@ public void responseMeteredMethodsAreMetered() { } @Test - public void testResourceNotFound() { + void testResourceNotFound() { final Response response = target().path("not-found").request().get(); assertThat(response.getStatus()).isEqualTo(404); @@ -142,11 +142,11 @@ public void testResourceNotFound() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedSubResource.class, "timed")); assertThat(timer.getCount()).isEqualTo(1); diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java index d70b408017..d2e2b87ac2 100644 --- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java +++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsMeteredPerClassJerseyTest.java @@ -6,7 +6,7 @@ import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceMeteredPerClass; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.ws.rs.core.Application; import java.util.logging.Level; @@ -18,7 +18,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { +class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -38,11 +38,11 @@ protected Application configure() { } @Test - public void meteredPerClassMethodsAreMetered() { + void meteredPerClassMethodsAreMetered() { assertThat(target("meteredPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Meter meter = registry.meter(MetricRegistry.name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); @@ -50,11 +50,11 @@ public void meteredPerClassMethodsAreMetered() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/meteredPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Meter meter = registry.meter(MetricRegistry.name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); assertThat(meter.getCount()).isEqualTo(1); diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java index 8bf0e524f7..2122ac37c5 100644 --- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java +++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsResponseMeteredPerClassJerseyTest.java @@ -7,20 +7,20 @@ import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceResponseMeteredPerClass; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.ws.rs.core.Application; import java.util.logging.Level; import java.util.logging.Logger; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { +class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -42,97 +42,97 @@ protected Application configure() { } @Test - public void responseMetered2xxPerClassMethodsAreMetered() { + void responseMetered2xxPerClassMethodsAreMetered() { assertThat(target("responseMetered2xxPerClass") - .request() - .get().getStatus()) - .isEqualTo(200); + .request() + .get().getStatus()) + .isEqualTo(200); final Meter meter2xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMetered2xxPerClass", - "2xx-responses")); + "responseMetered2xxPerClass", + "2xx-responses")); assertThat(meter2xx.getCount()).isEqualTo(1); } @Test - public void responseMetered4xxPerClassMethodsAreMetered() { + void responseMetered4xxPerClassMethodsAreMetered() { assertThat(target("responseMetered4xxPerClass") - .request() - .get().getStatus()) - .isEqualTo(400); + .request() + .get().getStatus()) + .isEqualTo(400); assertThat(target("responseMeteredBadRequestPerClass") - .request() - .get().getStatus()) - .isEqualTo(400); + .request() + .get().getStatus()) + .isEqualTo(400); final Meter meter4xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMetered4xxPerClass", - "4xx-responses")); + "responseMetered4xxPerClass", + "4xx-responses")); final Meter meterException4xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMeteredBadRequestPerClass", - "4xx-responses")); + "responseMeteredBadRequestPerClass", + "4xx-responses")); assertThat(meter4xx.getCount()).isEqualTo(1); assertThat(meterException4xx.getCount()).isEqualTo(1); } @Test - public void responseMetered5xxPerClassMethodsAreMetered() { + void responseMetered5xxPerClassMethodsAreMetered() { assertThat(target("responseMetered5xxPerClass") - .request() - .get().getStatus()) - .isEqualTo(500); + .request() + .get().getStatus()) + .isEqualTo(500); final Meter meter5xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMetered5xxPerClass", - "5xx-responses")); + "responseMetered5xxPerClass", + "5xx-responses")); assertThat(meter5xx.getCount()).isEqualTo(1); } @Test - public void responseMeteredMappedExceptionPerClassMethodsAreMetered() { + void responseMeteredMappedExceptionPerClassMethodsAreMetered() { assertThat(target("responseMeteredTestExceptionPerClass") - .request() - .get().getStatus()) - .isEqualTo(500); + .request() + .get().getStatus()) + .isEqualTo(500); final Meter meterTestException = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMeteredTestExceptionPerClass", - "5xx-responses")); + "responseMeteredTestExceptionPerClass", + "5xx-responses")); assertThat(meterTestException.getCount()).isEqualTo(1); } @Test - public void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { + void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { try { target("responseMeteredRuntimeExceptionPerClass") - .request() - .get(); + .request() + .get(); fail("expected RuntimeException"); } catch (Exception e) { assertThat(e.getCause()).isInstanceOf(RuntimeException.class); } final Meter meterException5xx = registry.meter(MetricRegistry.name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMeteredRuntimeExceptionPerClass", - "5xx-responses")); + "responseMeteredRuntimeExceptionPerClass", + "5xx-responses")); assertThat(meterException5xx.getCount()).isEqualTo(1); } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/responseMeteredPerClass") - .request() - .get().getStatus()) - .isEqualTo(200); + .request() + .get().getStatus()) + .isEqualTo(200); final Meter meter = registry.meter(MetricRegistry.name(InstrumentedSubResourceResponseMeteredPerClass.class, - "responseMeteredPerClass", - "2xx-responses")); + "responseMeteredPerClass", + "2xx-responses")); assertThat(meter.getCount()).isEqualTo(1); } } diff --git a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java index 7c46ae22c8..7b384745e0 100644 --- a/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java +++ b/metrics-jersey2/src/test/java/io/dropwizard/metrics5/jersey2/SingletonMetricsTimedPerClassJerseyTest.java @@ -6,7 +6,7 @@ import io.dropwizard.metrics5.jersey2.resources.InstrumentedSubResourceTimedPerClass; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.ws.rs.core.Application; import java.util.logging.Level; @@ -18,7 +18,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { +class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -38,11 +38,11 @@ protected Application configure() { } @Test - public void timedPerClassMethodsAreTimed() { + void timedPerClassMethodsAreTimed() { assertThat(target("timedPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); @@ -50,11 +50,11 @@ public void timedPerClassMethodsAreTimed() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/timedPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(MetricRegistry.name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); assertThat(timer.getCount()).isEqualTo(1); diff --git a/metrics-jersey3/pom.xml b/metrics-jersey3/pom.xml index f71055896b..b993faaff7 100644 --- a/metrics-jersey3/pom.xml +++ b/metrics-jersey3/pom.xml @@ -52,6 +52,13 @@ byte-buddy ${byte-buddy.version} + + org.junit + junit-bom + ${junit5.version} + pom + import + @@ -74,11 +81,10 @@ 3.0.0 - junit - junit - 4.13.1 + org.junit.jupiter + junit-jupiter-api test - + org.assertj assertj-core diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java index a59d751150..775dae5ee4 100644 --- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java +++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/CustomReservoirImplementationTest.java @@ -7,7 +7,7 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.logging.Level; import java.util.logging.Logger; @@ -15,7 +15,7 @@ import static io.dropwizard.metrics5.MetricRegistry.name; import static org.assertj.core.api.Assertions.assertThat; -public class CustomReservoirImplementationTest extends JerseyTest { +class CustomReservoirImplementationTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -27,18 +27,18 @@ protected Application configure() { this.registry = new MetricRegistry(); return new ResourceConfig() - .register(new MetricsFeature(this.registry, UniformReservoir::new)) - .register(InstrumentedResourceTimedPerClass.class); + .register(new MetricsFeature(this.registry, UniformReservoir::new)) + .register(InstrumentedResourceTimedPerClass.class); } @Test - public void timerHistogramIsUsingCustomReservoirImplementation() { + void timerHistogramIsUsingCustomReservoirImplementation() { assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); assertThat(timer) - .extracting("histogram") - .extracting("reservoir") - .isInstanceOf(UniformReservoir.class); + .extracting("histogram") + .extracting("reservoir") + .isInstanceOf(UniformReservoir.class); } } diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java index e8b4b2786b..de9de0a5e1 100644 --- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java +++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonFilterMetricsJerseyTest.java @@ -7,8 +7,8 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.logging.Level; import java.util.logging.Logger; @@ -20,7 +20,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} with filter tracking */ -public class SingletonFilterMetricsJerseyTest extends JerseyTest { +class SingletonFilterMetricsJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -40,17 +40,17 @@ protected Application configure() { return config; } - @Before - public void resetClock() { + @BeforeEach + void resetClock() { testClock.tick = 0; } @Test - public void timedMethodsAreTimed() { + void timedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed")); @@ -59,11 +59,11 @@ public void timedMethodsAreTimed() { } @Test - public void explicitNamesAreTimed() { + void explicitNamesAreTimed() { assertThat(target("named") - .request() - .get(String.class)) - .isEqualTo("fancy"); + .request() + .get(String.class)) + .isEqualTo("fancy"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName")); @@ -72,11 +72,11 @@ public void explicitNamesAreTimed() { } @Test - public void absoluteNamesAreTimed() { + void absoluteNamesAreTimed() { assertThat(target("absolute") - .request() - .get(String.class)) - .isEqualTo("absolute"); + .request() + .get(String.class)) + .isEqualTo("absolute"); final Timer timer = registry.timer("absolutelyFancy"); @@ -85,11 +85,11 @@ public void absoluteNamesAreTimed() { } @Test - public void requestFiltersOfTimedMethodsAreTimed() { + void requestFiltersOfTimedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); @@ -98,11 +98,11 @@ public void requestFiltersOfTimedMethodsAreTimed() { } @Test - public void responseFiltersOfTimedMethodsAreTimed() { + void responseFiltersOfTimedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); @@ -110,11 +110,11 @@ public void responseFiltersOfTimedMethodsAreTimed() { } @Test - public void totalTimeOfTimedMethodsIsTimed() { + void totalTimeOfTimedMethodsIsTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "total")); @@ -123,11 +123,11 @@ public void totalTimeOfTimedMethodsIsTimed() { } @Test - public void requestFiltersOfNamedMethodsAreTimed() { + void requestFiltersOfNamedMethodsAreTimed() { assertThat(target("named") - .request() - .get(String.class)) - .isEqualTo("fancy"); + .request() + .get(String.class)) + .isEqualTo("fancy"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); @@ -136,11 +136,11 @@ public void requestFiltersOfNamedMethodsAreTimed() { } @Test - public void requestFiltersOfAbsoluteMethodsAreTimed() { + void requestFiltersOfAbsoluteMethodsAreTimed() { assertThat(target("absolute") - .request() - .get(String.class)) - .isEqualTo("absolute"); + .request() + .get(String.class)) + .isEqualTo("absolute"); final Timer timer = registry.timer(name("absolutelyFancy", "request", "filtering")); assertThat(timer.getCount()).isEqualTo(1); @@ -148,14 +148,14 @@ public void requestFiltersOfAbsoluteMethodsAreTimed() { } @Test - public void subResourcesFromLocatorsRegisterMetrics() { + void subResourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, - "timed")); + "timed")); assertThat(timer.getCount()).isEqualTo(1); } diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java index 4bc69bac07..12f0b2bd2c 100644 --- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsExceptionMeteredPerClassJerseyTest.java @@ -8,7 +8,7 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.logging.Level; @@ -22,7 +22,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { +class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -42,23 +42,23 @@ protected Application configure() { } @Test - public void exceptionMeteredMethodsAreExceptionMetered() { + void exceptionMeteredMethodsAreExceptionMetered() { final Meter meter = registry.meter(name(InstrumentedResourceExceptionMeteredPerClass.class, - "exceptionMetered", - "exceptions")); + "exceptionMetered", + "exceptions")); assertThat(target("exception-metered") - .request() - .get(String.class)) - .isEqualTo("fuh"); + .request() + .get(String.class)) + .isEqualTo("fuh"); assertThat(meter.getCount()).isZero(); try { target("exception-metered") - .queryParam("splode", true) - .request() - .get(String.class); + .queryParam("splode", true) + .request() + .get(String.class); failBecauseExceptionWasNotThrown(ProcessingException.class); } catch (ProcessingException e) { @@ -69,23 +69,23 @@ public void exceptionMeteredMethodsAreExceptionMetered() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { final Meter meter = registry.meter(name(InstrumentedSubResourceExceptionMeteredPerClass.class, - "exceptionMetered", - "exceptions")); + "exceptionMetered", + "exceptions")); assertThat(target("subresource/exception-metered") - .request() - .get(String.class)) - .isEqualTo("fuh"); + .request() + .get(String.class)) + .isEqualTo("fuh"); assertThat(meter.getCount()).isZero(); try { target("subresource/exception-metered") - .queryParam("splode", true) - .request() - .get(String.class); + .queryParam("splode", true) + .request() + .get(String.class); failBecauseExceptionWasNotThrown(ProcessingException.class); } catch (ProcessingException e) { diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java index 6fed31519d..05489cbdd4 100644 --- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java +++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsJerseyTest.java @@ -12,7 +12,7 @@ import org.glassfish.jersey.client.ClientResponse; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.logging.Level; @@ -26,7 +26,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link org.glassfish.jersey.server.ResourceConfig} */ -public class SingletonMetricsJerseyTest extends JerseyTest { +class SingletonMetricsJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -45,11 +45,11 @@ protected Application configure() { } @Test - public void timedMethodsAreTimed() { + void timedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedResource.class, "timed")); @@ -57,34 +57,34 @@ public void timedMethodsAreTimed() { } @Test - public void meteredMethodsAreMetered() { + void meteredMethodsAreMetered() { assertThat(target("metered") - .request() - .get(String.class)) - .isEqualTo("woo"); + .request() + .get(String.class)) + .isEqualTo("woo"); final Meter meter = registry.meter(name(InstrumentedResource.class, "metered")); assertThat(meter.getCount()).isEqualTo(1); } @Test - public void exceptionMeteredMethodsAreExceptionMetered() { + void exceptionMeteredMethodsAreExceptionMetered() { final Meter meter = registry.meter(name(InstrumentedResource.class, - "exceptionMetered", - "exceptions")); + "exceptionMetered", + "exceptions")); assertThat(target("exception-metered") - .request() - .get(String.class)) - .isEqualTo("fuh"); + .request() + .get(String.class)) + .isEqualTo("fuh"); assertThat(meter.getCount()).isZero(); try { target("exception-metered") - .queryParam("splode", true) - .request() - .get(String.class); + .queryParam("splode", true) + .request() + .get(String.class); failBecauseExceptionWasNotThrown(ProcessingException.class); } catch (ProcessingException e) { @@ -95,34 +95,34 @@ public void exceptionMeteredMethodsAreExceptionMetered() { } @Test - public void responseMeteredMethodsAreMetered() { + void responseMeteredMethodsAreMetered() { final Meter meter2xx = registry.meter(name(InstrumentedResource.class, - "response2xxMetered", - "2xx-responses")); + "response2xxMetered", + "2xx-responses")); final Meter meter4xx = registry.meter(name(InstrumentedResource.class, - "response4xxMetered", - "4xx-responses")); + "response4xxMetered", + "4xx-responses")); final Meter meter5xx = registry.meter(name(InstrumentedResource.class, - "response5xxMetered", - "5xx-responses")); + "response5xxMetered", + "5xx-responses")); assertThat(meter2xx.getCount()).isZero(); assertThat(target("response-2xx-metered") - .request() - .get().getStatus()) - .isEqualTo(200); + .request() + .get().getStatus()) + .isEqualTo(200); assertThat(meter4xx.getCount()).isZero(); assertThat(target("response-4xx-metered") - .request() - .get().getStatus()) - .isEqualTo(400); + .request() + .get().getStatus()) + .isEqualTo(400); assertThat(meter5xx.getCount()).isZero(); assertThat(target("response-5xx-metered") - .request() - .get().getStatus()) - .isEqualTo(500); + .request() + .get().getStatus()) + .isEqualTo(500); assertThat(meter2xx.getCount()).isEqualTo(1); assertThat(meter4xx.getCount()).isEqualTo(1); @@ -130,7 +130,7 @@ public void responseMeteredMethodsAreMetered() { } @Test - public void testResourceNotFound() { + void testResourceNotFound() { final Response response = target().path("not-found").request().get(); assertThat(response.getStatus()).isEqualTo(404); @@ -143,11 +143,11 @@ public void testResourceNotFound() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedSubResource.class, "timed")); assertThat(timer.getCount()).isEqualTo(1); diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java index f27e590259..e1c52a6e49 100644 --- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java +++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsMeteredPerClassJerseyTest.java @@ -7,7 +7,7 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.logging.Level; import java.util.logging.Logger; @@ -19,7 +19,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { +class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -39,11 +39,11 @@ protected Application configure() { } @Test - public void meteredPerClassMethodsAreMetered() { + void meteredPerClassMethodsAreMetered() { assertThat(target("meteredPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Meter meter = registry.meter(name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); @@ -51,11 +51,11 @@ public void meteredPerClassMethodsAreMetered() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/meteredPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Meter meter = registry.meter(name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); assertThat(meter.getCount()).isEqualTo(1); diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java index a569225bab..56b38209c8 100644 --- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java +++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsResponseMeteredPerClassJerseyTest.java @@ -8,20 +8,20 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.logging.Level; import java.util.logging.Logger; import static io.dropwizard.metrics5.MetricRegistry.name; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { +class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -43,97 +43,97 @@ protected Application configure() { } @Test - public void responseMetered2xxPerClassMethodsAreMetered() { + void responseMetered2xxPerClassMethodsAreMetered() { assertThat(target("responseMetered2xxPerClass") - .request() - .get().getStatus()) - .isEqualTo(200); + .request() + .get().getStatus()) + .isEqualTo(200); final Meter meter2xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMetered2xxPerClass", - "2xx-responses")); + "responseMetered2xxPerClass", + "2xx-responses")); assertThat(meter2xx.getCount()).isEqualTo(1); } @Test - public void responseMetered4xxPerClassMethodsAreMetered() { + void responseMetered4xxPerClassMethodsAreMetered() { assertThat(target("responseMetered4xxPerClass") - .request() - .get().getStatus()) - .isEqualTo(400); + .request() + .get().getStatus()) + .isEqualTo(400); assertThat(target("responseMeteredBadRequestPerClass") - .request() - .get().getStatus()) - .isEqualTo(400); + .request() + .get().getStatus()) + .isEqualTo(400); final Meter meter4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMetered4xxPerClass", - "4xx-responses")); + "responseMetered4xxPerClass", + "4xx-responses")); final Meter meterException4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMeteredBadRequestPerClass", - "4xx-responses")); + "responseMeteredBadRequestPerClass", + "4xx-responses")); assertThat(meter4xx.getCount()).isEqualTo(1); assertThat(meterException4xx.getCount()).isEqualTo(1); } @Test - public void responseMetered5xxPerClassMethodsAreMetered() { + void responseMetered5xxPerClassMethodsAreMetered() { assertThat(target("responseMetered5xxPerClass") - .request() - .get().getStatus()) - .isEqualTo(500); + .request() + .get().getStatus()) + .isEqualTo(500); final Meter meter5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMetered5xxPerClass", - "5xx-responses")); + "responseMetered5xxPerClass", + "5xx-responses")); assertThat(meter5xx.getCount()).isEqualTo(1); } @Test - public void responseMeteredMappedExceptionPerClassMethodsAreMetered() { + void responseMeteredMappedExceptionPerClassMethodsAreMetered() { assertThat(target("responseMeteredTestExceptionPerClass") - .request() - .get().getStatus()) - .isEqualTo(500); + .request() + .get().getStatus()) + .isEqualTo(500); final Meter meterTestException = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMeteredTestExceptionPerClass", - "5xx-responses")); + "responseMeteredTestExceptionPerClass", + "5xx-responses")); assertThat(meterTestException.getCount()).isEqualTo(1); } @Test - public void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { + void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { try { target("responseMeteredRuntimeExceptionPerClass") - .request() - .get(); + .request() + .get(); fail("expected RuntimeException"); } catch (Exception e) { assertThat(e.getCause()).isInstanceOf(RuntimeException.class); } final Meter meterException5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMeteredRuntimeExceptionPerClass", - "5xx-responses")); + "responseMeteredRuntimeExceptionPerClass", + "5xx-responses")); assertThat(meterException5xx.getCount()).isEqualTo(1); } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/responseMeteredPerClass") - .request() - .get().getStatus()) - .isEqualTo(200); + .request() + .get().getStatus()) + .isEqualTo(200); final Meter meter = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, - "responseMeteredPerClass", - "2xx-responses")); + "responseMeteredPerClass", + "2xx-responses")); assertThat(meter.getCount()).isEqualTo(1); } } diff --git a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java index 840919e6bc..b4016f394f 100644 --- a/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java +++ b/metrics-jersey3/src/test/java/io/dropwizard/metrics5/jersey3/SingletonMetricsTimedPerClassJerseyTest.java @@ -7,7 +7,7 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.logging.Level; import java.util.logging.Logger; @@ -19,7 +19,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { +class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -39,11 +39,11 @@ protected Application configure() { } @Test - public void timedPerClassMethodsAreTimed() { + void timedPerClassMethodsAreTimed() { assertThat(target("timedPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); @@ -51,11 +51,11 @@ public void timedPerClassMethodsAreTimed() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/timedPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); assertThat(timer.getCount()).isEqualTo(1); diff --git a/metrics-jersey31/pom.xml b/metrics-jersey31/pom.xml index 67bd38d262..4b29501b53 100644 --- a/metrics-jersey31/pom.xml +++ b/metrics-jersey31/pom.xml @@ -52,6 +52,13 @@ byte-buddy ${byte-buddy.version} + + org.junit + junit-bom + ${junit5.version} + pom + import + @@ -74,11 +81,10 @@ 3.1.0 - junit - junit - 4.13.1 + org.junit.jupiter + junit-jupiter-api test - + org.assertj assertj-core diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java index 2d1ee61e40..4f5b19beac 100644 --- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java +++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/CustomReservoirImplementationTest.java @@ -7,7 +7,7 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.logging.Level; import java.util.logging.Logger; @@ -15,7 +15,7 @@ import static io.dropwizard.metrics5.MetricRegistry.name; import static org.assertj.core.api.Assertions.assertThat; -public class CustomReservoirImplementationTest extends JerseyTest { +class CustomReservoirImplementationTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -27,18 +27,18 @@ protected Application configure() { this.registry = new MetricRegistry(); return new ResourceConfig() - .register(new MetricsFeature(this.registry, UniformReservoir::new)) - .register(InstrumentedResourceTimedPerClass.class); + .register(new MetricsFeature(this.registry, UniformReservoir::new)) + .register(InstrumentedResourceTimedPerClass.class); } @Test - public void timerHistogramIsUsingCustomReservoirImplementation() { + void timerHistogramIsUsingCustomReservoirImplementation() { assertThat(target("timedPerClass").request().get(String.class)).isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); assertThat(timer) - .extracting("histogram") - .extracting("reservoir") - .isInstanceOf(UniformReservoir.class); + .extracting("histogram") + .extracting("reservoir") + .isInstanceOf(UniformReservoir.class); } } diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java index bc7ba9c155..641f12ddbb 100644 --- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java +++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonFilterMetricsJerseyTest.java @@ -7,8 +7,8 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.logging.Level; import java.util.logging.Logger; @@ -20,7 +20,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} with filter tracking */ -public class SingletonFilterMetricsJerseyTest extends JerseyTest { +class SingletonFilterMetricsJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -40,17 +40,17 @@ protected Application configure() { return config; } - @Before - public void resetClock() { + @BeforeEach + void resetClock() { testClock.tick = 0; } @Test - public void timedMethodsAreTimed() { + void timedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed")); @@ -59,11 +59,11 @@ public void timedMethodsAreTimed() { } @Test - public void explicitNamesAreTimed() { + void explicitNamesAreTimed() { assertThat(target("named") - .request() - .get(String.class)) - .isEqualTo("fancy"); + .request() + .get(String.class)) + .isEqualTo("fancy"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName")); @@ -72,11 +72,11 @@ public void explicitNamesAreTimed() { } @Test - public void absoluteNamesAreTimed() { + void absoluteNamesAreTimed() { assertThat(target("absolute") - .request() - .get(String.class)) - .isEqualTo("absolute"); + .request() + .get(String.class)) + .isEqualTo("absolute"); final Timer timer = registry.timer("absolutelyFancy"); @@ -85,11 +85,11 @@ public void absoluteNamesAreTimed() { } @Test - public void requestFiltersOfTimedMethodsAreTimed() { + void requestFiltersOfTimedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "request", "filtering")); @@ -98,11 +98,11 @@ public void requestFiltersOfTimedMethodsAreTimed() { } @Test - public void responseFiltersOfTimedMethodsAreTimed() { + void responseFiltersOfTimedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "response", "filtering")); @@ -110,11 +110,11 @@ public void responseFiltersOfTimedMethodsAreTimed() { } @Test - public void totalTimeOfTimedMethodsIsTimed() { + void totalTimeOfTimedMethodsIsTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "timed", "total")); @@ -123,11 +123,11 @@ public void totalTimeOfTimedMethodsIsTimed() { } @Test - public void requestFiltersOfNamedMethodsAreTimed() { + void requestFiltersOfNamedMethodsAreTimed() { assertThat(target("named") - .request() - .get(String.class)) - .isEqualTo("fancy"); + .request() + .get(String.class)) + .isEqualTo("fancy"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.class, "fancyName", "request", "filtering")); @@ -136,11 +136,11 @@ public void requestFiltersOfNamedMethodsAreTimed() { } @Test - public void requestFiltersOfAbsoluteMethodsAreTimed() { + void requestFiltersOfAbsoluteMethodsAreTimed() { assertThat(target("absolute") - .request() - .get(String.class)) - .isEqualTo("absolute"); + .request() + .get(String.class)) + .isEqualTo("absolute"); final Timer timer = registry.timer(name("absolutelyFancy", "request", "filtering")); assertThat(timer.getCount()).isEqualTo(1); @@ -148,14 +148,14 @@ public void requestFiltersOfAbsoluteMethodsAreTimed() { } @Test - public void subResourcesFromLocatorsRegisterMetrics() { + void subResourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedFilteredResource.InstrumentedFilteredSubResource.class, - "timed")); + "timed")); assertThat(timer.getCount()).isEqualTo(1); } diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java index 51d5c7398d..ffd14b0e46 100644 --- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java +++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsExceptionMeteredPerClassJerseyTest.java @@ -8,7 +8,7 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.logging.Level; @@ -22,7 +22,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { +class SingletonMetricsExceptionMeteredPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -42,23 +42,23 @@ protected Application configure() { } @Test - public void exceptionMeteredMethodsAreExceptionMetered() { + void exceptionMeteredMethodsAreExceptionMetered() { final Meter meter = registry.meter(name(InstrumentedResourceExceptionMeteredPerClass.class, - "exceptionMetered", - "exceptions")); + "exceptionMetered", + "exceptions")); assertThat(target("exception-metered") - .request() - .get(String.class)) - .isEqualTo("fuh"); + .request() + .get(String.class)) + .isEqualTo("fuh"); assertThat(meter.getCount()).isZero(); try { target("exception-metered") - .queryParam("splode", true) - .request() - .get(String.class); + .queryParam("splode", true) + .request() + .get(String.class); failBecauseExceptionWasNotThrown(ProcessingException.class); } catch (ProcessingException e) { @@ -69,23 +69,23 @@ public void exceptionMeteredMethodsAreExceptionMetered() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { final Meter meter = registry.meter(name(InstrumentedSubResourceExceptionMeteredPerClass.class, - "exceptionMetered", - "exceptions")); + "exceptionMetered", + "exceptions")); assertThat(target("subresource/exception-metered") - .request() - .get(String.class)) - .isEqualTo("fuh"); + .request() + .get(String.class)) + .isEqualTo("fuh"); assertThat(meter.getCount()).isZero(); try { target("subresource/exception-metered") - .queryParam("splode", true) - .request() - .get(String.class); + .queryParam("splode", true) + .request() + .get(String.class); failBecauseExceptionWasNotThrown(ProcessingException.class); } catch (ProcessingException e) { diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java index 832076d70c..caa17e03dd 100644 --- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java +++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsJerseyTest.java @@ -12,7 +12,7 @@ import org.glassfish.jersey.client.ClientResponse; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.logging.Level; @@ -26,7 +26,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsJerseyTest extends JerseyTest { +class SingletonMetricsJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -45,11 +45,11 @@ protected Application configure() { } @Test - public void timedMethodsAreTimed() { + void timedMethodsAreTimed() { assertThat(target("timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedResource.class, "timed")); @@ -57,34 +57,34 @@ public void timedMethodsAreTimed() { } @Test - public void meteredMethodsAreMetered() { + void meteredMethodsAreMetered() { assertThat(target("metered") - .request() - .get(String.class)) - .isEqualTo("woo"); + .request() + .get(String.class)) + .isEqualTo("woo"); final Meter meter = registry.meter(name(InstrumentedResource.class, "metered")); assertThat(meter.getCount()).isEqualTo(1); } @Test - public void exceptionMeteredMethodsAreExceptionMetered() { + void exceptionMeteredMethodsAreExceptionMetered() { final Meter meter = registry.meter(name(InstrumentedResource.class, - "exceptionMetered", - "exceptions")); + "exceptionMetered", + "exceptions")); assertThat(target("exception-metered") - .request() - .get(String.class)) - .isEqualTo("fuh"); + .request() + .get(String.class)) + .isEqualTo("fuh"); assertThat(meter.getCount()).isZero(); try { target("exception-metered") - .queryParam("splode", true) - .request() - .get(String.class); + .queryParam("splode", true) + .request() + .get(String.class); failBecauseExceptionWasNotThrown(ProcessingException.class); } catch (ProcessingException e) { @@ -95,34 +95,34 @@ public void exceptionMeteredMethodsAreExceptionMetered() { } @Test - public void responseMeteredMethodsAreMetered() { + void responseMeteredMethodsAreMetered() { final Meter meter2xx = registry.meter(name(InstrumentedResource.class, - "response2xxMetered", - "2xx-responses")); + "response2xxMetered", + "2xx-responses")); final Meter meter4xx = registry.meter(name(InstrumentedResource.class, - "response4xxMetered", - "4xx-responses")); + "response4xxMetered", + "4xx-responses")); final Meter meter5xx = registry.meter(name(InstrumentedResource.class, - "response5xxMetered", - "5xx-responses")); + "response5xxMetered", + "5xx-responses")); assertThat(meter2xx.getCount()).isZero(); assertThat(target("response-2xx-metered") - .request() - .get().getStatus()) - .isEqualTo(200); + .request() + .get().getStatus()) + .isEqualTo(200); assertThat(meter4xx.getCount()).isZero(); assertThat(target("response-4xx-metered") - .request() - .get().getStatus()) - .isEqualTo(400); + .request() + .get().getStatus()) + .isEqualTo(400); assertThat(meter5xx.getCount()).isZero(); assertThat(target("response-5xx-metered") - .request() - .get().getStatus()) - .isEqualTo(500); + .request() + .get().getStatus()) + .isEqualTo(500); assertThat(meter2xx.getCount()).isEqualTo(1); assertThat(meter4xx.getCount()).isEqualTo(1); @@ -130,7 +130,7 @@ public void responseMeteredMethodsAreMetered() { } @Test - public void testResourceNotFound() { + void testResourceNotFound() { final Response response = target().path("not-found").request().get(); assertThat(response.getStatus()).isEqualTo(404); @@ -143,11 +143,11 @@ public void testResourceNotFound() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/timed") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedSubResource.class, "timed")); assertThat(timer.getCount()).isEqualTo(1); diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java index 24df5a4c5e..3975c55145 100644 --- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java +++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsMeteredPerClassJerseyTest.java @@ -7,7 +7,7 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.logging.Level; import java.util.logging.Logger; @@ -19,7 +19,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { +class SingletonMetricsMeteredPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -39,11 +39,11 @@ protected Application configure() { } @Test - public void meteredPerClassMethodsAreMetered() { + void meteredPerClassMethodsAreMetered() { assertThat(target("meteredPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Meter meter = registry.meter(name(InstrumentedResourceMeteredPerClass.class, "meteredPerClass")); @@ -51,11 +51,11 @@ public void meteredPerClassMethodsAreMetered() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/meteredPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Meter meter = registry.meter(name(InstrumentedSubResourceMeteredPerClass.class, "meteredPerClass")); assertThat(meter.getCount()).isEqualTo(1); diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java index 3b0f9cc43a..931da616b9 100644 --- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java +++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsResponseMeteredPerClassJerseyTest.java @@ -8,20 +8,20 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.logging.Level; import java.util.logging.Logger; import static io.dropwizard.metrics5.MetricRegistry.name; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { +class SingletonMetricsResponseMeteredPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -43,97 +43,97 @@ protected Application configure() { } @Test - public void responseMetered2xxPerClassMethodsAreMetered() { + void responseMetered2xxPerClassMethodsAreMetered() { assertThat(target("responseMetered2xxPerClass") - .request() - .get().getStatus()) - .isEqualTo(200); + .request() + .get().getStatus()) + .isEqualTo(200); final Meter meter2xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMetered2xxPerClass", - "2xx-responses")); + "responseMetered2xxPerClass", + "2xx-responses")); assertThat(meter2xx.getCount()).isEqualTo(1); } @Test - public void responseMetered4xxPerClassMethodsAreMetered() { + void responseMetered4xxPerClassMethodsAreMetered() { assertThat(target("responseMetered4xxPerClass") - .request() - .get().getStatus()) - .isEqualTo(400); + .request() + .get().getStatus()) + .isEqualTo(400); assertThat(target("responseMeteredBadRequestPerClass") - .request() - .get().getStatus()) - .isEqualTo(400); + .request() + .get().getStatus()) + .isEqualTo(400); final Meter meter4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMetered4xxPerClass", - "4xx-responses")); + "responseMetered4xxPerClass", + "4xx-responses")); final Meter meterException4xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMeteredBadRequestPerClass", - "4xx-responses")); + "responseMeteredBadRequestPerClass", + "4xx-responses")); assertThat(meter4xx.getCount()).isEqualTo(1); assertThat(meterException4xx.getCount()).isEqualTo(1); } @Test - public void responseMetered5xxPerClassMethodsAreMetered() { + void responseMetered5xxPerClassMethodsAreMetered() { assertThat(target("responseMetered5xxPerClass") - .request() - .get().getStatus()) - .isEqualTo(500); + .request() + .get().getStatus()) + .isEqualTo(500); final Meter meter5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMetered5xxPerClass", - "5xx-responses")); + "responseMetered5xxPerClass", + "5xx-responses")); assertThat(meter5xx.getCount()).isEqualTo(1); } @Test - public void responseMeteredMappedExceptionPerClassMethodsAreMetered() { + void responseMeteredMappedExceptionPerClassMethodsAreMetered() { assertThat(target("responseMeteredTestExceptionPerClass") - .request() - .get().getStatus()) - .isEqualTo(500); + .request() + .get().getStatus()) + .isEqualTo(500); final Meter meterTestException = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMeteredTestExceptionPerClass", - "5xx-responses")); + "responseMeteredTestExceptionPerClass", + "5xx-responses")); assertThat(meterTestException.getCount()).isEqualTo(1); } @Test - public void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { + void responseMeteredUnmappedExceptionPerClassMethodsAreMetered() { try { target("responseMeteredRuntimeExceptionPerClass") - .request() - .get(); + .request() + .get(); fail("expected RuntimeException"); } catch (Exception e) { assertThat(e.getCause()).isInstanceOf(RuntimeException.class); } final Meter meterException5xx = registry.meter(name(InstrumentedResourceResponseMeteredPerClass.class, - "responseMeteredRuntimeExceptionPerClass", - "5xx-responses")); + "responseMeteredRuntimeExceptionPerClass", + "5xx-responses")); assertThat(meterException5xx.getCount()).isEqualTo(1); } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/responseMeteredPerClass") - .request() - .get().getStatus()) - .isEqualTo(200); + .request() + .get().getStatus()) + .isEqualTo(200); final Meter meter = registry.meter(name(InstrumentedSubResourceResponseMeteredPerClass.class, - "responseMeteredPerClass", - "2xx-responses")); + "responseMeteredPerClass", + "2xx-responses")); assertThat(meter.getCount()).isEqualTo(1); } } diff --git a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java index 344c02d878..7bce0ffb0d 100644 --- a/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java +++ b/metrics-jersey31/src/test/java/io/dropwizard/metrics5/jersey31/SingletonMetricsTimedPerClassJerseyTest.java @@ -7,7 +7,7 @@ import jakarta.ws.rs.core.Application; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.logging.Level; import java.util.logging.Logger; @@ -19,7 +19,7 @@ * Tests registering {@link InstrumentedResourceMethodApplicationListener} as a singleton * in a Jersey {@link ResourceConfig} */ -public class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { +class SingletonMetricsTimedPerClassJerseyTest extends JerseyTest { static { Logger.getLogger("org.glassfish.jersey").setLevel(Level.OFF); } @@ -39,11 +39,11 @@ protected Application configure() { } @Test - public void timedPerClassMethodsAreTimed() { + void timedPerClassMethodsAreTimed() { assertThat(target("timedPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedResourceTimedPerClass.class, "timedPerClass")); @@ -51,11 +51,11 @@ public void timedPerClassMethodsAreTimed() { } @Test - public void subresourcesFromLocatorsRegisterMetrics() { + void subresourcesFromLocatorsRegisterMetrics() { assertThat(target("subresource/timedPerClass") - .request() - .get(String.class)) - .isEqualTo("yay"); + .request() + .get(String.class)) + .isEqualTo("yay"); final Timer timer = registry.timer(name(InstrumentedSubResourceTimedPerClass.class, "timedPerClass")); assertThat(timer.getCount()).isEqualTo(1); diff --git a/metrics-jetty10/pom.xml b/metrics-jetty10/pom.xml index f783531e89..606cb3b5b7 100644 --- a/metrics-jetty10/pom.xml +++ b/metrics-jetty10/pom.xml @@ -87,12 +87,6 @@ ${slf4j.version} runtime - - junit - junit - ${junit.version} - test - org.assertj assertj-core @@ -110,6 +104,18 @@ jetty-client test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.slf4j slf4j-simple diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java index 93820fb5ff..4fae656627 100644 --- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java +++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedConnectionFactoryTest.java @@ -10,9 +10,9 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -22,7 +22,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class InstrumentedConnectionFactoryTest { +class InstrumentedConnectionFactoryTest { private final MetricRegistry registry = new MetricRegistry(); private final Server server = new Server(); private final ServerConnector connector = @@ -31,14 +31,14 @@ public class InstrumentedConnectionFactoryTest { registry.counter("http.active-connections"))); private final HttpClient client = new HttpClient(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { server.setHandler(new AbstractHandler() { @Override public void handle(String target, - Request baseRequest, - HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException { + Request baseRequest, + HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { try (PrintWriter writer = response.getWriter()) { writer.println("OK"); } @@ -51,14 +51,14 @@ public void handle(String target, client.start(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { server.stop(); client.stop(); } @Test - public void instrumentsConnectionTimes() throws Exception { + void instrumentsConnectionTimes() throws Exception { final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); assertThat(response.getStatus()) .isEqualTo(200); @@ -73,7 +73,7 @@ public void instrumentsConnectionTimes() throws Exception { } @Test - public void instrumentsActiveConnections() throws Exception { + void instrumentsActiveConnections() throws Exception { final Counter counter = registry.counter("http.active-connections"); final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java index ef179bd653..24a00b4fdc 100644 --- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java +++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHandlerTest.java @@ -8,10 +8,10 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import javax.servlet.AsyncContext; import javax.servlet.ServletException; @@ -25,15 +25,15 @@ import static org.assertj.core.api.Assertions.assertThat; -public class InstrumentedHandlerTest { +class InstrumentedHandlerTest { private final HttpClient client = new HttpClient(); private final MetricRegistry registry = new MetricRegistry(); private final Server server = new Server(); private final ServerConnector connector = new ServerConnector(server); private final InstrumentedHandler handler = new InstrumentedHandler(registry); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { handler.setName("handler"); handler.setHandler(new TestHandler()); server.addConnector(connector); @@ -42,20 +42,20 @@ public void setUp() throws Exception { client.start(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { server.stop(); client.stop(); } @Test - public void hasAName() throws Exception { + void hasAName() throws Exception { assertThat(handler.getName()) .isEqualTo("handler"); } @Test - public void createsAndRemovesMetricsForTheHandler() throws Exception { + void createsAndRemovesMetricsForTheHandler() throws Exception { final ContentResponse response = client.GET(uri("/hello")); assertThat(response.getStatus()) @@ -100,7 +100,7 @@ public void createsAndRemovesMetricsForTheHandler() throws Exception { } @Test - public void responseTimesAreRecordedForBlockingResponses() throws Exception { + void responseTimesAreRecordedForBlockingResponses() throws Exception { final ContentResponse response = client.GET(uri("/blocking")); @@ -111,8 +111,8 @@ public void responseTimesAreRecordedForBlockingResponses() throws Exception { } @Test - @Ignore("flaky on virtual machines") - public void responseTimesAreRecordedForAsyncResponses() throws Exception { + @Disabled("flaky on virtual machines") + void responseTimesAreRecordedForAsyncResponses() throws Exception { final ContentResponse response = client.GET(uri("/async")); diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java index c90df42788..d43c45609f 100644 --- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java +++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedHttpChannelListenerTest.java @@ -8,9 +8,9 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.servlet.AsyncContext; import javax.servlet.ServletOutputStream; @@ -22,15 +22,15 @@ import static org.assertj.core.api.Assertions.assertThat; -public class InstrumentedHttpChannelListenerTest { +class InstrumentedHttpChannelListenerTest { private final HttpClient client = new HttpClient(); private final Server server = new Server(); private final ServerConnector connector = new ServerConnector(server); private final TestHandler handler = new TestHandler(); private MetricRegistry registry; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { registry = new MetricRegistry(); connector.addBean(new InstrumentedHttpChannelListener(registry, MetricRegistry.name(TestHandler.class, "handler"))); server.addConnector(connector); @@ -39,14 +39,14 @@ public void setUp() throws Exception { client.start(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { server.stop(); client.stop(); } @Test - public void createsMetricsForTheHandler() throws Exception { + void createsMetricsForTheHandler() throws Exception { final ContentResponse response = client.GET(uri("/hello")); assertThat(response.getStatus()) @@ -87,7 +87,7 @@ public void createsMetricsForTheHandler() throws Exception { @Test - public void responseTimesAreRecordedForBlockingResponses() throws Exception { + void responseTimesAreRecordedForBlockingResponses() throws Exception { final ContentResponse response = client.GET(uri("/blocking")); @@ -99,7 +99,7 @@ public void responseTimesAreRecordedForBlockingResponses() throws Exception { } @Test - public void responseTimesAreRecordedForAsyncResponses() throws Exception { + void responseTimesAreRecordedForAsyncResponses() throws Exception { final ContentResponse response = client.GET(uri("/async")); diff --git a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java index 8cec20d21c..aacfd897fa 100644 --- a/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java +++ b/metrics-jetty10/src/test/java/io/dropwizard/metrics5/jetty10/InstrumentedQueuedThreadPoolTest.java @@ -3,25 +3,25 @@ import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class InstrumentedQueuedThreadPoolTest { +class InstrumentedQueuedThreadPoolTest { private static final String PREFIX = "prefix"; private MetricRegistry metricRegistry; private InstrumentedQueuedThreadPool iqtp; - @Before - public void setUp() { + @BeforeEach + void setUp() { metricRegistry = new MetricRegistry(); iqtp = new InstrumentedQueuedThreadPool(metricRegistry); } @Test - public void customMetricsPrefix() throws Exception { + void customMetricsPrefix() throws Exception { iqtp.setPrefix(PREFIX); iqtp.start(); @@ -37,7 +37,7 @@ public void customMetricsPrefix() throws Exception { } @Test - public void metricsPrefixBackwardCompatible() throws Exception { + void metricsPrefixBackwardCompatible() throws Exception { iqtp.start(); assertThat(metricRegistry.getNames()) .extracting(MetricName::getKey) diff --git a/metrics-jetty11/pom.xml b/metrics-jetty11/pom.xml index 3d4147b39e..2f26796938 100644 --- a/metrics-jetty11/pom.xml +++ b/metrics-jetty11/pom.xml @@ -87,12 +87,6 @@ ${slf4j.version} runtime - - junit - junit - ${junit.version} - test - org.assertj assertj-core @@ -110,6 +104,18 @@ jetty-client test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.slf4j slf4j-simple diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java index 37cd2bbac4..d1ca0f0edb 100644 --- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java +++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedConnectionFactoryTest.java @@ -13,16 +13,16 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.PrintWriter; import static org.assertj.core.api.Assertions.assertThat; -public class InstrumentedConnectionFactoryTest { +class InstrumentedConnectionFactoryTest { private final MetricRegistry registry = new MetricRegistry(); private final Server server = new Server(); private final ServerConnector connector = @@ -31,14 +31,14 @@ public class InstrumentedConnectionFactoryTest { registry.counter("http.active-connections"))); private final HttpClient client = new HttpClient(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { server.setHandler(new AbstractHandler() { @Override public void handle(String target, - Request baseRequest, - HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException { + Request baseRequest, + HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { try (PrintWriter writer = response.getWriter()) { writer.println("OK"); } @@ -51,14 +51,14 @@ public void handle(String target, client.start(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { server.stop(); client.stop(); } @Test - public void instrumentsConnectionTimes() throws Exception { + void instrumentsConnectionTimes() throws Exception { final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); assertThat(response.getStatus()) .isEqualTo(200); @@ -73,7 +73,7 @@ public void instrumentsConnectionTimes() throws Exception { } @Test - public void instrumentsActiveConnections() throws Exception { + void instrumentsActiveConnections() throws Exception { final Counter counter = registry.counter("http.active-connections"); final ContentResponse response = client.GET("http://localhost:" + connector.getLocalPort() + "/hello"); diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java index 7f59aaf8ff..a3e5548e4d 100644 --- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java +++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHandlerTest.java @@ -14,10 +14,10 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -25,15 +25,15 @@ import static org.assertj.core.api.Assertions.assertThat; -public class InstrumentedHandlerTest { +class InstrumentedHandlerTest { private final HttpClient client = new HttpClient(); private final MetricRegistry registry = new MetricRegistry(); private final Server server = new Server(); private final ServerConnector connector = new ServerConnector(server); private final InstrumentedHandler handler = new InstrumentedHandler(registry); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { handler.setName("handler"); handler.setHandler(new TestHandler()); server.addConnector(connector); @@ -42,20 +42,20 @@ public void setUp() throws Exception { client.start(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { server.stop(); client.stop(); } @Test - public void hasAName() throws Exception { + void hasAName() throws Exception { assertThat(handler.getName()) .isEqualTo("handler"); } @Test - public void createsAndRemovesMetricsForTheHandler() throws Exception { + void createsAndRemovesMetricsForTheHandler() throws Exception { final ContentResponse response = client.GET(uri("/hello")); assertThat(response.getStatus()) @@ -100,7 +100,7 @@ public void createsAndRemovesMetricsForTheHandler() throws Exception { } @Test - public void responseTimesAreRecordedForBlockingResponses() throws Exception { + void responseTimesAreRecordedForBlockingResponses() throws Exception { final ContentResponse response = client.GET(uri("/blocking")); @@ -111,8 +111,8 @@ public void responseTimesAreRecordedForBlockingResponses() throws Exception { } @Test - @Ignore("flaky on virtual machines") - public void responseTimesAreRecordedForAsyncResponses() throws Exception { + @Disabled("flaky on virtual machines") + void responseTimesAreRecordedForAsyncResponses() throws Exception { final ContentResponse response = client.GET(uri("/async")); diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java index 626a526dc8..7596e28214 100644 --- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java +++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedHttpChannelListenerTest.java @@ -13,24 +13,24 @@ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; import static org.assertj.core.api.Assertions.assertThat; -public class InstrumentedHttpChannelListenerTest { +class InstrumentedHttpChannelListenerTest { private final HttpClient client = new HttpClient(); private final Server server = new Server(); private final ServerConnector connector = new ServerConnector(server); private final TestHandler handler = new TestHandler(); private MetricRegistry registry; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { registry = new MetricRegistry(); connector.addBean(new InstrumentedHttpChannelListener(registry, MetricRegistry.name(TestHandler.class, "handler"))); server.addConnector(connector); @@ -39,14 +39,14 @@ public void setUp() throws Exception { client.start(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { server.stop(); client.stop(); } @Test - public void createsMetricsForTheHandler() throws Exception { + void createsMetricsForTheHandler() throws Exception { final ContentResponse response = client.GET(uri("/hello")); assertThat(response.getStatus()) @@ -87,7 +87,7 @@ public void createsMetricsForTheHandler() throws Exception { @Test - public void responseTimesAreRecordedForBlockingResponses() throws Exception { + void responseTimesAreRecordedForBlockingResponses() throws Exception { final ContentResponse response = client.GET(uri("/blocking")); @@ -99,7 +99,7 @@ public void responseTimesAreRecordedForBlockingResponses() throws Exception { } @Test - public void responseTimesAreRecordedForAsyncResponses() throws Exception { + void responseTimesAreRecordedForAsyncResponses() throws Exception { final ContentResponse response = client.GET(uri("/async")); diff --git a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java index 3c492bfd97..a7fd60da7b 100644 --- a/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java +++ b/metrics-jetty11/src/test/java/io/dropwizard/metrics5/jetty11/InstrumentedQueuedThreadPoolTest.java @@ -3,25 +3,25 @@ import io.dropwizard.metrics5.MetricName; import io.dropwizard.metrics5.MetricRegistry; import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class InstrumentedQueuedThreadPoolTest { +class InstrumentedQueuedThreadPoolTest { private static final String PREFIX = "prefix"; private MetricRegistry metricRegistry; private InstrumentedQueuedThreadPool iqtp; - @Before - public void setUp() { + @BeforeEach + void setUp() { metricRegistry = new MetricRegistry(); iqtp = new InstrumentedQueuedThreadPool(metricRegistry); } @Test - public void customMetricsPrefix() throws Exception { + void customMetricsPrefix() throws Exception { iqtp.setPrefix(PREFIX); iqtp.start(); @@ -37,7 +37,7 @@ public void customMetricsPrefix() throws Exception { } @Test - public void metricsPrefixBackwardCompatible() throws Exception { + void metricsPrefixBackwardCompatible() throws Exception { iqtp.start(); assertThat(metricRegistry.getNames()) .extracting(MetricName::getKey) diff --git a/metrics-jmx/pom.xml b/metrics-jmx/pom.xml index 482d6ce024..da9eb44160 100644 --- a/metrics-jmx/pom.xml +++ b/metrics-jmx/pom.xml @@ -45,18 +45,24 @@ slf4j-api ${slf4j.version} - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core diff --git a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java index 1ca3e3125c..a1f991b5c2 100644 --- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java +++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/DefaultObjectNameFactoryTest.java @@ -1,17 +1,17 @@ package io.dropwizard.metrics5.jmx; import io.dropwizard.metrics5.MetricName; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.management.ObjectName; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThat; -public class DefaultObjectNameFactoryTest { +class DefaultObjectNameFactoryTest { @Test - public void createsObjectNameWithDomainInInput() { + void createsObjectNameWithDomainInInput() { DefaultObjectNameFactory f = new DefaultObjectNameFactory(); ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.dots").tagged("foo", "bar", "baz", "biz")); assertThat(on.getDomain()).isEqualTo("com.domain"); @@ -20,7 +20,7 @@ public void createsObjectNameWithDomainInInput() { } @Test - public void createsObjectNameWithNameAsKeyPropertyName() { + void createsObjectNameWithNameAsKeyPropertyName() { DefaultObjectNameFactory f = new DefaultObjectNameFactory(); ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.dots").tagged("foo", "bar", "baz", "biz")); assertThat(on.getKeyProperty("name")).isEqualTo("something.with.dots"); @@ -30,10 +30,10 @@ public void createsObjectNameWithNameAsKeyPropertyName() { } @Test - public void createsObjectNameWithNameWithDisallowedUnquotedCharacters() { + void createsObjectNameWithNameWithDisallowedUnquotedCharacters() { DefaultObjectNameFactory f = new DefaultObjectNameFactory(); ObjectName on = f.createName("type", "com.domain", MetricName.build("something.with.quotes(\"ABcd\")").tagged("foo", "bar", "baz", "biz")); - assertThatCode(() -> new ObjectName(on.toString())).doesNotThrowAnyException(); + assertThatCode(() -> new ObjectName(on.toString())).doesNotThrowAnyException(); assertThat(on.getKeyProperty("name")).isEqualTo("\"something.with.quotes(\\\"ABcd\\\")\""); assertThat(on.getKeyProperty("foo")).isEqualTo("bar"); assertThat(on.getKeyProperty("baz")).isEqualTo("biz"); diff --git a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java index 5d0cabd469..66d5e769e5 100644 --- a/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java +++ b/metrics-jmx/src/test/java/io/dropwizard/metrics5/jmx/JmxReporterTest.java @@ -9,9 +9,9 @@ import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.Snapshot; import io.dropwizard.metrics5.Timer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.management.Attribute; import javax.management.AttributeList; @@ -36,7 +36,7 @@ import static org.mockito.Mockito.when; @SuppressWarnings("rawtypes") -public class JmxReporterTest { +class JmxReporterTest { private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); private final String name = UUID.randomUUID().toString().replaceAll("[{\\-}]", ""); private final MetricRegistry registry = new MetricRegistry(); @@ -57,8 +57,8 @@ public class JmxReporterTest { private final ObjectNameFactory mockObjectNameFactory = mock(ObjectNameFactory.class); private final ObjectNameFactory concreteObjectNameFactory = reporter.getObjectNameFactory(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(gauge.getValue()).thenReturn(1); when(counter.getCount()).thenReturn(100L); @@ -119,13 +119,13 @@ public void setUp() throws Exception { reporter.start(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { reporter.stop(); } @Test - public void registersMBeansForMetricObjectsUsingProvidedObjectNameFactory() throws Exception { + void registersMBeansForMetricObjectsUsingProvidedObjectNameFactory() throws Exception { ObjectName n = new ObjectName(name + ":name=dummy"); try { String widgetName = "something"; @@ -148,7 +148,7 @@ public void registersMBeansForMetricObjectsUsingProvidedObjectNameFactory() thro } @Test - public void registersMBeansForGauges() throws Exception { + void registersMBeansForGauges() throws Exception { final AttributeList attributes = getAttributes("gauges", "gauge", "Value", "Number"); assertThat(values(attributes)) @@ -156,7 +156,7 @@ public void registersMBeansForGauges() throws Exception { } @Test - public void registersMBeansForCounters() throws Exception { + void registersMBeansForCounters() throws Exception { final AttributeList attributes = getAttributes("counters", "test.counter", "Count"); assertThat(values(attributes)) @@ -164,7 +164,7 @@ public void registersMBeansForCounters() throws Exception { } @Test - public void registersMBeansForHistograms() throws Exception { + void registersMBeansForHistograms() throws Exception { final AttributeList attributes = getAttributes("histograms", "test.histogram", "Count", "Sum", @@ -197,7 +197,7 @@ public void registersMBeansForHistograms() throws Exception { } @Test - public void registersMBeansForMeters() throws Exception { + void registersMBeansForMeters() throws Exception { final AttributeList attributes = getAttributes("meters", "test.meter", "Count", "Sum", @@ -218,7 +218,7 @@ public void registersMBeansForMeters() throws Exception { } @Test - public void registersMBeansForTimers() throws Exception { + void registersMBeansForTimers() throws Exception { final AttributeList attributes = getAttributes("timers", "test.another.timer", "Count", "Sum", @@ -261,7 +261,7 @@ public void registersMBeansForTimers() throws Exception { } @Test - public void cleansUpAfterItselfWhenStopped() throws Exception { + void cleansUpAfterItselfWhenStopped() throws Exception { reporter.stop(); try { @@ -273,7 +273,7 @@ public void cleansUpAfterItselfWhenStopped() throws Exception { } @Test - public void objectNameModifyingMBeanServer() throws Exception { + void objectNameModifyingMBeanServer() throws Exception { MBeanServer mockedMBeanServer = mock(MBeanServer.class); // overwrite the objectName @@ -298,7 +298,7 @@ public void objectNameModifyingMBeanServer() throws Exception { } @Test - public void testJmxMetricNameWithAsterisk() { + void testJmxMetricNameWithAsterisk() { MetricRegistry metricRegistry = new MetricRegistry(); JmxReporter.forRegistry(metricRegistry).build().start(); metricRegistry.counter("test*"); diff --git a/metrics-json/pom.xml b/metrics-json/pom.xml index 976edf5e52..0ccc5397c2 100644 --- a/metrics-json/pom.xml +++ b/metrics-json/pom.xml @@ -61,18 +61,24 @@ com.fasterxml.jackson.core jackson-databind - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core diff --git a/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java b/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java index fbf62f3101..b7e8f0ee01 100644 --- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java +++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/HealthCheckModuleTest.java @@ -2,7 +2,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.dropwizard.metrics5.health.HealthCheck; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.math.BigInteger; @@ -11,64 +11,64 @@ import static org.assertj.core.api.Assertions.assertThat; -public class HealthCheckModuleTest { +class HealthCheckModuleTest { private final ObjectMapper mapper = new ObjectMapper().registerModule(new HealthCheckModule()); @Test - public void serializesAHealthyResult() throws Exception { + void serializesAHealthyResult() throws Exception { HealthCheck.Result result = HealthCheck.Result.healthy(); assertThat(mapper.writeValueAsString(result)) - .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); + .isEqualTo("{\"healthy\":true,\"duration\":0,\"timestamp\":\"" + result.getTimestamp() + "\"}"); } @Test - public void serializesAHealthyResultWithAMessage() throws Exception { + void serializesAHealthyResultWithAMessage() throws Exception { HealthCheck.Result result = HealthCheck.Result.healthy("yay for %s", "me"); assertThat(mapper.writeValueAsString(result)) - .isEqualTo("{" + - "\"healthy\":true," + - "\"message\":\"yay for me\"," + - "\"duration\":0," + - "\"timestamp\":\"" + result.getTimestamp() + "\"" + - "}"); + .isEqualTo("{" + + "\"healthy\":true," + + "\"message\":\"yay for me\"," + + "\"duration\":0," + + "\"timestamp\":\"" + result.getTimestamp() + "\"" + + "}"); } @Test - public void serializesAnUnhealthyResult() throws Exception { + void serializesAnUnhealthyResult() throws Exception { HealthCheck.Result result = HealthCheck.Result.unhealthy("boo"); assertThat(mapper.writeValueAsString(result)) - .isEqualTo("{" + - "\"healthy\":false," + - "\"message\":\"boo\"," + - "\"duration\":0," + - "\"timestamp\":\"" + result.getTimestamp() + "\"" + - "}"); + .isEqualTo("{" + + "\"healthy\":false," + + "\"message\":\"boo\"," + + "\"duration\":0," + + "\"timestamp\":\"" + result.getTimestamp() + "\"" + + "}"); } @Test - public void serializesAnUnhealthyResultWithAnException() throws Exception { + void serializesAnUnhealthyResultWithAnException() throws Exception { final RuntimeException e = new RuntimeException("oh no"); e.setStackTrace(new StackTraceElement[]{ - new StackTraceElement("Blah", "bloo", "Blah.java", 100) + new StackTraceElement("Blah", "bloo", "Blah.java", 100) }); HealthCheck.Result result = HealthCheck.Result.unhealthy(e); assertThat(mapper.writeValueAsString(result)) - .isEqualTo("{" + - "\"healthy\":false," + - "\"message\":\"oh no\"," + - "\"error\":{" + - "\"type\":\"java.lang.RuntimeException\"," + - "\"message\":\"oh no\"," + - "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" + - "}," + - "\"duration\":0," + - "\"timestamp\":\"" + result.getTimestamp() + "\"" + - "}"); + .isEqualTo("{" + + "\"healthy\":false," + + "\"message\":\"oh no\"," + + "\"error\":{" + + "\"type\":\"java.lang.RuntimeException\"," + + "\"message\":\"oh no\"," + + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" + + "}," + + "\"duration\":0," + + "\"timestamp\":\"" + result.getTimestamp() + "\"" + + "}"); } @Test - public void serializesAnUnhealthyResultWithNestedExceptions() throws Exception { + void serializesAnUnhealthyResultWithNestedExceptions() throws Exception { final RuntimeException a = new RuntimeException("oh no"); a.setStackTrace(new StackTraceElement[]{ new StackTraceElement("Blah", "bloo", "Blah.java", 100) @@ -81,58 +81,58 @@ public void serializesAnUnhealthyResultWithNestedExceptions() throws Exception { HealthCheck.Result result = HealthCheck.Result.unhealthy(b); assertThat(mapper.writeValueAsString(result)) - .isEqualTo("{" + - "\"healthy\":false," + - "\"message\":\"oh well\"," + - "\"error\":{" + - "\"type\":\"java.lang.RuntimeException\"," + - "\"message\":\"oh well\"," + - "\"stack\":[\"Blah.blee(Blah.java:150)\"]," + - "\"cause\":{" + - "\"type\":\"java.lang.RuntimeException\"," + - "\"message\":\"oh no\"," + - "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" + - "}" + - "}," + - "\"duration\":0," + - "\"timestamp\":\"" + result.getTimestamp() + "\"" + - "}"); + .isEqualTo("{" + + "\"healthy\":false," + + "\"message\":\"oh well\"," + + "\"error\":{" + + "\"type\":\"java.lang.RuntimeException\"," + + "\"message\":\"oh well\"," + + "\"stack\":[\"Blah.blee(Blah.java:150)\"]," + + "\"cause\":{" + + "\"type\":\"java.lang.RuntimeException\"," + + "\"message\":\"oh no\"," + + "\"stack\":[\"Blah.bloo(Blah.java:100)\"]" + + "}" + + "}," + + "\"duration\":0," + + "\"timestamp\":\"" + result.getTimestamp() + "\"" + + "}"); } @Test - public void serializeResultWithDetail() throws Exception { + void serializeResultWithDetail() throws Exception { Map complex = new LinkedHashMap<>(); complex.put("field", "value"); HealthCheck.Result result = HealthCheck.Result.builder() - .healthy() - .withDetail("boolean", true) - .withDetail("integer", 1) - .withDetail("long", 2L) - .withDetail("float", 3.546F) - .withDetail("double", 4.567D) - .withDetail("BigInteger", new BigInteger("12345")) - .withDetail("BigDecimal", new BigDecimal("12345.56789")) - .withDetail("String", "string") - .withDetail("complex", complex) - .build(); + .healthy() + .withDetail("boolean", true) + .withDetail("integer", 1) + .withDetail("long", 2L) + .withDetail("float", 3.546F) + .withDetail("double", 4.567D) + .withDetail("BigInteger", new BigInteger("12345")) + .withDetail("BigDecimal", new BigDecimal("12345.56789")) + .withDetail("String", "string") + .withDetail("complex", complex) + .build(); assertThat(mapper.writeValueAsString(result)) - .isEqualTo("{" + - "\"healthy\":true," + - "\"duration\":0," + - "\"boolean\":true," + - "\"integer\":1," + - "\"long\":2," + - "\"float\":3.546," + - "\"double\":4.567," + - "\"BigInteger\":12345," + - "\"BigDecimal\":12345.56789," + - "\"String\":\"string\"," + - "\"complex\":{" + - "\"field\":\"value\"" + - "}," + - "\"timestamp\":\"" + result.getTimestamp() + "\"" + - "}"); + .isEqualTo("{" + + "\"healthy\":true," + + "\"duration\":0," + + "\"boolean\":true," + + "\"integer\":1," + + "\"long\":2," + + "\"float\":3.546," + + "\"double\":4.567," + + "\"BigInteger\":12345," + + "\"BigDecimal\":12345.56789," + + "\"String\":\"string\"," + + "\"complex\":{" + + "\"field\":\"value\"" + + "}," + + "\"timestamp\":\"" + result.getTimestamp() + "\"" + + "}"); } } diff --git a/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java b/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java index 17c1a3f0c4..1329c8a091 100644 --- a/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java +++ b/metrics-json/src/test/java/io/dropwizard/metrics5/json/MetricsModuleTest.java @@ -9,7 +9,7 @@ import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.Snapshot; import io.dropwizard.metrics5.Timer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; @@ -17,12 +17,12 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class MetricsModuleTest { +class MetricsModuleTest { private final ObjectMapper mapper = new ObjectMapper().registerModule( new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, false, MetricFilter.ALL)); @Test - public void serializesGauges() throws Exception { + void serializesGauges() throws Exception { final Gauge gauge = () -> 100; assertThat(mapper.writeValueAsString(gauge)) @@ -30,7 +30,7 @@ public void serializesGauges() throws Exception { } @Test - public void serializesGaugesThatThrowExceptions() throws Exception { + void serializesGaugesThatThrowExceptions() throws Exception { final Gauge gauge = () -> { throw new IllegalArgumentException("poops"); }; @@ -40,7 +40,7 @@ public void serializesGaugesThatThrowExceptions() throws Exception { } @Test - public void serializesCounters() throws Exception { + void serializesCounters() throws Exception { final Counter counter = mock(Counter.class); when(counter.getCount()).thenReturn(100L); @@ -49,7 +49,7 @@ public void serializesCounters() throws Exception { } @Test - public void serializesHistograms() throws Exception { + void serializesHistograms() throws Exception { final Histogram histogram = mock(Histogram.class); when(histogram.getCount()).thenReturn(1L); @@ -102,7 +102,7 @@ public void serializesHistograms() throws Exception { } @Test - public void serializesMeters() throws Exception { + void serializesMeters() throws Exception { final Meter meter = mock(Meter.class); when(meter.getCount()).thenReturn(1L); when(meter.getMeanRate()).thenReturn(2.0); @@ -121,7 +121,7 @@ public void serializesMeters() throws Exception { } @Test - public void serializesTimers() throws Exception { + void serializesTimers() throws Exception { final Timer timer = mock(Timer.class); when(timer.getCount()).thenReturn(1L); when(timer.getMeanRate()).thenReturn(2.0); @@ -195,7 +195,7 @@ public void serializesTimers() throws Exception { } @Test - public void serializesMetricRegistries() throws Exception { + void serializesMetricRegistries() throws Exception { final MetricRegistry registry = new MetricRegistry(); assertThat(mapper.writeValueAsString(registry)) diff --git a/metrics-jvm/pom.xml b/metrics-jvm/pom.xml index c910f5aef7..6457561148 100644 --- a/metrics-jvm/pom.xml +++ b/metrics-jvm/pom.xml @@ -47,18 +47,24 @@ slf4j-api ${slf4j.version} - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java index fb6bada1c9..0e2126ff1d 100644 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/BufferPoolMetricSetTest.java @@ -2,8 +2,8 @@ import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricName; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; @@ -14,7 +14,7 @@ import static org.mockito.Mockito.when; @SuppressWarnings("rawtypes") -public class BufferPoolMetricSetTest { +class BufferPoolMetricSetTest { private static final MetricName DIRECT = MetricName.build("direct"); private static final MetricName MAPPED = MetricName.build("mapped"); @@ -31,15 +31,15 @@ public class BufferPoolMetricSetTest { private ObjectName mapped; private ObjectName direct; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { this.mapped = new ObjectName("java.nio:type=BufferPool,name=mapped"); this.direct = new ObjectName("java.nio:type=BufferPool,name=direct"); } @Test - public void includesGaugesForDirectAndMappedPools() { + void includesGaugesForDirectAndMappedPools() { assertThat(buffers.getMetrics().keySet()) .containsOnly(DIRECT_COUNT, DIRECT_USED, @@ -50,7 +50,7 @@ public void includesGaugesForDirectAndMappedPools() { } @Test - public void ignoresGaugesForObjectsWhichCannotBeFound() throws Exception { + void ignoresGaugesForObjectsWhichCannotBeFound() throws Exception { when(mBeanServer.getMBeanInfo(mapped)).thenThrow(new InstanceNotFoundException()); assertThat(buffers.getMetrics().keySet()) @@ -60,7 +60,7 @@ public void ignoresGaugesForObjectsWhichCannotBeFound() throws Exception { } @Test - public void includesAGaugeForDirectCount() throws Exception { + void includesAGaugeForDirectCount() throws Exception { final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_COUNT); when(mBeanServer.getAttribute(direct, "Count")).thenReturn(100); @@ -70,7 +70,7 @@ public void includesAGaugeForDirectCount() throws Exception { } @Test - public void includesAGaugeForDirectMemoryUsed() throws Exception { + void includesAGaugeForDirectMemoryUsed() throws Exception { final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_USED); when(mBeanServer.getAttribute(direct, "MemoryUsed")).thenReturn(100); @@ -80,7 +80,7 @@ public void includesAGaugeForDirectMemoryUsed() throws Exception { } @Test - public void includesAGaugeForDirectCapacity() throws Exception { + void includesAGaugeForDirectCapacity() throws Exception { final Gauge gauge = (Gauge) buffers.getMetrics().get(DIRECT_CAPACITY); when(mBeanServer.getAttribute(direct, "TotalCapacity")).thenReturn(100); @@ -90,7 +90,7 @@ public void includesAGaugeForDirectCapacity() throws Exception { } @Test - public void includesAGaugeForMappedCount() throws Exception { + void includesAGaugeForMappedCount() throws Exception { final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_COUNT); when(mBeanServer.getAttribute(mapped, "Count")).thenReturn(100); @@ -100,7 +100,7 @@ public void includesAGaugeForMappedCount() throws Exception { } @Test - public void includesAGaugeForMappedMemoryUsed() throws Exception { + void includesAGaugeForMappedMemoryUsed() throws Exception { final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_USED); when(mBeanServer.getAttribute(mapped, "MemoryUsed")).thenReturn(100); @@ -110,7 +110,7 @@ public void includesAGaugeForMappedMemoryUsed() throws Exception { } @Test - public void includesAGaugeForMappedCapacity() throws Exception { + void includesAGaugeForMappedCapacity() throws Exception { final Gauge gauge = (Gauge) buffers.getMetrics().get(MAPPED_CAPACITY); when(mBeanServer.getAttribute(mapped, "TotalCapacity")).thenReturn(100); diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java index e2fc8ebdc3..1a9e9429a5 100644 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ClassLoadingGaugeSetTest.java @@ -2,8 +2,8 @@ import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricName; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.management.ClassLoadingMXBean; @@ -12,25 +12,25 @@ import static org.mockito.Mockito.when; @SuppressWarnings("rawtypes") -public class ClassLoadingGaugeSetTest { +class ClassLoadingGaugeSetTest { private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class); private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl); - @Before - public void setUp() { + @BeforeEach + void setUp() { when(cl.getTotalLoadedClassCount()).thenReturn(2L); when(cl.getUnloadedClassCount()).thenReturn(1L); } @Test - public void loadedGauge() { + void loadedGauge() { final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("loaded")); assertThat(gauge.getValue()).isEqualTo(2L); } @Test - public void unLoadedGauge() { + void unLoadedGauge() { final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("unloaded")); assertThat(gauge.getValue()).isEqualTo(1L); } diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java index 5a061ac7d6..59c35591b3 100644 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/CpuTimeClockTest.java @@ -1,16 +1,16 @@ package io.dropwizard.metrics5.jvm; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.management.ManagementFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.offset; -public class CpuTimeClockTest { +class CpuTimeClockTest { @Test - public void cpuTimeClock() { + void cpuTimeClock() { final CpuTimeClock clock = new CpuTimeClock(); final long clockTime = clock.getTime(); diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java deleted file mode 100644 index e072b013a1..0000000000 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeSunManagementNotExistsTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package io.dropwizard.metrics5.jvm; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.InitializationError; - -import java.io.File; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.security.AccessController; -import java.security.CodeSource; -import java.security.PermissionCollection; -import java.security.Permissions; -import java.security.PrivilegedAction; -import java.util.LinkedHashSet; -import java.util.Set; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(FileDescriptorRatioGaugeSunManagementNotExistsTest.SunManagementNotExistsTestRunner.class) -public class FileDescriptorRatioGaugeSunManagementNotExistsTest { - - @Test - public void validateFileDescriptorRatioWhenSunManagementNotExists() { - assertThat(new FileDescriptorRatioGauge().getValue()).isNaN(); - } - - public static class SunManagementNotExistsTestRunner extends BlockJUnit4ClassRunner { - - public SunManagementNotExistsTestRunner(Class clazz) throws InitializationError { - super(getFromSunManagementNotExistsClassLoader(clazz)); - } - - private static Class getFromSunManagementNotExistsClassLoader(Class clazz) throws InitializationError { - try { - return Class.forName(clazz.getName(), true, - new SunManagementNotExistsClassLoader(SunManagementNotExistsTestRunner.class.getClassLoader())); - } catch (ClassNotFoundException e) { - throw new InitializationError(e); - } - } - } - - public static class SunManagementNotExistsClassLoader extends URLClassLoader { - private static final URL[] CLASSPATH_ENTRY_URLS; - private static final PermissionCollection NO_PERMS = new Permissions(); - - static { - String[] classpathEntries = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public String run() { - return System.getProperty("java.class.path"); - } - }).split(File.pathSeparator); - CLASSPATH_ENTRY_URLS = getClasspathEntryUrls(classpathEntries); - } - - private static URL[] getClasspathEntryUrls(String... classpathEntries) { - Set classpathEntryUrls = new LinkedHashSet<>(classpathEntries.length, 1); - for (String classpathEntry : classpathEntries) { - URL classpathEntryUrl = getClasspathEntryUrl(classpathEntry); - if (classpathEntryUrl != null) { - classpathEntryUrls.add(classpathEntryUrl); - } - } - return classpathEntryUrls.toArray(new URL[classpathEntryUrls.size()]); - } - - private static URL getClasspathEntryUrl(String classpathEntry) { - try { - if (classpathEntry.endsWith(".jar")) { - return new URL("file:jar:" + classpathEntry); - } - if (!classpathEntry.endsWith("/")) { - classpathEntry = classpathEntry + "/"; - } - return new URL("file:" + classpathEntry); - } catch (MalformedURLException mue) { - // do nothing - } - return null; - } - - public SunManagementNotExistsClassLoader(ClassLoader parent) { - super(CLASSPATH_ENTRY_URLS, parent); - } - - @Override - protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - if (getClass().getName().equals(name)) { - return getClass(); - } - if (name.startsWith("com.sun.management.")) { - throw new ClassNotFoundException(name); - } - if (name.startsWith("io.dropwizard.metrics5.jvm.")) { - return loadMetricsClasses(name); - } - return super.loadClass(name, resolve); - } - - private Class loadMetricsClasses(String name) throws ClassNotFoundException { - Class ret = findLoadedClass(name); - if (ret != null) { - return ret; - } - return findClass(name); - } - - @Override - protected PermissionCollection getPermissions(CodeSource codesource) { - return NO_PERMS; - } - } -} diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java index 2e0e8a0a9d..f90ed55d29 100644 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/FileDescriptorRatioGaugeTest.java @@ -2,36 +2,36 @@ import com.sun.management.UnixOperatingSystemMXBean; import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @SuppressWarnings("UnusedDeclaration") -public class FileDescriptorRatioGaugeTest { +class FileDescriptorRatioGaugeTest { private final UnixOperatingSystemMXBean os = mock(UnixOperatingSystemMXBean.class); private final FileDescriptorRatioGauge gauge = new FileDescriptorRatioGauge(os); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(os.getOpenFileDescriptorCount()).thenReturn(10L); when(os.getMaxFileDescriptorCount()).thenReturn(100L); } @Test - public void calculatesTheRatioOfUsedToTotalFileDescriptors() { + void calculatesTheRatioOfUsedToTotalFileDescriptors() { Assertions.assertThat(gauge.getValue()) .isEqualTo(0.1); } @Test - public void validateFileDescriptorRatioPresenceOnNixPlatforms() { + void validateFileDescriptorRatioPresenceOnNixPlatforms() { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); assumeTrue(osBean instanceof com.sun.management.UnixOperatingSystemMXBean); @@ -41,7 +41,7 @@ public void validateFileDescriptorRatioPresenceOnNixPlatforms() { } @Test - public void returnsNaNWhenTheInformationIsUnavailable() { + void returnsNaNWhenTheInformationIsUnavailable() { Assertions.assertThat(new FileDescriptorRatioGauge(mock(OperatingSystemMXBean.class)).getValue()) .isNaN(); } diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java index 5420de97a6..753368a0e0 100644 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/GarbageCollectorMetricSetTest.java @@ -2,8 +2,8 @@ import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricName; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.management.GarbageCollectorMXBean; import java.util.Collections; @@ -13,42 +13,42 @@ import static org.mockito.Mockito.when; @SuppressWarnings("unchecked") -public class GarbageCollectorMetricSetTest { +class GarbageCollectorMetricSetTest { private final GarbageCollectorMXBean gc = mock(GarbageCollectorMXBean.class); private final GarbageCollectorMetricSet metrics = new GarbageCollectorMetricSet(Collections.singletonList(gc)); private static final MetricName PS_OLDGEN_TIME = MetricName.build("PS-OldGen.time"); private static final MetricName PS_OLDGEN_COUNT = MetricName.build("PS-OldGen.count"); - @Before - public void setUp() { + @BeforeEach + void setUp() { when(gc.getName()).thenReturn("PS OldGen"); when(gc.getCollectionCount()).thenReturn(1L); when(gc.getCollectionTime()).thenReturn(2L); } @Test - public void hasGaugesForGcCountsAndElapsedTimes() { + void hasGaugesForGcCountsAndElapsedTimes() { assertThat(metrics.getMetrics().keySet()) .containsOnly(PS_OLDGEN_TIME, PS_OLDGEN_COUNT); } @Test - public void hasAGaugeForGcCounts() { + void hasAGaugeForGcCounts() { final Gauge gauge = (Gauge) metrics.getMetrics().get(PS_OLDGEN_COUNT); assertThat(gauge.getValue()) .isEqualTo(1L); } @Test - public void hasAGaugeForGcTimes() { + void hasAGaugeForGcTimes() { final Gauge gauge = (Gauge) metrics.getMetrics().get(PS_OLDGEN_TIME); assertThat(gauge.getValue()) .isEqualTo(2L); } @Test - public void autoDiscoversGCs() { + void autoDiscoversGCs() { assertThat(new GarbageCollectorMetricSet().getMetrics().keySet()) .isNotEmpty(); } diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java index e39bcfefad..6395a8f125 100644 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JmxAttributeGaugeTest.java @@ -11,11 +11,11 @@ import javax.management.ObjectInstance; import javax.management.ObjectName; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -public class JmxAttributeGaugeTest { +class JmxAttributeGaugeTest { private static MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); @@ -32,14 +32,14 @@ public Long getValue() { } } - @BeforeClass - public static void setUp() throws Exception { + @BeforeAll + static void setUp() throws Exception { registerMBean(new ObjectName("JmxAttributeGaugeTest:type=test,name=test1")); registerMBean(new ObjectName("JmxAttributeGaugeTest:type=test,name=test2")); } - @AfterClass - public static void tearDown() { + @AfterAll + static void tearDown() { for (ObjectName objectName : registeredMBeans) { try { mBeanServer.unregisterMBean(objectName); @@ -50,7 +50,7 @@ public static void tearDown() { } @Test - public void returnsJmxAttribute() throws Exception { + void returnsJmxAttribute() throws Exception { ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); @@ -59,7 +59,7 @@ public void returnsJmxAttribute() throws Exception { } @Test - public void returnsNullIfAttributeDoesNotExist() throws Exception { + void returnsNullIfAttributeDoesNotExist() throws Exception { ObjectName objectName = new ObjectName("java.lang:type=ClassLoading"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "DoesNotExist"); @@ -67,7 +67,7 @@ public void returnsNullIfAttributeDoesNotExist() throws Exception { } @Test - public void returnsNullIfMBeanNotFound() throws Exception { + void returnsNullIfMBeanNotFound() throws Exception { ObjectName objectName = new ObjectName("foo.bar:type=NoSuchMBean"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "LoadedClassCount"); @@ -75,7 +75,7 @@ public void returnsNullIfMBeanNotFound() throws Exception { } @Test - public void returnsAttributeForObjectNamePattern() throws Exception { + void returnsAttributeForObjectNamePattern() throws Exception { ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:name=test1,*"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); @@ -84,7 +84,7 @@ public void returnsAttributeForObjectNamePattern() throws Exception { } @Test - public void returnsNullIfObjectNamePatternAmbiguous() throws Exception { + void returnsNullIfObjectNamePatternAmbiguous() throws Exception { ObjectName objectName = new ObjectName("JmxAttributeGaugeTest:type=test,*"); JmxAttributeGauge gauge = new JmxAttributeGauge(mBeanServer, objectName, "Value"); diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java index 5cdea96f08..c237edf8f1 100644 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/JvmAttributeGaugeSetTest.java @@ -2,8 +2,8 @@ import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricName; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.management.RuntimeMXBean; @@ -12,12 +12,12 @@ import static org.mockito.Mockito.when; @SuppressWarnings("unchecked") -public class JvmAttributeGaugeSetTest { +class JvmAttributeGaugeSetTest { private final RuntimeMXBean runtime = mock(RuntimeMXBean.class); private final JvmAttributeGaugeSet gauges = new JvmAttributeGaugeSet(runtime); - @Before - public void setUp() { + @BeforeEach + void setUp() { when(runtime.getName()).thenReturn("9928@example.com"); when(runtime.getVmVendor()).thenReturn("Oracle Corporation"); @@ -28,7 +28,7 @@ public void setUp() { } @Test - public void hasASetOfGauges() { + void hasASetOfGauges() { assertThat(gauges.getMetrics().keySet()) .containsOnly(MetricName.build("vendor"), MetricName.build("name"), @@ -36,7 +36,7 @@ public void hasASetOfGauges() { } @Test - public void hasAGaugeForTheJVMName() { + void hasAGaugeForTheJVMName() { final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("name")); assertThat(gauge.getValue()) @@ -44,7 +44,7 @@ public void hasAGaugeForTheJVMName() { } @Test - public void hasAGaugeForTheJVMVendor() { + void hasAGaugeForTheJVMVendor() { final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("vendor")); assertThat(gauge.getValue()) @@ -52,7 +52,7 @@ public void hasAGaugeForTheJVMVendor() { } @Test - public void hasAGaugeForTheJVMUptime() { + void hasAGaugeForTheJVMUptime() { final Gauge gauge = (Gauge) gauges.getMetrics().get(MetricName.build("uptime")); assertThat(gauge.getValue()) @@ -60,7 +60,7 @@ public void hasAGaugeForTheJVMUptime() { } @Test - public void autoDiscoversTheRuntimeBean() { + void autoDiscoversTheRuntimeBean() { final Gauge gauge = (Gauge) new JvmAttributeGaugeSet().getMetrics().get(MetricName.build("uptime")); assertThat(gauge.getValue()).isPositive(); diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java index f1f6c6a920..1fb6d4273d 100644 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/MemoryUsageGaugeSetTest.java @@ -2,8 +2,8 @@ import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricName; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryPoolMXBean; @@ -15,7 +15,7 @@ import static org.mockito.Mockito.when; @SuppressWarnings("rawtypes") -public class MemoryUsageGaugeSetTest { +class MemoryUsageGaugeSetTest { private final MemoryUsage heap = mock(MemoryUsage.class); private final MemoryUsage nonHeap = mock(MemoryUsage.class); private final MemoryUsage pool = mock(MemoryUsage.class); @@ -60,8 +60,8 @@ public class MemoryUsageGaugeSetTest { private static final MetricName NON_HEAP_INIT = NON_HEAP.resolve("init"); private static final MetricName NON_HEAP_COMMITTED = NON_HEAP.resolve("committed"); - @Before - public void setUp() { + @BeforeEach + void setUp() { when(heap.getCommitted()).thenReturn(10L); when(heap.getInit()).thenReturn(20L); when(heap.getUsed()).thenReturn(30L); @@ -99,7 +99,7 @@ public void setUp() { } @Test - public void hasASetOfGauges() { + void hasASetOfGauges() { assertThat(gauges.getMetrics().keySet()) .containsOnly( TOTAL_MAX, @@ -131,7 +131,7 @@ public void hasASetOfGauges() { } @Test - public void hasAGaugeForTotalCommitted() { + void hasAGaugeForTotalCommitted() { final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_COMMITTED); assertThat(gauge.getValue()) @@ -139,7 +139,7 @@ public void hasAGaugeForTotalCommitted() { } @Test - public void hasAGaugeForTotalInit() { + void hasAGaugeForTotalInit() { final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_INIT); assertThat(gauge.getValue()) @@ -147,7 +147,7 @@ public void hasAGaugeForTotalInit() { } @Test - public void hasAGaugeForTotalUsed() { + void hasAGaugeForTotalUsed() { final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_USED); assertThat(gauge.getValue()) @@ -155,7 +155,7 @@ public void hasAGaugeForTotalUsed() { } @Test - public void hasAGaugeForTotalMax() { + void hasAGaugeForTotalMax() { final Gauge gauge = (Gauge) gauges.getMetrics().get(TOTAL_MAX); assertThat(gauge.getValue()) @@ -163,7 +163,7 @@ public void hasAGaugeForTotalMax() { } @Test - public void hasAGaugeForHeapCommitted() { + void hasAGaugeForHeapCommitted() { final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_COMMITTED); assertThat(gauge.getValue()) @@ -171,7 +171,7 @@ public void hasAGaugeForHeapCommitted() { } @Test - public void hasAGaugeForHeapInit() { + void hasAGaugeForHeapInit() { final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_INIT); assertThat(gauge.getValue()) @@ -179,7 +179,7 @@ public void hasAGaugeForHeapInit() { } @Test - public void hasAGaugeForHeapUsed() { + void hasAGaugeForHeapUsed() { final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_USED); assertThat(gauge.getValue()) @@ -187,7 +187,7 @@ public void hasAGaugeForHeapUsed() { } @Test - public void hasAGaugeForHeapMax() { + void hasAGaugeForHeapMax() { final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_MAX); assertThat(gauge.getValue()) @@ -195,7 +195,7 @@ public void hasAGaugeForHeapMax() { } @Test - public void hasAGaugeForHeapUsage() { + void hasAGaugeForHeapUsage() { final Gauge gauge = (Gauge) gauges.getMetrics().get(HEAP_USAGE); assertThat(gauge.getValue()) @@ -203,7 +203,7 @@ public void hasAGaugeForHeapUsage() { } @Test - public void hasAGaugeForNonHeapCommitted() { + void hasAGaugeForNonHeapCommitted() { final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_COMMITTED); assertThat(gauge.getValue()) @@ -211,7 +211,7 @@ public void hasAGaugeForNonHeapCommitted() { } @Test - public void hasAGaugeForNonHeapInit() { + void hasAGaugeForNonHeapInit() { final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_INIT); assertThat(gauge.getValue()) @@ -219,7 +219,7 @@ public void hasAGaugeForNonHeapInit() { } @Test - public void hasAGaugeForNonHeapUsed() { + void hasAGaugeForNonHeapUsed() { final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USED); assertThat(gauge.getValue()) @@ -227,7 +227,7 @@ public void hasAGaugeForNonHeapUsed() { } @Test - public void hasAGaugeForNonHeapMax() { + void hasAGaugeForNonHeapMax() { final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_MAX); assertThat(gauge.getValue()) @@ -235,7 +235,7 @@ public void hasAGaugeForNonHeapMax() { } @Test - public void hasAGaugeForNonHeapUsage() { + void hasAGaugeForNonHeapUsage() { final Gauge gauge = (Gauge) gauges.getMetrics().get(NON_HEAP_USAGE); assertThat(gauge.getValue()) @@ -243,7 +243,7 @@ public void hasAGaugeForNonHeapUsage() { } @Test - public void hasAGaugeForMemoryPoolUsage() { + void hasAGaugeForMemoryPoolUsage() { final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_BIG_POOL_USAGE); assertThat(gauge.getValue()) @@ -251,7 +251,7 @@ public void hasAGaugeForMemoryPoolUsage() { } @Test - public void hasAGaugeForWeirdMemoryPoolInit() { + void hasAGaugeForWeirdMemoryPoolInit() { final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_INIT); assertThat(gauge.getValue()) @@ -259,7 +259,7 @@ public void hasAGaugeForWeirdMemoryPoolInit() { } @Test - public void hasAGaugeForWeirdMemoryPoolCommitted() { + void hasAGaugeForWeirdMemoryPoolCommitted() { final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_COMMITTED); assertThat(gauge.getValue()) @@ -267,7 +267,7 @@ public void hasAGaugeForWeirdMemoryPoolCommitted() { } @Test - public void hasAGaugeForWeirdMemoryPoolUsed() { + void hasAGaugeForWeirdMemoryPoolUsed() { final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USED); assertThat(gauge.getValue()) @@ -275,7 +275,7 @@ public void hasAGaugeForWeirdMemoryPoolUsed() { } @Test - public void hasAGaugeForWeirdMemoryPoolUsage() { + void hasAGaugeForWeirdMemoryPoolUsage() { final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USAGE); assertThat(gauge.getValue()) @@ -283,7 +283,7 @@ public void hasAGaugeForWeirdMemoryPoolUsage() { } @Test - public void hasAGaugeForWeirdMemoryPoolMax() { + void hasAGaugeForWeirdMemoryPoolMax() { final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_MAX); assertThat(gauge.getValue()) @@ -291,7 +291,7 @@ public void hasAGaugeForWeirdMemoryPoolMax() { } @Test - public void hasAGaugeForWeirdCollectionPoolUsed() { + void hasAGaugeForWeirdCollectionPoolUsed() { final Gauge gauge = (Gauge) gauges.getMetrics().get(POOLS_WEIRD_POOL_USED_AFTER_GC); assertThat(gauge.getValue()) @@ -299,7 +299,7 @@ public void hasAGaugeForWeirdCollectionPoolUsed() { } @Test - public void autoDetectsMemoryUsageBeanAndMemoryPools() { + void autoDetectsMemoryUsageBeanAndMemoryPools() { assertThat(new MemoryUsageGaugeSet().getMetrics().keySet()) .isNotEmpty(); } diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java index 6e706ef556..4751ba141f 100644 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDeadlockDetectorTest.java @@ -1,6 +1,6 @@ package io.dropwizard.metrics5.jvm; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; @@ -12,27 +12,27 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ThreadDeadlockDetectorTest { +class ThreadDeadlockDetectorTest { private final ThreadMXBean threads = mock(ThreadMXBean.class); private final ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threads); @Test - public void returnsAnEmptySetIfNoThreadsAreDeadlocked() { + void returnsAnEmptySetIfNoThreadsAreDeadlocked() { when(threads.findDeadlockedThreads()).thenReturn(null); assertThat(detector.getDeadlockedThreads()) - .isEmpty(); + .isEmpty(); } @Test - public void returnsASetOfThreadsIfAnyAreDeadlocked() { + void returnsASetOfThreadsIfAnyAreDeadlocked() { final ThreadInfo thread1 = mock(ThreadInfo.class); when(thread1.getThreadName()).thenReturn("thread1"); when(thread1.getLockName()).thenReturn("lock2"); when(thread1.getLockOwnerName()).thenReturn("thread2"); when(thread1.getStackTrace()).thenReturn(new StackTraceElement[]{ - new StackTraceElement("Blah", "bloo", "Blah.java", 150), - new StackTraceElement("Blah", "blee", "Blah.java", 100) + new StackTraceElement("Blah", "bloo", "Blah.java", 150), + new StackTraceElement("Blah", "blee", "Blah.java", 100) }); final ThreadInfo thread2 = mock(ThreadInfo.class); @@ -40,29 +40,29 @@ public void returnsASetOfThreadsIfAnyAreDeadlocked() { when(thread2.getLockName()).thenReturn("lock1"); when(thread2.getLockOwnerName()).thenReturn("thread1"); when(thread2.getStackTrace()).thenReturn(new StackTraceElement[]{ - new StackTraceElement("Blah", "blee", "Blah.java", 100), - new StackTraceElement("Blah", "bloo", "Blah.java", 150) + new StackTraceElement("Blah", "blee", "Blah.java", 100), + new StackTraceElement("Blah", "bloo", "Blah.java", 150) }); final long[] ids = {1, 2}; when(threads.findDeadlockedThreads()).thenReturn(ids); when(threads.getThreadInfo(eq(ids), anyInt())) - .thenReturn(new ThreadInfo[]{thread1, thread2}); + .thenReturn(new ThreadInfo[]{thread1, thread2}); assertThat(detector.getDeadlockedThreads()) - .containsOnly(String.format(Locale.US, - "thread1 locked on lock2 (owned by thread2):%n" + - "\t at Blah.bloo(Blah.java:150)%n" + - "\t at Blah.blee(Blah.java:100)%n"), - String.format(Locale.US, - "thread2 locked on lock1 (owned by thread1):%n" + - "\t at Blah.blee(Blah.java:100)%n" + - "\t at Blah.bloo(Blah.java:150)%n")); + .containsOnly(String.format(Locale.US, + "thread1 locked on lock2 (owned by thread2):%n" + + "\t at Blah.bloo(Blah.java:150)%n" + + "\t at Blah.blee(Blah.java:100)%n"), + String.format(Locale.US, + "thread2 locked on lock1 (owned by thread1):%n" + + "\t at Blah.blee(Blah.java:100)%n" + + "\t at Blah.bloo(Blah.java:150)%n")); } @Test - public void autoDiscoversTheThreadMXBean() { + void autoDiscoversTheThreadMXBean() { assertThat(new ThreadDeadlockDetector().getDeadlockedThreads()) - .isNotNull(); + .isNotNull(); } } diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java index e44a7c2302..e356ab2c37 100755 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadDumpTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5.jvm; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.lang.management.LockInfo; @@ -15,14 +15,14 @@ // TODO: 3/12/13 -- improve test coverage for ThreadDump -public class ThreadDumpTest { +class ThreadDumpTest { private final ThreadMXBean threadMXBean = mock(ThreadMXBean.class); private final ThreadDump threadDump = new ThreadDump(threadMXBean); private final ThreadInfo runnable = mock(ThreadInfo.class); - @Before - public void setUp() { + @BeforeEach + void setUp() { final StackTraceElement rLine1 = new StackTraceElement("Blah", "blee", "Blah.java", 100); when(runnable.getThreadName()).thenReturn("runnable"); @@ -33,19 +33,19 @@ public void setUp() { when(runnable.getLockedSynchronizers()).thenReturn(new LockInfo[]{}); when(threadMXBean.dumpAllThreads(true, true)).thenReturn(new ThreadInfo[]{ - runnable + runnable }); } @Test - public void dumpsAllThreads() { + void dumpsAllThreads() { final ByteArrayOutputStream output = new ByteArrayOutputStream(); threadDump.dump(output); assertThat(output.toString()) - .isEqualTo(String.format("\"runnable\" id=100 state=RUNNABLE%n" + - " at Blah.blee(Blah.java:100)%n" + - "%n" + - "%n")); + .isEqualTo(String.format("\"runnable\" id=100 state=RUNNABLE%n" + + " at Blah.blee(Blah.java:100)%n" + + "%n" + + "%n")); } } diff --git a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java index c395046429..cbfb944abf 100644 --- a/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java +++ b/metrics-jvm/src/test/java/io/dropwizard/metrics5/jvm/ThreadStatesGaugeSetTest.java @@ -3,8 +3,8 @@ import io.dropwizard.metrics5.Gauge; import io.dropwizard.metrics5.MetricName; import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; @@ -15,7 +15,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class ThreadStatesGaugeSetTest { +class ThreadStatesGaugeSetTest { private final ThreadMXBean threads = mock(ThreadMXBean.class); private final ThreadDeadlockDetector detector = mock(ThreadDeadlockDetector.class); private final ThreadStatesGaugeSet gauges = new ThreadStatesGaugeSet(threads, detector); @@ -41,8 +41,8 @@ public class ThreadStatesGaugeSetTest { private static final MetricName RUNNABLE_COUNT = MetricName.build("runnable.count"); private static final MetricName DEADLOCK_COUNT = MetricName.build("deadlock.count"); - @Before - public void setUp() { + @BeforeEach + void setUp() { deadlocks.add("yay"); when(newThread.getThreadState()).thenReturn(Thread.State.NEW); @@ -54,8 +54,8 @@ public void setUp() { when(threads.getAllThreadIds()).thenReturn(ids); when(threads.getThreadInfo(ids, 0)).thenReturn(new ThreadInfo[]{ - newThread, runnableThread, blockedThread, - waitingThread, timedWaitingThread, terminatedThread + newThread, runnableThread, blockedThread, + waitingThread, timedWaitingThread, terminatedThread }); when(threads.getThreadCount()).thenReturn(12); @@ -67,7 +67,7 @@ public void setUp() { } @Test - public void hasASetOfGauges() { + void hasASetOfGauges() { assertThat(gauges.getMetrics().keySet()) .containsOnly(TERMINATED_COUNT, NEW_COUNT, @@ -84,68 +84,68 @@ public void hasASetOfGauges() { } @Test - public void hasAGaugeForEachThreadState() { + void hasAGaugeForEachThreadState() { Assertions.assertThat(((Gauge) gauges.getMetrics().get(NEW_COUNT)).getValue()) - .isEqualTo(1); + .isEqualTo(1); assertThat(((Gauge) gauges.getMetrics().get(RUNNABLE_COUNT)).getValue()) - .isEqualTo(1); + .isEqualTo(1); assertThat(((Gauge) gauges.getMetrics().get(BLOCKED_COUNT)).getValue()) - .isEqualTo(1); + .isEqualTo(1); assertThat(((Gauge) gauges.getMetrics().get(WAITING_COUNT)).getValue()) - .isEqualTo(1); + .isEqualTo(1); assertThat(((Gauge) gauges.getMetrics().get(TIMED_WAITING_COUNT)).getValue()) - .isEqualTo(1); + .isEqualTo(1); assertThat(((Gauge) gauges.getMetrics().get(TERMINATED_COUNT)).getValue()) - .isEqualTo(1); + .isEqualTo(1); } @Test - public void hasAGaugeForTheNumberOfThreads() { + void hasAGaugeForTheNumberOfThreads() { assertThat(((Gauge) gauges.getMetrics().get(COUNT)).getValue()) - .isEqualTo(12); + .isEqualTo(12); } @Test - public void hasAGaugeForTheNumberOfDaemonThreads() { + void hasAGaugeForTheNumberOfDaemonThreads() { assertThat(((Gauge) gauges.getMetrics().get(DAEMON_COUNT)).getValue()) - .isEqualTo(10); + .isEqualTo(10); } @Test - public void hasAGaugeForAnyDeadlocks() { + void hasAGaugeForAnyDeadlocks() { assertThat(((Gauge) gauges.getMetrics().get(DEADLOCKS)).getValue()) - .isEqualTo(deadlocks); + .isEqualTo(deadlocks); } @Test - public void hasAGaugeForAnyDeadlockCount() { + void hasAGaugeForAnyDeadlockCount() { assertThat(((Gauge) gauges.getMetrics().get(DEADLOCK_COUNT)).getValue()) - .isEqualTo(1); + .isEqualTo(1); } @Test - public void hasAGaugeForPeakThreadCount() { + void hasAGaugeForPeakThreadCount() { assertThat(((Gauge) gauges.getMetrics().get(MetricName.build("peak.count"))).getValue()) - .isEqualTo(30); + .isEqualTo(30); } @Test - public void hasAGaugeForTotalStartedThreadsCount() { + void hasAGaugeForTotalStartedThreadsCount() { assertThat(((Gauge) gauges.getMetrics().get(MetricName.build("total_started.count"))).getValue()) - .isEqualTo(42L); + .isEqualTo(42L); } @Test - public void autoDiscoversTheMXBeans() { + void autoDiscoversTheMXBeans() { final ThreadStatesGaugeSet set = new ThreadStatesGaugeSet(); assertThat(((Gauge) set.getMetrics().get(COUNT)).getValue()) - .isNotNull(); + .isNotNull(); assertThat(((Gauge) set.getMetrics().get(DEADLOCKS)).getValue()) - .isNotNull(); + .isNotNull(); } } diff --git a/metrics-legacy-adapter-healthchecks/pom.xml b/metrics-legacy-adapter-healthchecks/pom.xml index 513af3ac49..4c58aec0ee 100644 --- a/metrics-legacy-adapter-healthchecks/pom.xml +++ b/metrics-legacy-adapter-healthchecks/pom.xml @@ -19,12 +19,6 @@ metrics-healthchecks ${project.version} - - junit - junit - ${junit.version} - test - org.assertj assertj-core diff --git a/metrics-legacy-adapter/pom.xml b/metrics-legacy-adapter/pom.xml index 32d2666797..f920efe2cb 100644 --- a/metrics-legacy-adapter/pom.xml +++ b/metrics-legacy-adapter/pom.xml @@ -33,18 +33,24 @@ slf4j-api ${slf4j.version} - - junit - junit - ${junit.version} - test - org.hamcrest hamcrest-core ${hamcrest.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.assertj assertj-core diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java index 88284f7c24..7bd805d670 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CachedGaugeTest.java @@ -1,16 +1,16 @@ package com.codahale.metrics; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class CachedGaugeTest { +class CachedGaugeTest { @Test - public void testCreate() { + void testCreate() { CachedGauge cachedGauge = new CachedGauge(100, TimeUnit.MILLISECONDS) { @Override protected String loadValue() { @@ -21,7 +21,7 @@ protected String loadValue() { } @Test - public void testCreateWothClock() { + void testCreateWothClock() { CachedGauge cachedGauge = new CachedGauge(new Clock.UserTimeClock(), 100, TimeUnit.MILLISECONDS) { @Override diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java index 2cb2e41187..1fe6108431 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ClockTest.java @@ -1,26 +1,26 @@ package com.codahale.metrics; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class ClockTest { +class ClockTest { @Test - public void testDefaultClockCanBeUsed() { + void testDefaultClockCanBeUsed() { Clock clock = Clock.defaultClock(); assertThat(clock.getTick()).isGreaterThan(0); } @Test - public void testUserTimeClockCanBeUsed() { + void testUserTimeClockCanBeUsed() { Clock clock = new Clock.UserTimeClock(); assertThat(clock.getTick()).isGreaterThan(0); } @Test - public void testCustomTimeClockCanBeUsed() { + void testCustomTimeClockCanBeUsed() { Clock clock = new Clock() { @Override public long getTick() { diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java index e8ba8db81b..16945b4d40 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ConsoleReporterTest.java @@ -12,24 +12,24 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class ConsoleReporterTest { +class ConsoleReporterTest { private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); private final String dateHeader = System.getProperty("java.version").startsWith("1.8") ? "3/18/13 1:04:36 AM =============================================================" : "3/18/13, 1:04:36 AM ============================================================"; - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { executor.shutdownNow(); } @Test - public void testCreateConsoleReporter() throws Exception { + void testCreateConsoleReporter() throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); MetricRegistry metricRegistry = new MetricRegistry(); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java index 7d49be5367..cc0e4c94eb 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/CounterTest.java @@ -1,38 +1,38 @@ package com.codahale.metrics; import io.dropwizard.metrics5.Counter; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class CounterTest { +class CounterTest { private Counter counter = new Counter(); @Test - public void testIncrementCounter() { + void testIncrementCounter() { counter.inc(); assertThat(counter.getCount()).isEqualTo(1); } @Test - public void testIncrementCounterOnManyPoints() { + void testIncrementCounterOnManyPoints() { counter.inc(5); assertThat(counter.getCount()).isEqualTo(5); } @Test - public void testDecrementCounter() { + void testDecrementCounter() { counter.dec(); assertThat(counter.getCount()).isEqualTo(-1); } @Test - public void testDecrementCounterOnManyPoints() { + void testDecrementCounterOnManyPoints() { counter.dec(5); assertThat(counter.getCount()).isEqualTo(-5); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java index 317d51918f..d585c3b4d9 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/DerivativeGaugeTest.java @@ -1,14 +1,14 @@ package com.codahale.metrics; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class DerivativeGaugeTest { +class DerivativeGaugeTest { @Test - public void testCalculate() { + void testCalculate() { DerivativeGauge derivativeGauge = new DerivativeGauge(() -> "23") { @Override protected Integer transform(String value) { diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java index 51480c455e..6b59d627c2 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ExponentiallyDecayingReservoirTest.java @@ -1,15 +1,15 @@ package com.codahale.metrics; import org.assertj.core.data.Offset; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class ExponentiallyDecayingReservoirTest { +class ExponentiallyDecayingReservoirTest { @Test - public void testCreateReservoir() { + void testCreateReservoir() { ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(); reservoir.update(120); reservoir.update(190); @@ -31,7 +31,7 @@ public void testCreateReservoir() { } @Test - public void testCreateReservoirWithCustomSizeAndAlpha() { + void testCreateReservoirWithCustomSizeAndAlpha() { ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01); reservoir.update(100); assertThat(reservoir.size()).isEqualTo(1); @@ -39,7 +39,7 @@ public void testCreateReservoirWithCustomSizeAndAlpha() { @Test - public void testCreateReservoirWithCustomSizeAlphaAndClock() { + void testCreateReservoirWithCustomSizeAlphaAndClock() { ExponentiallyDecayingReservoir reservoir = new ExponentiallyDecayingReservoir(512, 0.01, new Clock() { @Override diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java index 4b235850cf..ae776d133f 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/FixedNameCsvFileProviderTest.java @@ -1,8 +1,8 @@ package com.codahale.metrics; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.nio.file.Files; @@ -11,23 +11,23 @@ import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class FixedNameCsvFileProviderTest { +class FixedNameCsvFileProviderTest { private Path tempDirectory; private FixedNameCsvFileProvider fixedNameCsvFileProvider = new FixedNameCsvFileProvider(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { tempDirectory = Files.createTempDirectory("csv-test"); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { Files.delete(tempDirectory); } @Test - public void getFile() throws Exception { + void getFile() throws Exception { File file = fixedNameCsvFileProvider.getFile(tempDirectory.toFile(), "timer-test"); assertThat(file.toString()).startsWith(tempDirectory.toString()); assertThat(file.toString()).endsWith("timer-test.csv"); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java index 3c40e43fc7..c8ef88a7cb 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/GaugeTest.java @@ -1,16 +1,16 @@ package com.codahale.metrics; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class GaugeTest { +class GaugeTest { private Gauge gauge = () -> 83; @Test - public void testGetValue() { + void testGetValue() { assertThat(gauge.getValue()).isEqualTo(83); } } diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java index e8a9258af8..c74807bd97 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/HistogramTest.java @@ -1,15 +1,15 @@ package com.codahale.metrics; import org.assertj.core.data.Offset; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class HistogramTest { +class HistogramTest { @Test - public void testCreate() { + void testCreate() { Histogram histogram = new Histogram(new ExponentiallyDecayingReservoir()); histogram.update(120); histogram.update(190); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java index 6324b7b2ed..055b519612 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedExecutorServiceTest.java @@ -1,7 +1,6 @@ package com.codahale.metrics; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -11,11 +10,11 @@ import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class InstrumentedExecutorServiceTest { +class InstrumentedExecutorServiceTest { @Test - public void testCreate() throws Exception { + void testCreate() throws Exception { ExecutorService executorService = Executors.newSingleThreadExecutor(); MetricRegistry registry = new MetricRegistry(); InstrumentedExecutorService instrumentedExecutorService = new InstrumentedExecutorService(executorService, diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java index c594c07876..8fa396ca05 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedScheduledExecutorServiceTest.java @@ -1,7 +1,7 @@ package com.codahale.metrics; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; @@ -11,16 +11,16 @@ import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class InstrumentedScheduledExecutorServiceTest { +class InstrumentedScheduledExecutorServiceTest { private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - @After - public void tearDown() { + @AfterEach + void tearDown() { executorService.shutdown(); } @Test - public void testCreate() throws Exception { + void testCreate() throws Exception { MetricRegistry registry = new MetricRegistry(); InstrumentedScheduledExecutorService instrumentedExecutorService = new InstrumentedScheduledExecutorService( executorService, registry, "test-scheduled-instrumented"); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java index 19c6fe0380..57e3ba5b6d 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/InstrumentedThreadFactoryTest.java @@ -1,6 +1,6 @@ package com.codahale.metrics; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -8,11 +8,11 @@ import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class InstrumentedThreadFactoryTest { +class InstrumentedThreadFactoryTest { @Test @SuppressWarnings("DoNotCall") - public void testFactory() throws Exception { + void testFactory() throws Exception { MetricRegistry registry = new MetricRegistry(); InstrumentedThreadFactory threadFactory = new InstrumentedThreadFactory(Thread::new, registry, "test-instrumented-thread-factory"); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java index a115cf56e2..652c1f4d54 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MeterTest.java @@ -1,22 +1,22 @@ package com.codahale.metrics; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class MeterTest { +class MeterTest { @Test - public void testCreateMeteer() { + void testCreateMeteer() { Meter meter = new Meter(); assertThat(meter.getCount()).isEqualTo(0); } @Test - public void testCreateMeterWithCustomClock() { + void testCreateMeterWithCustomClock() { Meter meter = new Meter(new Clock() { @Override public long getTick() { @@ -27,7 +27,7 @@ public long getTick() { } @Test - public void testMark() { + void testMark() { Meter meter = new Meter(new Clock() { private long start = System.nanoTime(); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java index 4ef53074ba..518b6259d2 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/MetricRegistryTest.java @@ -1,6 +1,6 @@ package com.codahale.metrics; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; @@ -12,19 +12,19 @@ import static org.assertj.core.data.Offset.offset; @SuppressWarnings("deprecation") -public class MetricRegistryTest { +class MetricRegistryTest { private MetricRegistry metricRegistry = new MetricRegistry(); @Test - public void testRegisterMetric() { + void testRegisterMetric() { Counter counter = metricRegistry.register("test-counter", new Counter()); counter.inc(42); assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); } @Test - public void testRegisterAll() { + void testRegisterAll() { metricRegistry.registerAll(() -> { Map map = new HashMap<>(); map.put("test-counter", new Counter()); @@ -40,26 +40,26 @@ public void testRegisterAll() { } @Test - public void testRegisterGauge() { + void testRegisterGauge() { metricRegistry.registerGauge("test-gauge", () -> 42); assertThat(metricRegistry.getGauges().get("test-gauge").getValue()).isEqualTo(42); } @Test - public void testCreateCustomGauge() { + void testCreateCustomGauge() { Gauge gauge = metricRegistry.gauge("test-gauge-supplier", () -> () -> 42); assertThat(gauge.getValue()).isEqualTo(42); } @Test - public void testCreateCounter() { + void testCreateCounter() { Counter counter = metricRegistry.counter("test-counter"); counter.inc(42); assertThat(metricRegistry.counter("test-counter").getCount()).isEqualTo(42); } @Test - public void testCreateCustomCounter() { + void testCreateCustomCounter() { Counter counter = metricRegistry.counter("test-custom-counter", () -> { Counter c = new Counter(); c.inc(8); @@ -70,7 +70,7 @@ public void testCreateCustomCounter() { } @Test - public void testCreateHistogram() { + void testCreateHistogram() { Histogram histogram = metricRegistry.histogram("test-histogram"); histogram.update(100); histogram.update(200); @@ -80,7 +80,7 @@ public void testCreateHistogram() { } @Test - public void testCreateCustomHistogram() { + void testCreateCustomHistogram() { Histogram histogram = metricRegistry.histogram("test-custom-histogram", () -> new Histogram(new SlidingWindowReservoir(2))); histogram.update(100); @@ -91,7 +91,7 @@ public void testCreateCustomHistogram() { } @Test - public void testCreateMeter() { + void testCreateMeter() { Meter meter = metricRegistry.meter("test-meter"); meter.mark(); meter.mark(2); @@ -100,7 +100,7 @@ public void testCreateMeter() { } @Test - public void testCreateCustomMeter() { + void testCreateCustomMeter() { Meter meter = metricRegistry.meter("test-custom-meter", () -> { Meter m = new Meter(); m.mark(16); @@ -112,7 +112,7 @@ public void testCreateCustomMeter() { } @Test - public void testCreateTimer() { + void testCreateTimer() { Timer timer = metricRegistry.timer("test-timer"); timer.update(100, TimeUnit.MILLISECONDS); timer.update(200, TimeUnit.MILLISECONDS); @@ -122,7 +122,7 @@ public void testCreateTimer() { } @Test - public void testCreateCustomTimer() { + void testCreateCustomTimer() { Timer timer = metricRegistry.timer("custom-test-timer", () -> { Timer t = new Timer(new UniformReservoir()); t.update(300, TimeUnit.MILLISECONDS); @@ -135,7 +135,7 @@ public void testCreateCustomTimer() { } @Test - public void testRemoveMetric() { + void testRemoveMetric() { metricRegistry.timer("test-timer"); metricRegistry.counter("test-counter"); metricRegistry.meter("test-meter"); @@ -146,7 +146,7 @@ public void testRemoveMetric() { } @Test - public void testRemoveMatching() { + void testRemoveMatching() { metricRegistry.counter("test-counter"); metricRegistry.timer("test-timer"); metricRegistry.timer("test-custom-timer"); @@ -157,7 +157,7 @@ public void testRemoveMatching() { } @Test - public void testAddListenerForGauge() throws Exception { + void testAddListenerForGauge() throws Exception { CountDownLatch gaugeAddedLatch = new CountDownLatch(1); CountDownLatch gaugeRemovedLatch = new CountDownLatch(1); metricRegistry.addListener(new MetricRegistryListener.Base() { @@ -185,7 +185,7 @@ public void onGaugeRemoved(String name) { } @Test - public void testAddListenerForCounter() throws Exception { + void testAddListenerForCounter() throws Exception { CountDownLatch counterAddedLatch = new CountDownLatch(1); CountDownLatch counterRemovedLatch = new CountDownLatch(1); metricRegistry.addListener(new MetricRegistryListener.Base() { @@ -212,7 +212,7 @@ public void onCounterRemoved(String name) { } @Test - public void testAddListenerForHistogram() throws Exception { + void testAddListenerForHistogram() throws Exception { CountDownLatch histogramAddedLatch = new CountDownLatch(1); CountDownLatch histogramRemovedLatch = new CountDownLatch(1); metricRegistry.addListener(new MetricRegistryListener.Base() { @@ -241,7 +241,7 @@ public void onHistogramRemoved(String name) { } @Test - public void testAddListenerForMeter() throws Exception { + void testAddListenerForMeter() throws Exception { CountDownLatch meterAddedLatch = new CountDownLatch(1); CountDownLatch meterRemovedLatch = new CountDownLatch(1); metricRegistry.addListener(new MetricRegistryListener.Base() { @@ -269,7 +269,7 @@ public void onMeterRemoved(String name) { } @Test - public void testAddListenerForTimer() throws Exception { + void testAddListenerForTimer() throws Exception { CountDownLatch timerAddedLatch = new CountDownLatch(1); CountDownLatch timerRemovedLatch = new CountDownLatch(1); metricRegistry.addListener(new MetricRegistryListener.Base() { @@ -297,7 +297,7 @@ public void onTimerRemoved(String name) { } @Test - public void testRemoveListener() throws Exception { + void testRemoveListener() throws Exception { CountDownLatch gaugeAddedLatch = new CountDownLatch(1); MetricRegistryListener listener = new MetricRegistryListener.Base() { @Override @@ -315,7 +315,7 @@ public void onGaugeAdded(String name, Gauge gauge) { } @Test - public void testGetNames() { + void testGetNames() { metricRegistry.counter("test-counter"); metricRegistry.timer("test-timer"); metricRegistry.timer("test-custom-timer"); @@ -326,7 +326,7 @@ public void testGetNames() { } @Test - public void testGetGauges() { + void testGetGauges() { metricRegistry.counter("test-counter"); metricRegistry.timer("test-timer"); metricRegistry.meter("test-meter"); @@ -349,7 +349,7 @@ protected String transform(Integer value) { } @Test - public void testGetGaugesWithFilter() { + void testGetGaugesWithFilter() { metricRegistry.counter("test-counter"); metricRegistry.timer("test-timer"); metricRegistry.meter("test-meter"); @@ -372,7 +372,7 @@ protected String transform(Integer value) { } @Test - public void testGetHistograms() { + void testGetHistograms() { metricRegistry.counter("test-counter"); metricRegistry.timer("test-timer"); metricRegistry.meter("test-meter"); @@ -385,7 +385,7 @@ public void testGetHistograms() { } @Test - public void testGetHistogramsWithFilter() { + void testGetHistogramsWithFilter() { metricRegistry.counter("sw-counter"); metricRegistry.timer("sw-timer"); metricRegistry.meter("sw-meter"); @@ -398,7 +398,7 @@ public void testGetHistogramsWithFilter() { } @Test - public void testGetCounters() { + void testGetCounters() { metricRegistry.histogram("test-histogram"); metricRegistry.timer("test-timer"); metricRegistry.meter("test-meter"); @@ -411,7 +411,7 @@ public void testGetCounters() { } @Test - public void testGetCountersWithFilter() { + void testGetCountersWithFilter() { metricRegistry.histogram("test-histogram"); metricRegistry.timer("test-timer"); metricRegistry.meter("test-meter"); @@ -424,7 +424,7 @@ public void testGetCountersWithFilter() { } @Test - public void testGetMeters() { + void testGetMeters() { metricRegistry.register("test-gauge", (Gauge) () -> 42); metricRegistry.histogram("test-histogram"); metricRegistry.timer("test-timer"); @@ -437,7 +437,7 @@ public void testGetMeters() { } @Test - public void testGetMetersWithFilter() { + void testGetMetersWithFilter() { metricRegistry.register("sw-gauge", (Gauge) () -> 42); metricRegistry.histogram("sw-histogram"); metricRegistry.timer("sw-timer"); @@ -450,7 +450,7 @@ public void testGetMetersWithFilter() { } @Test - public void testGetTimers() { + void testGetTimers() { metricRegistry.histogram("test-histogram"); metricRegistry.meter("test-meter"); metricRegistry.counter("test-counter"); @@ -462,7 +462,7 @@ public void testGetTimers() { } @Test - public void testGetTimersWithFilter() { + void testGetTimersWithFilter() { metricRegistry.histogram("test-histogram-2"); metricRegistry.meter("test-meter-2"); metricRegistry.counter("test-counter-2"); @@ -474,7 +474,7 @@ public void testGetTimersWithFilter() { } @Test - public void testGetMetrics() { + void testGetMetrics() { metricRegistry.register("test-text-gauge-2", new CachedGauge(1, TimeUnit.MINUTES) { @Override protected String loadValue() { diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java index 97edf06734..a5f7c5ace2 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/RatioGaugeTest.java @@ -1,12 +1,12 @@ package com.codahale.metrics; import org.assertj.core.data.Offset; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class RatioGaugeTest { +class RatioGaugeTest { private RatioGauge ratioGauge = new RatioGauge() { @Override @@ -16,13 +16,13 @@ protected Ratio getRatio() { }; @Test - public void testViewRatin() { + void testViewRatin() { assertThat(ratioGauge.getRatio().toString()).isEqualTo("1.0:3.0"); } @Test - public void testCalculateRatio() { + void testCalculateRatio() { assertThat(ratioGauge.getValue()).isCloseTo(0.33, Offset.offset(0.01)); } } diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java index 09ca24032e..4792810456 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/ScheduledReporterTest.java @@ -1,8 +1,8 @@ package com.codahale.metrics; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.SortedMap; import java.util.concurrent.CountDownLatch; @@ -11,13 +11,13 @@ import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class ScheduledReporterTest { +class ScheduledReporterTest { private MetricRegistry metricRegistry = new MetricRegistry(); private ScheduledReporter scheduledReporter; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { metricRegistry.register("sw-gauge", (Gauge) () -> 28); metricRegistry.counter("sw-counter"); metricRegistry.timer("sw-timer"); @@ -25,8 +25,8 @@ public void setUp() throws Exception { metricRegistry.histogram("sw-histogram"); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { scheduledReporter.stop(); } @@ -36,8 +36,8 @@ private ScheduledReporter createScheduledReporter(CountDownLatch latch) { @Override @SuppressWarnings("rawtypes") public void report(SortedMap gauges, SortedMap counters, - SortedMap histograms, SortedMap meters, - SortedMap timers) { + SortedMap histograms, SortedMap meters, + SortedMap timers) { assertThat(gauges).containsOnlyKeys("sw-gauge"); assertThat(counters).containsOnlyKeys("sw-counter"); assertThat(histograms).containsOnlyKeys("sw-histogram"); @@ -49,7 +49,7 @@ public void report(SortedMap gauges, SortedMap c } @Test - public void testReport() throws Exception { + void testReport() throws Exception { CountDownLatch latch = new CountDownLatch(1); scheduledReporter = createScheduledReporter(latch); scheduledReporter.report(); @@ -59,7 +59,7 @@ public void testReport() throws Exception { } @Test - public void testStart() throws Exception { + void testStart() throws Exception { CountDownLatch latch = new CountDownLatch(2); scheduledReporter = createScheduledReporter(latch); scheduledReporter.start(10, TimeUnit.MILLISECONDS); @@ -69,7 +69,7 @@ public void testStart() throws Exception { } @Test - public void testStartWithoutDelay() throws Exception { + void testStartWithoutDelay() throws Exception { CountDownLatch latch = new CountDownLatch(2); scheduledReporter = createScheduledReporter(latch); scheduledReporter.start(0, 10, TimeUnit.MILLISECONDS); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java index c6dd76519d..052f6dac8c 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SharedMetricRegistriesTest.java @@ -1,21 +1,21 @@ package com.codahale.metrics; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; @SuppressWarnings("deprecation") -public class SharedMetricRegistriesTest { +class SharedMetricRegistriesTest { - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { SharedMetricRegistries.clear(); } @Test - public void testGetOrCreateMetricRegistry() { + void testGetOrCreateMetricRegistry() { SharedMetricRegistries.getOrCreate("get-or-create").counter("test-counter"); assertThat(SharedMetricRegistries.getOrCreate("get-or-create").getCounters()) @@ -23,7 +23,7 @@ public void testGetOrCreateMetricRegistry() { } @Test - public void testAddMetricRegistry() { + void testAddMetricRegistry() { MetricRegistry metricRegistry = new MetricRegistry(); metricRegistry.histogram("test-histogram"); SharedMetricRegistries.add("add", metricRegistry); @@ -33,7 +33,7 @@ public void testAddMetricRegistry() { } @Test - public void testNames() { + void testNames() { SharedMetricRegistries.add("registry-1", new MetricRegistry()); SharedMetricRegistries.add("registry-2", new MetricRegistry()); SharedMetricRegistries.add("registry-3", new MetricRegistry()); @@ -42,12 +42,12 @@ public void testNames() { } @Test - public void testTryGetDefaultRegistry() { + void testTryGetDefaultRegistry() { assertThat(SharedMetricRegistries.tryGetDefault()).isNull(); } @Test - public void testGetDefaultRegistry() { + void testGetDefaultRegistry() { assertThatIllegalStateException().isThrownBy(SharedMetricRegistries::getDefault); } } diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java index 9705ddf097..d04a55a9e7 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/Slf4jReporterTest.java @@ -1,8 +1,8 @@ package com.codahale.metrics; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.Marker; @@ -15,24 +15,24 @@ import static org.mockito.Mockito.when; @SuppressWarnings("deprecation") -public class Slf4jReporterTest { +class Slf4jReporterTest { private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); private Logger logger = mock(Logger.class); private Marker marker = mock(Marker.class); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { when(logger.isInfoEnabled(marker)).thenReturn(true); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { executor.shutdownNow(); } @Test - public void testReport() throws Exception { + void testReport() throws Exception { MetricRegistry metricRegistry = new MetricRegistry(); metricRegistry.counter("test-counter").inc(100); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java index 9ff6e1754b..8977da4aed 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowArrayReservoirTest.java @@ -1,17 +1,17 @@ package com.codahale.metrics; import org.assertj.core.data.Offset; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class SlidingTimeWindowArrayReservoirTest { +class SlidingTimeWindowArrayReservoirTest { @Test - public void testCreateWithWindow() { + void testCreateWithWindow() { SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS); reservoir.update(100); reservoir.update(200); @@ -22,7 +22,7 @@ public void testCreateWithWindow() { } @Test - public void testCreateWithWindowAndClock() { + void testCreateWithWindowAndClock() { SlidingTimeWindowArrayReservoir reservoir = new SlidingTimeWindowArrayReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); reservoir.update(400); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java index 14e550dd90..22bb076a1a 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingTimeWindowReservoirTest.java @@ -1,17 +1,17 @@ package com.codahale.metrics; import org.assertj.core.data.Offset; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class SlidingTimeWindowReservoirTest { +class SlidingTimeWindowReservoirTest { @Test - public void testCreateWithWindow() { + void testCreateWithWindow() { SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS); reservoir.update(100); reservoir.update(200); @@ -22,7 +22,7 @@ public void testCreateWithWindow() { } @Test - public void testCreateWithWindowAndClock() { + void testCreateWithWindowAndClock() { SlidingTimeWindowReservoir reservoir = new SlidingTimeWindowReservoir(1, TimeUnit.HOURS, new Clock.UserTimeClock()); reservoir.update(400); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java index e7d100867c..80c7f787bd 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SlidingWindowReservoirTest.java @@ -1,15 +1,15 @@ package com.codahale.metrics; import org.assertj.core.data.Offset; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class SlidingWindowReservoirTest { +class SlidingWindowReservoirTest { @Test - public void testCreateWithBigWindow() { + void testCreateWithBigWindow() { SlidingWindowReservoir reservoir = new SlidingWindowReservoir(100); reservoir.update(100); reservoir.update(220); @@ -20,7 +20,7 @@ public void testCreateWithBigWindow() { } @Test - public void testCreateWithLowWindow() { + void testCreateWithLowWindow() { SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3); reservoir.update(500); reservoir.update(220); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java index 062780c446..c24332a0ba 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/SnapshotTest.java @@ -2,17 +2,17 @@ import io.dropwizard.metrics5.UniformSnapshot; import org.assertj.core.data.Offset; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class SnapshotTest { +class SnapshotTest { @Test - public void testCreateSnapshot() throws Exception { + void testCreateSnapshot() throws Exception { Snapshot snapshot = Snapshot.of(new UniformSnapshot(new long[]{5, 1, 2, 3, 4})); assertThat(snapshot.getValues()).isEqualTo(new long[]{1, 2, 3, 4, 5}); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java index 58424c907f..6b6fa6ae04 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/TimerTest.java @@ -1,6 +1,6 @@ package com.codahale.metrics; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.concurrent.TimeUnit; @@ -9,7 +9,7 @@ import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class TimerTest { +class TimerTest { private static class ManualClock extends Clock { @@ -27,7 +27,7 @@ private static void verifyOneEvent(Timer timer) { } @Test - public void testCreate() { + void testCreate() { Timer timer = new Timer(); timer.update(100, TimeUnit.MILLISECONDS); timer.update(200, TimeUnit.MILLISECONDS); @@ -36,7 +36,7 @@ public void testCreate() { } @Test - public void testCreateWithCustomReservoir() { + void testCreateWithCustomReservoir() { Timer timer = new Timer(new SlidingWindowReservoir(100)); timer.update(100, TimeUnit.MILLISECONDS); timer.update(200, TimeUnit.MILLISECONDS); @@ -45,7 +45,7 @@ public void testCreateWithCustomReservoir() { } @Test - public void testCreateWithCustomReservoirAndClock() { + void testCreateWithCustomReservoirAndClock() { Timer timer = new Timer(new SlidingWindowReservoir(100), new Clock.UserTimeClock()); timer.update(100, TimeUnit.MILLISECONDS); timer.update(200, TimeUnit.MILLISECONDS); @@ -54,7 +54,7 @@ public void testCreateWithCustomReservoirAndClock() { } @Test - public void testTimerContext() { + void testTimerContext() { Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); timer.time().stop(); @@ -62,7 +62,7 @@ public void testTimerContext() { } @Test - public void testTimerRunnable() { + void testTimerRunnable() { Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); AtomicInteger counter = new AtomicInteger(); @@ -73,7 +73,7 @@ public void testTimerRunnable() { } @Test - public void testTimerCallable() throws Exception { + void testTimerCallable() throws Exception { Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); String message = timer.time(() -> "SUCCESS"); @@ -83,7 +83,7 @@ public void testTimerCallable() throws Exception { } @Test - public void testTimerSupplier() throws Exception { + void testTimerSupplier() throws Exception { Timer timer = new Timer(new SlidingWindowReservoir(100), new ManualClock()); Integer result = timer.timeSupplier(() -> 42); @@ -93,7 +93,7 @@ public void testTimerSupplier() throws Exception { } @Test - public void testUpdateDuration() { + void testUpdateDuration() { Timer timer = new Timer(); timer.update(Duration.ofMillis(100)); timer.update(Duration.ofMillis(200)); diff --git a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java index 8c3c390db1..7106f53301 100644 --- a/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java +++ b/metrics-legacy-adapter/src/test/java/com/codahale/metrics/UniformReservoirTest.java @@ -1,15 +1,15 @@ package com.codahale.metrics; import org.assertj.core.data.Offset; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("deprecation") -public class UniformReservoirTest { +class UniformReservoirTest { @Test - public void testCreateReservoir() { + void testCreateReservoir() { UniformReservoir reservoir = new UniformReservoir(); reservoir.update(120); reservoir.update(190); @@ -31,7 +31,7 @@ public void testCreateReservoir() { } @Test - public void testCreateReservoirWithCustomSize() { + void testCreateReservoirWithCustomSize() { UniformReservoir reservoir = new UniformReservoir(128); reservoir.update(440); reservoir.update(250); diff --git a/metrics-log4j2/pom.xml b/metrics-log4j2/pom.xml index 46fc4a86e8..a389b4153d 100644 --- a/metrics-log4j2/pom.xml +++ b/metrics-log4j2/pom.xml @@ -65,18 +65,24 @@ log4j-core ${log4j2.version} - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core diff --git a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java index 28b2253aca..03d9a40c0b 100644 --- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java +++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderConfigTest.java @@ -6,9 +6,9 @@ import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.Configurator; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -20,21 +20,21 @@ public class InstrumentedAppenderConfigTest { private ConfigurationSource source; private LoggerContext context; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { source = new ConfigurationSource(this.getClass().getClassLoader().getResourceAsStream("log4j2-testconfig.xml")); context = Configurator.initialize(null, source); } - @After - public void tearDown() { + @AfterEach + void tearDown() { context.stop(); } // The biggest test is that we can initialize the log4j2 config at all. @Test - public void canRecordAll() { + void canRecordAll() { Logger logger = context.getLogger(this.getClass().getName()); long initialAllCount = registry.meter(METRIC_NAME_PREFIX + ".all").getCount(); @@ -44,7 +44,7 @@ public void canRecordAll() { } @Test - public void canRecordError() { + void canRecordError() { Logger logger = context.getLogger(this.getClass().getName()); long initialErrorCount = registry.meter(METRIC_NAME_PREFIX + ".error").getCount(); @@ -54,7 +54,7 @@ public void canRecordError() { } @Test - public void noInvalidRecording() { + void noInvalidRecording() { Logger logger = context.getLogger(this.getClass().getName()); long initialInfoCount = registry.meter(METRIC_NAME_PREFIX + ".info").getCount(); diff --git a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java index 28c9f275b0..85e9b599d9 100644 --- a/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java +++ b/metrics-log4j2/src/test/java/io/dropwizard/metrics5/log4j2/InstrumentedAppenderTest.java @@ -4,9 +4,9 @@ import io.dropwizard.metrics5.SharedMetricRegistries; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.LogEvent; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -20,18 +20,18 @@ public class InstrumentedAppenderTest { private final InstrumentedAppender appender = new InstrumentedAppender(registry); private final LogEvent event = mock(LogEvent.class); - @Before - public void setUp() { + @BeforeEach + void setUp() { appender.start(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { SharedMetricRegistries.clear(); } @Test - public void metersTraceEvents() { + void metersTraceEvents() { when(event.getLevel()).thenReturn(Level.TRACE); appender.append(event); @@ -44,7 +44,7 @@ public void metersTraceEvents() { } @Test - public void metersDebugEvents() { + void metersDebugEvents() { when(event.getLevel()).thenReturn(Level.DEBUG); appender.append(event); @@ -57,7 +57,7 @@ public void metersDebugEvents() { } @Test - public void metersInfoEvents() { + void metersInfoEvents() { when(event.getLevel()).thenReturn(Level.INFO); appender.append(event); @@ -70,7 +70,7 @@ public void metersInfoEvents() { } @Test - public void metersWarnEvents() { + void metersWarnEvents() { when(event.getLevel()).thenReturn(Level.WARN); appender.append(event); @@ -83,7 +83,7 @@ public void metersWarnEvents() { } @Test - public void metersErrorEvents() { + void metersErrorEvents() { when(event.getLevel()).thenReturn(Level.ERROR); appender.append(event); @@ -96,7 +96,7 @@ public void metersErrorEvents() { } @Test - public void metersFatalEvents() { + void metersFatalEvents() { when(event.getLevel()).thenReturn(Level.FATAL); appender.append(event); @@ -109,7 +109,7 @@ public void metersFatalEvents() { } @Test - public void usesSharedRegistries() { + void usesSharedRegistries() { String registryName = "registry"; diff --git a/metrics-logback13/pom.xml b/metrics-logback13/pom.xml index c5e209c319..6465a4f9e3 100644 --- a/metrics-logback13/pom.xml +++ b/metrics-logback13/pom.xml @@ -65,18 +65,24 @@ - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core diff --git a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java index b192358193..355660eb3f 100644 --- a/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java +++ b/metrics-logback13/src/test/java/io/dropwizard/metrics/logback13/InstrumentedAppenderTest.java @@ -4,9 +4,9 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.SharedMetricRegistries; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -20,18 +20,18 @@ public class InstrumentedAppenderTest { private final InstrumentedAppender appender = new InstrumentedAppender(registry); private final ILoggingEvent event = mock(ILoggingEvent.class); - @Before - public void setUp() { + @BeforeEach + void setUp() { appender.start(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { SharedMetricRegistries.clear(); } @Test - public void metersTraceEvents() { + void metersTraceEvents() { when(event.getLevel()).thenReturn(Level.TRACE); appender.doAppend(event); @@ -44,7 +44,7 @@ public void metersTraceEvents() { } @Test - public void metersDebugEvents() { + void metersDebugEvents() { when(event.getLevel()).thenReturn(Level.DEBUG); appender.doAppend(event); @@ -57,7 +57,7 @@ public void metersDebugEvents() { } @Test - public void metersInfoEvents() { + void metersInfoEvents() { when(event.getLevel()).thenReturn(Level.INFO); appender.doAppend(event); @@ -70,7 +70,7 @@ public void metersInfoEvents() { } @Test - public void metersWarnEvents() { + void metersWarnEvents() { when(event.getLevel()).thenReturn(Level.WARN); appender.doAppend(event); @@ -83,7 +83,7 @@ public void metersWarnEvents() { } @Test - public void metersErrorEvents() { + void metersErrorEvents() { when(event.getLevel()).thenReturn(Level.ERROR); appender.doAppend(event); @@ -96,7 +96,7 @@ public void metersErrorEvents() { } @Test - public void usesSharedRegistries() { + void usesSharedRegistries() { String registryName = "registry"; @@ -113,7 +113,7 @@ public void usesSharedRegistries() { } @Test - public void usesDefaultRegistry() { + void usesDefaultRegistry() { SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); final InstrumentedAppender shared = new InstrumentedAppender(); shared.start(); @@ -126,7 +126,7 @@ public void usesDefaultRegistry() { } @Test - public void usesRegistryFromProperty() { + void usesRegistryFromProperty() { SharedMetricRegistries.add("something_else", registry); System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); final InstrumentedAppender shared = new InstrumentedAppender(); diff --git a/metrics-logback14/pom.xml b/metrics-logback14/pom.xml index 0d2941223b..c8a20b62e1 100644 --- a/metrics-logback14/pom.xml +++ b/metrics-logback14/pom.xml @@ -61,18 +61,24 @@ logback-classic ${logback14.version} - - junit - junit - ${junit.version} - test - org.assertj assertj-core ${assertj.version} test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + org.mockito mockito-core diff --git a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java index 00b38c6e6d..9342bcfb99 100644 --- a/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java +++ b/metrics-logback14/src/test/java/io/dropwizard/metrics/logback14/InstrumentedAppenderTest.java @@ -4,9 +4,9 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import io.dropwizard.metrics5.MetricRegistry; import io.dropwizard.metrics5.SharedMetricRegistries; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -20,18 +20,18 @@ public class InstrumentedAppenderTest { private final InstrumentedAppender appender = new InstrumentedAppender(registry); private final ILoggingEvent event = mock(ILoggingEvent.class); - @Before - public void setUp() { + @BeforeEach + void setUp() { appender.start(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { SharedMetricRegistries.clear(); } @Test - public void metersTraceEvents() { + void metersTraceEvents() { when(event.getLevel()).thenReturn(Level.TRACE); appender.doAppend(event); @@ -44,7 +44,7 @@ public void metersTraceEvents() { } @Test - public void metersDebugEvents() { + void metersDebugEvents() { when(event.getLevel()).thenReturn(Level.DEBUG); appender.doAppend(event); @@ -57,7 +57,7 @@ public void metersDebugEvents() { } @Test - public void metersInfoEvents() { + void metersInfoEvents() { when(event.getLevel()).thenReturn(Level.INFO); appender.doAppend(event); @@ -70,7 +70,7 @@ public void metersInfoEvents() { } @Test - public void metersWarnEvents() { + void metersWarnEvents() { when(event.getLevel()).thenReturn(Level.WARN); appender.doAppend(event); @@ -83,7 +83,7 @@ public void metersWarnEvents() { } @Test - public void metersErrorEvents() { + void metersErrorEvents() { when(event.getLevel()).thenReturn(Level.ERROR); appender.doAppend(event); @@ -96,7 +96,7 @@ public void metersErrorEvents() { } @Test - public void usesSharedRegistries() { + void usesSharedRegistries() { String registryName = "registry"; @@ -113,7 +113,7 @@ public void usesSharedRegistries() { } @Test - public void usesDefaultRegistry() { + void usesDefaultRegistry() { SharedMetricRegistries.add(InstrumentedAppender.DEFAULT_REGISTRY, registry); final InstrumentedAppender shared = new InstrumentedAppender(); shared.start(); @@ -126,7 +126,7 @@ public void usesDefaultRegistry() { } @Test - public void usesRegistryFromProperty() { + void usesRegistryFromProperty() { SharedMetricRegistries.add("something_else", registry); System.setProperty(InstrumentedAppender.REGISTRY_PROPERTY_NAME, "something_else"); final InstrumentedAppender shared = new InstrumentedAppender(); diff --git a/metrics-servlet/pom.xml b/metrics-servlet/pom.xml index 1ae7753324..4c8e99dd8f 100644 --- a/metrics-servlet/pom.xml +++ b/metrics-servlet/pom.xml @@ -45,9 +45,15 @@ provided - junit - junit - ${junit.version} + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} test diff --git a/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java b/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java index 1b6c06bca5..36f0909acb 100644 --- a/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java +++ b/metrics-servlet/src/test/java/io/dropwizard/metrics5/servlet/InstrumentedFilterContextListenerTest.java @@ -1,7 +1,7 @@ package io.dropwizard.metrics5.servlet; import io.dropwizard.metrics5.MetricRegistry; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; @@ -10,7 +10,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class InstrumentedFilterContextListenerTest { +class InstrumentedFilterContextListenerTest { private final MetricRegistry registry = mock(MetricRegistry.class); private final InstrumentedFilterContextListener listener = new InstrumentedFilterContextListener() { @Override @@ -20,7 +20,7 @@ protected MetricRegistry getMetricRegistry() { }; @Test - public void injectsTheMetricRegistryIntoTheServletContext() { + void injectsTheMetricRegistryIntoTheServletContext() { final ServletContext context = mock(ServletContext.class); final ServletContextEvent event = mock(ServletContextEvent.class); diff --git a/metrics-servlets/pom.xml b/metrics-servlets/pom.xml index fe5c8ea776..a3ffcfdb90 100644 --- a/metrics-servlets/pom.xml +++ b/metrics-servlets/pom.xml @@ -90,12 +90,6 @@ com.fasterxml.jackson.core jackson-databind - - junit - junit - ${junit.version} - test - org.assertj assertj-core @@ -134,6 +128,18 @@ jetty-util test + + org.junit.jupiter + junit-jupiter-api + ${junit5.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit5.version} + test + io.dropwizard.metrics5 metrics-jetty10 diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java index d412f899e2..d341826c76 100644 --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AbstractServletTest.java @@ -2,15 +2,15 @@ import org.eclipse.jetty.http.HttpTester; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; public abstract class AbstractServletTest { private final ServletTester tester = new ServletTester(); protected final HttpTester.Request request = HttpTester.newRequest(); protected HttpTester.Response response; - @Before + @BeforeEach public void setUpTester() throws Exception { setUp(tester); tester.start(); @@ -18,7 +18,7 @@ public void setUpTester() throws Exception { protected abstract void setUp(ServletTester tester); - @After + @AfterEach public void tearDownTester() throws Exception { tester.stop(); } diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java index 90d36c408c..a34753384e 100755 --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletTest.java @@ -4,12 +4,12 @@ import io.dropwizard.metrics5.health.HealthCheckRegistry; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class AdminServletTest extends AbstractServletTest { +class AdminServletTest extends AbstractServletTest { private final MetricRegistry registry = new MetricRegistry(); private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); @@ -22,15 +22,15 @@ protected void setUp(ServletTester tester) { tester.addServlet(AdminServlet.class, "/admin"); } - @Before - public void setUp() { + @BeforeEach + void setUp() { request.setMethod("GET"); request.setURI("/context/admin"); request.setVersion("HTTP/1.0"); } @Test - public void returnsA200() throws Exception { + void returnsA200() throws Exception { processRequest(); assertThat(response.getStatus()) diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java index b62cd6df49..b6618a93df 100755 --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/AdminServletUriTest.java @@ -4,12 +4,12 @@ import io.dropwizard.metrics5.health.HealthCheckRegistry; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class AdminServletUriTest extends AbstractServletTest { +class AdminServletUriTest extends AbstractServletTest { private final MetricRegistry registry = new MetricRegistry(); private final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); @@ -27,15 +27,15 @@ protected void setUp(ServletTester tester) { tester.addServlet(AdminServlet.class, "/admin"); } - @Before - public void setUp() { + @BeforeEach + void setUp() { request.setMethod("GET"); request.setURI("/context/admin"); request.setVersion("HTTP/1.0"); } @Test - public void returnsA200() throws Exception { + void returnsA200() throws Exception { processRequest(); assertThat(response.getStatus()) diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java index 335fdc2f96..ac6c761a17 100644 --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/CpuProfileServletTest.java @@ -4,18 +4,18 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class CpuProfileServletTest extends AbstractServletTest { +class CpuProfileServletTest extends AbstractServletTest { @Override protected void setUp(ServletTester tester) { tester.addServlet(CpuProfileServlet.class, "/pprof"); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { request.setMethod("GET"); request.setURI("/pprof?duration=1"); request.setVersion("HTTP/1.0"); @@ -24,19 +24,19 @@ public void setUp() throws Exception { } @Test - public void returns200OK() { + void returns200OK() { assertThat(response.getStatus()) .isEqualTo(200); } @Test - public void returnsPprofRaw() { + void returnsPprofRaw() { assertThat(response.get(HttpHeader.CONTENT_TYPE)) .isEqualTo("pprof/raw"); } @Test - public void returnsUncacheable() { + void returnsUncacheable() { assertThat(response.get(HttpHeader.CACHE_CONTROL)) .isEqualTo("must-revalidate,no-cache,no-store"); diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java index 28bff1e7c2..c3fdc65b8b 100644 --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/HealthCheckServletTest.java @@ -7,9 +7,9 @@ import io.dropwizard.metrics5.health.HealthCheckRegistry; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; @@ -21,13 +21,14 @@ import java.util.concurrent.Executors; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class HealthCheckServletTest extends AbstractServletTest { +class HealthCheckServletTest extends AbstractServletTest { private static final ZonedDateTime FIXED_TIME = ZonedDateTime.now(); @@ -62,20 +63,20 @@ protected void setUp(ServletTester tester) { (HealthCheckFilter) (name, healthCheck) -> !"filtered".equals(name)); } - @Before - public void setUp() { + @BeforeEach + void setUp() { request.setMethod("GET"); request.setURI("/healthchecks"); request.setVersion("HTTP/1.0"); } - @After - public void tearDown() { + @AfterEach + void tearDown() { threadPool.shutdown(); } @Test - public void returns501IfNoHealthChecksAreRegistered() throws Exception { + void returns501IfNoHealthChecksAreRegistered() throws Exception { processRequest(); assertThat(response.getStatus()).isEqualTo(501); @@ -84,7 +85,7 @@ public void returns501IfNoHealthChecksAreRegistered() throws Exception { } @Test - public void returnsA200IfAllHealthChecksAreHealthy() throws Exception { + void returnsA200IfAllHealthChecksAreHealthy() throws Exception { registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); processRequest(); @@ -98,7 +99,7 @@ public void returnsA200IfAllHealthChecksAreHealthy() throws Exception { } @Test - public void returnsASubsetOfHealthChecksIfFiltered() throws Exception { + void returnsASubsetOfHealthChecksIfFiltered() throws Exception { registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); registry.register("filtered", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); @@ -113,7 +114,7 @@ public void returnsASubsetOfHealthChecksIfFiltered() throws Exception { } @Test - public void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { + void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); @@ -127,7 +128,7 @@ public void returnsA500IfAnyHealthChecksAreUnhealthy() throws Exception { } @Test - public void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { + void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisabled() throws Exception { registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("whee"))); registry.register("notFun", new TestHealthCheck(() -> unhealthyResultWithMessage("whee"))); request.setURI("/healthchecks?httpStatusIndicator=false"); @@ -142,7 +143,7 @@ public void returnsA200IfAnyHealthChecksAreUnhealthyAndHttpStatusIndicatorIsDisa } @Test - public void optionallyPrettyPrintsTheJson() throws Exception { + void optionallyPrettyPrintsTheJson() throws Exception { registry.register("fun", new TestHealthCheck(() -> healthyResultWithMessage("foo bar 123"))); request.setURI("/healthchecks?pretty=true"); @@ -178,7 +179,7 @@ private static HealthCheck.Result unhealthyResultWithMessage(String message) { } @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); @@ -192,7 +193,7 @@ public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig } @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { final HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); @@ -207,20 +208,22 @@ public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws verify(servletContext, times(1)).getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY); } - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { - final ServletContext servletContext = mock(ServletContext.class); - final ServletConfig servletConfig = mock(ServletConfig.class); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) - .thenReturn("IRELLEVANT_STRING"); - - final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); - healthCheckServlet.init(servletConfig); + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { + assertThrows(ServletException.class, () -> { + final ServletContext servletContext = mock(ServletContext.class); + final ServletConfig servletConfig = mock(ServletConfig.class); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY)) + .thenReturn("IRELLEVANT_STRING"); + + final HealthCheckServlet healthCheckServlet = new HealthCheckServlet(null); + healthCheckServlet.init(servletConfig); + }); } @Test - public void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { + void constructorWithObjectMapperAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); when(servletConfig.getServletContext()).thenReturn(servletContext); diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java index 1620fcd9b9..f6279571c5 100644 --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletContextListenerTest.java @@ -8,8 +8,8 @@ import io.dropwizard.metrics5.Timer; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; @@ -17,7 +17,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class MetricsServletContextListenerTest extends AbstractServletTest { +class MetricsServletContextListenerTest extends AbstractServletTest { private final Clock clock = mock(Clock.class); private final MetricRegistry registry = new MetricRegistry(); private final String allowedOrigin = "some.other.origin"; @@ -49,8 +49,8 @@ protected String getAllowedOrigin() { }); } - @Before - public void setUp() { + @BeforeEach + void setUp() { // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves // will call getTick again several times and always get the same value (the last specified here) when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); @@ -68,7 +68,7 @@ public void setUp() { } @Test - public void returnsA200() throws Exception { + void returnsA200() throws Exception { processRequest(); assertThat(response.getStatus()) @@ -96,7 +96,7 @@ public void returnsA200() throws Exception { } @Test - public void optionallyPrettyPrintsTheJson() throws Exception { + void optionallyPrettyPrintsTheJson() throws Exception { request.setURI("/metrics?pretty=true"); processRequest(); diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java index 623484da7a..ab91743c44 100644 --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/MetricsServletTest.java @@ -8,8 +8,8 @@ import io.dropwizard.metrics5.Timer; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; @@ -17,6 +17,7 @@ import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -24,7 +25,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -public class MetricsServletTest extends AbstractServletTest { +class MetricsServletTest extends AbstractServletTest { private final Clock clock = mock(Clock.class); private final MetricRegistry registry = new MetricRegistry(); private ServletTester tester; @@ -37,8 +38,8 @@ protected void setUp(ServletTester tester) { tester.getContext().setInitParameter("io.dropwizard.metrics5.servlets.MetricsServlet.allowedOrigin", "*"); } - @Before - public void setUp() { + @BeforeEach + void setUp() { // provide ticks for the setup (calls getTick 6 times). The serialization in the tests themselves // will call getTick again several times and always get the same value (the last specified here) when(clock.getTick()).thenReturn(100L, 100L, 200L, 300L, 300L, 400L); @@ -56,7 +57,7 @@ public void setUp() { } @Test - public void returnsA200() throws Exception { + void returnsA200() throws Exception { processRequest(); assertThat(response.getStatus()) @@ -84,7 +85,7 @@ public void returnsA200() throws Exception { } @Test - public void returnsJsonWhenJsonpInitParamNotSet() throws Exception { + void returnsJsonWhenJsonpInitParamNotSet() throws Exception { String callbackParamName = "callbackParam"; String callbackParamVal = "callbackParamVal"; request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); @@ -115,7 +116,7 @@ public void returnsJsonWhenJsonpInitParamNotSet() throws Exception { } @Test - public void returnsJsonpWhenInitParamSet() throws Exception { + void returnsJsonpWhenInitParamSet() throws Exception { String callbackParamName = "callbackParam"; String callbackParamVal = "callbackParamVal"; request.setURI("/metrics?" + callbackParamName + "=" + callbackParamVal); @@ -146,7 +147,7 @@ public void returnsJsonpWhenInitParamSet() throws Exception { } @Test - public void optionallyPrettyPrintsTheJson() throws Exception { + void optionallyPrettyPrintsTheJson() throws Exception { request.setURI("/metrics?pretty=true"); processRequest(); @@ -220,7 +221,7 @@ public void optionallyPrettyPrintsTheJson() throws Exception { } @Test - public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { + void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { final MetricRegistry metricRegistry = mock(MetricRegistry.class); final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); @@ -234,7 +235,7 @@ public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig } @Test - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { + void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { final MetricRegistry metricRegistry = mock(MetricRegistry.class); final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); @@ -249,15 +250,17 @@ public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); } - @Test(expected = ServletException.class) - public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { - final ServletContext servletContext = mock(ServletContext.class); - final ServletConfig servletConfig = mock(ServletConfig.class); - when(servletConfig.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) - .thenReturn("IRELLEVANT_STRING"); + @Test + void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { + assertThrows(ServletException.class, () -> { + final ServletContext servletContext = mock(ServletContext.class); + final ServletConfig servletConfig = mock(ServletConfig.class); + when(servletConfig.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) + .thenReturn("IRELLEVANT_STRING"); - final MetricsServlet metricsServlet = new MetricsServlet(null); - metricsServlet.init(servletConfig); + final MetricsServlet metricsServlet = new MetricsServlet(null); + metricsServlet.init(servletConfig); + }); } } diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java index 4e7baecbe9..1ac0c799ae 100644 --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/PingServletTest.java @@ -2,19 +2,19 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class PingServletTest extends AbstractServletTest { +class PingServletTest extends AbstractServletTest { @Override protected void setUp(ServletTester tester) { tester.addServlet(PingServlet.class, "/ping"); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { request.setMethod("GET"); request.setURI("/ping"); request.setVersion("HTTP/1.0"); @@ -23,25 +23,25 @@ public void setUp() throws Exception { } @Test - public void returns200OK() { + void returns200OK() { assertThat(response.getStatus()) .isEqualTo(200); } @Test - public void returnsPong() { + void returnsPong() { assertThat(response.getContent()) .isEqualTo(String.format("pong%n")); } @Test - public void returnsTextPlain() { + void returnsTextPlain() { assertThat(response.get(HttpHeader.CONTENT_TYPE)) .isEqualTo("text/plain;charset=ISO-8859-1"); } @Test - public void returnsUncacheable() { + void returnsUncacheable() { assertThat(response.get(HttpHeader.CACHE_CONTROL)) .isEqualTo("must-revalidate,no-cache,no-store"); diff --git a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java index 6880b4c4eb..34e69f7bc2 100644 --- a/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java +++ b/metrics-servlets/src/test/java/io/dropwizard/metrics5/servlets/ThreadDumpServletTest.java @@ -2,19 +2,19 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.servlet.ServletTester; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class ThreadDumpServletTest extends AbstractServletTest { +class ThreadDumpServletTest extends AbstractServletTest { @Override protected void setUp(ServletTester tester) { tester.addServlet(ThreadDumpServlet.class, "/threads"); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { request.setMethod("GET"); request.setURI("/threads"); request.setVersion("HTTP/1.0"); @@ -23,25 +23,25 @@ public void setUp() throws Exception { } @Test - public void returns200OK() { + void returns200OK() { assertThat(response.getStatus()) .isEqualTo(200); } @Test - public void returnsAThreadDump() { + void returnsAThreadDump() { assertThat(response.getContent()) .contains("Finalizer"); } @Test - public void returnsTextPlain() { + void returnsTextPlain() { assertThat(response.get(HttpHeader.CONTENT_TYPE)) .isEqualTo("text/plain"); } @Test - public void returnsUncacheable() { + void returnsUncacheable() { assertThat(response.get(HttpHeader.CACHE_CONTROL)) .isEqualTo("must-revalidate,no-cache,no-store"); diff --git a/pom.xml b/pom.xml index 17556c4d70..aef42f7328 100644 --- a/pom.xml +++ b/pom.xml @@ -61,7 +61,6 @@ 3.23.1 1.12.18 5.1.1 - 4.13.1 1.3 3.10.1 2.18.0 @@ -71,6 +70,7 @@ dropwizard https://sonarcloud.io ${project.artifactId} + 5.9.2 @@ -505,6 +505,23 @@ + + org.openrewrite.maven + rewrite-maven-plugin + 4.39.0 + + + org.openrewrite.java.testing.junit5.JUnit5BestPractices + + + + + org.openrewrite.recipe + rewrite-testing-frameworks + 1.33.0 + + +