diff --git a/javatests/google/registry/monitoring/metrics/CounterTest.java b/javatests/google/registry/monitoring/metrics/CounterTest.java index 91d67f09a..9f794bb16 100644 --- a/javatests/google/registry/monitoring/metrics/CounterTest.java +++ b/javatests/google/registry/monitoring/metrics/CounterTest.java @@ -15,22 +15,18 @@ package google.registry.monitoring.metrics; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.joda.time.Instant; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link Counter}. */ @RunWith(JUnit4.class) public class CounterTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Test public void testGetCardinality_reflectsCurrentCardinality() { Counter counter = @@ -59,11 +55,12 @@ public class CounterTest { ImmutableSet.of( LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar"))); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "The count of labelValues must be equal to the underlying Metric's count of labels."); - - counter.increment("blah"); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> counter.increment("blah")); + assertThat(thrown) + .hasMessageThat() + .contains( + "The count of labelValues must be equal to the underlying Metric's count of labels."); } @Test @@ -122,9 +119,9 @@ public class CounterTest { "vdn", ImmutableSet.of(LabelDescriptor.create("label1", "bar"))); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("The offset provided must be non-negative"); - counter.incrementBy(-1L, "foo"); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> counter.incrementBy(-1L, "foo")); + assertThat(thrown).hasMessageThat().contains("The offset provided must be non-negative"); } @Test diff --git a/javatests/google/registry/monitoring/metrics/CustomFitterTest.java b/javatests/google/registry/monitoring/metrics/CustomFitterTest.java index a1d9ec4f6..3044c6785 100644 --- a/javatests/google/registry/monitoring/metrics/CustomFitterTest.java +++ b/javatests/google/registry/monitoring/metrics/CustomFitterTest.java @@ -15,35 +15,31 @@ package google.registry.monitoring.metrics; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link CustomFitter}. */ @RunWith(JUnit4.class) public class CustomFitterTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Test public void testCreateCustomFitter_emptyBounds_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("boundaries must not be empty"); - - CustomFitter.create(ImmutableSet.of()); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> CustomFitter.create(ImmutableSet.of())); + assertThat(thrown).hasMessageThat().contains("boundaries must not be empty"); } @Test public void testCreateCustomFitter_outOfOrderBounds_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("boundaries must be sorted"); - - CustomFitter.create(ImmutableSet.of(2.0, 0.0)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> CustomFitter.create(ImmutableSet.of(2.0, 0.0))); + assertThat(thrown).hasMessageThat().contains("boundaries must be sorted"); } @Test diff --git a/javatests/google/registry/monitoring/metrics/EventMetricTest.java b/javatests/google/registry/monitoring/metrics/EventMetricTest.java index 54143a503..d9416b23c 100644 --- a/javatests/google/registry/monitoring/metrics/EventMetricTest.java +++ b/javatests/google/registry/monitoring/metrics/EventMetricTest.java @@ -15,6 +15,7 @@ package google.registry.monitoring.metrics; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableRangeMap; @@ -22,9 +23,7 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Range; import org.joda.time.Instant; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -34,9 +33,6 @@ public class EventMetricTest { private final DistributionFitter distributionFitter = CustomFitter.create(ImmutableSet.of(5.0)); private EventMetric metric; - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Before public void setUp() { metric = @@ -67,11 +63,12 @@ public class EventMetricTest { @Test public void testIncrementBy_wrongLabelValueCount_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "The count of labelValues must be equal to the underlying Metric's count of labels."); - - metric.record(1.0, "blah", "blah"); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> metric.record(1.0, "blah", "blah")); + assertThat(thrown) + .hasMessageThat() + .contains( + "The count of labelValues must be equal to the underlying Metric's count of labels."); } @Test diff --git a/javatests/google/registry/monitoring/metrics/ExponentialFitterTest.java b/javatests/google/registry/monitoring/metrics/ExponentialFitterTest.java index df80e9d7b..2b007fb26 100644 --- a/javatests/google/registry/monitoring/metrics/ExponentialFitterTest.java +++ b/javatests/google/registry/monitoring/metrics/ExponentialFitterTest.java @@ -15,57 +15,49 @@ package google.registry.monitoring.metrics; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link ExponentialFitter}. */ @RunWith(JUnit4.class) public class ExponentialFitterTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Test public void testCreateExponentialFitter_zeroNumIntervals_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("numFiniteIntervals must be greater than 0"); - - ExponentialFitter.create(0, 3.0, 1.0); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(0, 3.0, 1.0)); + assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0"); } @Test public void testCreateExponentialFitter_negativeNumIntervals_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("numFiniteIntervals must be greater than 0"); - - ExponentialFitter.create(-1, 3.0, 1.0); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(-1, 3.0, 1.0)); + assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0"); } @Test public void testCreateExponentialFitter_invalidBase_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("base must be greater than 1"); - - ExponentialFitter.create(3, 0.5, 1.0); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(3, 0.5, 1.0)); + assertThat(thrown).hasMessageThat().contains("base must be greater than 1"); } @Test public void testCreateExponentialFitter_zeroScale_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("scale must not be 0"); - - ExponentialFitter.create(3, 2.0, 0.0); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> ExponentialFitter.create(3, 2.0, 0.0)); + assertThat(thrown).hasMessageThat().contains("scale must not be 0"); } @Test public void testCreateExponentialFitter_NanScale_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("value must be finite, not NaN, and not -0.0"); - - ExponentialFitter.create(3, 2.0, Double.NaN); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> ExponentialFitter.create(3, 2.0, Double.NaN)); + assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } @Test diff --git a/javatests/google/registry/monitoring/metrics/FibonacciFitterTest.java b/javatests/google/registry/monitoring/metrics/FibonacciFitterTest.java index 7b2d57ade..bb86b952d 100644 --- a/javatests/google/registry/monitoring/metrics/FibonacciFitterTest.java +++ b/javatests/google/registry/monitoring/metrics/FibonacciFitterTest.java @@ -15,7 +15,7 @@ package google.registry.monitoring.metrics; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableList; import org.junit.Test; @@ -28,22 +28,16 @@ public class FibonacciFitterTest { @Test public void testCreate_maxBucketSizeNegative_throwsException() { - try { - FibonacciFitter.create(-1); - fail("Expected exception"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0"); - } + IllegalArgumentException e = + expectThrows(IllegalArgumentException.class, () -> FibonacciFitter.create(-1)); + assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0"); } @Test public void testCreate_maxBucketSizeZero_throwsException() { - try { - FibonacciFitter.create(0); - fail("Expected exception"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0"); - } + IllegalArgumentException e = + expectThrows(IllegalArgumentException.class, () -> FibonacciFitter.create(0)); + assertThat(e).hasMessageThat().isEqualTo("maxBucketSize must be greater than 0"); } @Test diff --git a/javatests/google/registry/monitoring/metrics/JUnitBackports.java b/javatests/google/registry/monitoring/metrics/JUnitBackports.java new file mode 100644 index 000000000..3ee402777 --- /dev/null +++ b/javatests/google/registry/monitoring/metrics/JUnitBackports.java @@ -0,0 +1,122 @@ +package google.registry.monitoring.metrics; + +/** + * A testing utility class that contains backports of useful but not yet released JUnit methods. + * + *

All of this code was taken directly from + * https://github.com/junit-team/junit4/blob/a832c5afe5b0e7c2590d057a1a49a344d207f8a0/src/main/java/org/junit/Assert.java + */ +public class JUnitBackports { + // TODO(b/68257761): Delete these and switch over to JUnit 4.13 methods upon release. + + /** + * This interface facilitates the use of expectThrows from Java 8. It allows method references to + * void methods (that declare checked exceptions) to be passed directly into expectThrows without + * wrapping. It is not meant to be implemented directly. + * + * @since 4.13 + */ + public interface ThrowingRunnable { + void run() throws Throwable; + } + + /** + * Asserts that {@code runnable} throws an exception of type {@code expectedThrowable} when + * executed. If it does not throw an exception, an {@link AssertionError} is thrown. If it throws + * the wrong type of exception, an {@code AssertionError} is thrown describing the mismatch; the + * exception that was actually thrown can be obtained by calling {@link AssertionError#getCause}. + * + * @param expectedThrowable the expected type of the exception + * @param runnable a function that is expected to throw an exception when executed + * @since 4.13 + */ + public static void assertThrows( + Class expectedThrowable, ThrowingRunnable runnable) { + expectThrows(expectedThrowable, runnable); + } + + /** + * Asserts that {@code runnable} throws an exception of type {@code expectedThrowable} when + * executed. If it does, the exception object is returned. If it does not throw an exception, an + * {@link AssertionError} is thrown. If it throws the wrong type of exception, an {@code + * AssertionError} is thrown describing the mismatch; the exception that was actually thrown can + * be obtained by calling {@link AssertionError#getCause}. + * + * @param expectedThrowable the expected type of the exception + * @param runnable a function that is expected to throw an exception when executed + * @return the exception thrown by {@code runnable} + * @since 4.13 + */ + public static T expectThrows( + Class expectedThrowable, ThrowingRunnable runnable) { + try { + runnable.run(); + } catch (Throwable actualThrown) { + if (expectedThrowable.isInstance(actualThrown)) { + @SuppressWarnings("unchecked") + T retVal = (T) actualThrown; + return retVal; + } else { + String expected = formatClass(expectedThrowable); + Class actualThrowable = actualThrown.getClass(); + String actual = formatClass(actualThrowable); + if (expected.equals(actual)) { + // There must be multiple class loaders. Add the identity hash code so the message + // doesn't say "expected: java.lang.String ..." + expected += "@" + Integer.toHexString(System.identityHashCode(expectedThrowable)); + actual += "@" + Integer.toHexString(System.identityHashCode(actualThrowable)); + } + String mismatchMessage = format("unexpected exception type thrown;", expected, actual); + + // The AssertionError(String, Throwable) ctor is only available on JDK7. + AssertionError assertionError = new AssertionError(mismatchMessage); + assertionError.initCause(actualThrown); + throw assertionError; + } + } + String message = + String.format( + "expected %s to be thrown, but nothing was thrown", formatClass(expectedThrowable)); + throw new AssertionError(message); + } + + static String format(String message, Object expected, Object actual) { + String formatted = ""; + if (message != null && !"".equals(message)) { + formatted = message + " "; + } + String expectedString = String.valueOf(expected); + String actualString = String.valueOf(actual); + if (equalsRegardingNull(expectedString, actualString)) { + return formatted + + "expected: " + + formatClassAndValue(expected, expectedString) + + " but was: " + + formatClassAndValue(actual, actualString); + } else { + return formatted + "expected:<" + expectedString + "> but was:<" + actualString + ">"; + } + } + + private static String formatClass(Class value) { + String className = value.getCanonicalName(); + return className == null ? value.getName() : className; + } + + private static String formatClassAndValue(Object value, String valueString) { + String className = value == null ? "null" : value.getClass().getName(); + return className + "<" + valueString + ">"; + } + + private static boolean equalsRegardingNull(Object expected, Object actual) { + if (expected == null) { + return actual == null; + } + + return isEquals(expected, actual); + } + + private static boolean isEquals(Object expected, Object actual) { + return expected.equals(actual); + } +} diff --git a/javatests/google/registry/monitoring/metrics/LabelDescriptorTest.java b/javatests/google/registry/monitoring/metrics/LabelDescriptorTest.java index 7cfb2a3b8..854daa781 100644 --- a/javatests/google/registry/monitoring/metrics/LabelDescriptorTest.java +++ b/javatests/google/registry/monitoring/metrics/LabelDescriptorTest.java @@ -14,9 +14,10 @@ package google.registry.monitoring.metrics; -import org.junit.Rule; +import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; + import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -24,27 +25,26 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class LabelDescriptorTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testCreate_invalidLabel_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Label name must match the regex"); - LabelDescriptor.create("@", "description"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> LabelDescriptor.create("@", "description")); + assertThat(thrown).hasMessageThat().contains("Label name must match the regex"); } @Test public void testCreate_blankNameField_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Name must not be empty"); - LabelDescriptor.create("", "description"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> LabelDescriptor.create("", "description")); + assertThat(thrown).hasMessageThat().contains("Name must not be empty"); } @Test public void testCreate_blankDescriptionField_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Description must not be empty"); - LabelDescriptor.create("name", ""); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> LabelDescriptor.create("name", "")); + assertThat(thrown).hasMessageThat().contains("Description must not be empty"); } } diff --git a/javatests/google/registry/monitoring/metrics/LinearFitterTest.java b/javatests/google/registry/monitoring/metrics/LinearFitterTest.java index 8955029eb..de9b957cc 100644 --- a/javatests/google/registry/monitoring/metrics/LinearFitterTest.java +++ b/javatests/google/registry/monitoring/metrics/LinearFitterTest.java @@ -15,65 +15,55 @@ package google.registry.monitoring.metrics; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link LinearFitter}. */ @RunWith(JUnit4.class) public class LinearFitterTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Test public void testCreateLinearFitter_zeroNumIntervals_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("numFiniteIntervals must be greater than 0"); - - LinearFitter.create(0, 3.0, 0.0); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(0, 3.0, 0.0)); + assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0"); } @Test public void testCreateLinearFitter_negativeNumIntervals_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("numFiniteIntervals must be greater than 0"); - - LinearFitter.create(0, 3.0, 0.0); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(0, 3.0, 0.0)); + assertThat(thrown).hasMessageThat().contains("numFiniteIntervals must be greater than 0"); } @Test public void testCreateLinearFitter_zeroWidth_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("width must be greater than 0"); - - LinearFitter.create(3, 0.0, 0.0); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 0.0, 0.0)); + assertThat(thrown).hasMessageThat().contains("width must be greater than 0"); } @Test public void testCreateLinearFitter_negativeWidth_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("width must be greater than 0"); - - LinearFitter.create(3, 0.0, 0.0); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 0.0, 0.0)); + assertThat(thrown).hasMessageThat().contains("width must be greater than 0"); } @Test public void testCreateLinearFitter_NaNWidth_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("width must be greater than 0"); - - LinearFitter.create(3, Double.NaN, 0.0); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, Double.NaN, 0.0)); + assertThat(thrown).hasMessageThat().contains("width must be greater than 0"); } @Test public void testCreateLinearFitter_NaNOffset_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("value must be finite, not NaN, and not -0.0"); - - LinearFitter.create(3, 1.0, Double.NaN); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> LinearFitter.create(3, 1.0, Double.NaN)); + assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } @Test diff --git a/javatests/google/registry/monitoring/metrics/MetricRegistryImplTest.java b/javatests/google/registry/monitoring/metrics/MetricRegistryImplTest.java index a6a21deb7..4884cdef2 100644 --- a/javatests/google/registry/monitoring/metrics/MetricRegistryImplTest.java +++ b/javatests/google/registry/monitoring/metrics/MetricRegistryImplTest.java @@ -15,6 +15,7 @@ package google.registry.monitoring.metrics; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; import static org.mockito.Mockito.mock; import com.google.common.collect.ImmutableList; @@ -22,9 +23,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import google.registry.monitoring.metrics.MetricSchema.Kind; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -36,9 +35,6 @@ import org.junit.runners.JUnit4; */ @RunWith(JUnit4.class) public class MetricRegistryImplTest { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - private final LabelDescriptor label = LabelDescriptor.create("test_labelname", "test_labeldescription"); @@ -162,8 +158,10 @@ public class MetricRegistryImplTest { Boolean.class); MetricRegistryImpl.getDefault().registerMetric("/test/metric", testMetric); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Duplicate metric of same name"); - MetricRegistryImpl.getDefault().registerMetric("/test/metric", testMetric); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> MetricRegistryImpl.getDefault().registerMetric("/test/metric", testMetric)); + assertThat(thrown).hasMessageThat().contains("Duplicate metric of same name"); } } diff --git a/javatests/google/registry/monitoring/metrics/MetricSchemaTest.java b/javatests/google/registry/monitoring/metrics/MetricSchemaTest.java index ccf64334c..7f2d4c1ca 100644 --- a/javatests/google/registry/monitoring/metrics/MetricSchemaTest.java +++ b/javatests/google/registry/monitoring/metrics/MetricSchemaTest.java @@ -14,11 +14,12 @@ package google.registry.monitoring.metrics; +import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; + import com.google.common.collect.ImmutableSet; import google.registry.monitoring.metrics.MetricSchema.Kind; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -26,37 +27,59 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class MetricSchemaTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testCreate_blankNameField_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Name must not be blank"); - MetricSchema.create( - "", "description", "valueDisplayName", Kind.GAUGE, ImmutableSet.of()); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + MetricSchema.create( + "", + "description", + "valueDisplayName", + Kind.GAUGE, + ImmutableSet.of())); + assertThat(thrown).hasMessageThat().contains("Name must not be blank"); } @Test public void testCreate_blankDescriptionField_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Description must not be blank"); - MetricSchema.create( - "/name", "", "valueDisplayName", Kind.GAUGE, ImmutableSet.of()); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + MetricSchema.create( + "/name", + "", + "valueDisplayName", + Kind.GAUGE, + ImmutableSet.of())); + assertThat(thrown).hasMessageThat().contains("Description must not be blank"); } @Test public void testCreate_blankValueDisplayNameField_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Value Display Name must not be empty"); - MetricSchema.create("/name", "description", "", Kind.GAUGE, ImmutableSet.of()); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + MetricSchema.create( + "/name", "description", "", Kind.GAUGE, ImmutableSet.of())); + assertThat(thrown).hasMessageThat().contains("Value Display Name must not be empty"); } @Test public void testCreate_nakedNames_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Name must be URL-like and start with a '/'"); - MetricSchema.create( - "foo", "description", "valueDisplayName", Kind.GAUGE, ImmutableSet.of()); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + MetricSchema.create( + "foo", + "description", + "valueDisplayName", + Kind.GAUGE, + ImmutableSet.of())); + assertThat(thrown).hasMessageThat().contains("Name must be URL-like and start with a '/'"); } } diff --git a/javatests/google/registry/monitoring/metrics/MutableDistributionTest.java b/javatests/google/registry/monitoring/metrics/MutableDistributionTest.java index d87f75f42..bba75783d 100644 --- a/javatests/google/registry/monitoring/metrics/MutableDistributionTest.java +++ b/javatests/google/registry/monitoring/metrics/MutableDistributionTest.java @@ -15,14 +15,13 @@ package google.registry.monitoring.metrics; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableRangeMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Range; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -31,9 +30,6 @@ import org.junit.runners.JUnit4; public class MutableDistributionTest { private MutableDistribution distribution; - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Before public void setUp() throws Exception { distribution = new MutableDistribution(CustomFitter.create(ImmutableSet.of(3.0, 5.0))); @@ -125,30 +121,34 @@ public class MutableDistributionTest { @Test public void testAdd_negativeZero_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("value must be finite, not NaN, and not -0.0"); - distribution.add(Double.longBitsToDouble(0x80000000)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> distribution.add(Double.longBitsToDouble(0x80000000))); + assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } @Test public void testAdd_NaN_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("value must be finite, not NaN, and not -0.0"); - distribution.add(Double.NaN); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> distribution.add(Double.NaN)); + assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } @Test public void testAdd_positiveInfinity_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("value must be finite, not NaN, and not -0.0"); - distribution.add(Double.POSITIVE_INFINITY); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> distribution.add(Double.POSITIVE_INFINITY)); + assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } @Test public void testAdd_negativeInfinity_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("value must be finite, not NaN, and not -0.0"); - distribution.add(Double.NEGATIVE_INFINITY); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> distribution.add(Double.NEGATIVE_INFINITY)); + assertThat(thrown).hasMessageThat().contains("value must be finite, not NaN, and not -0.0"); } @Test diff --git a/javatests/google/registry/monitoring/metrics/StoredMetricTest.java b/javatests/google/registry/monitoring/metrics/StoredMetricTest.java index b41c85b8a..62b0918f4 100644 --- a/javatests/google/registry/monitoring/metrics/StoredMetricTest.java +++ b/javatests/google/registry/monitoring/metrics/StoredMetricTest.java @@ -15,13 +15,12 @@ package google.registry.monitoring.metrics; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.joda.time.Instant; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -29,9 +28,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class StoredMetricTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testGetCardinality_reflectsCurrentCardinality() { StoredMetric smallMetric = @@ -68,11 +64,12 @@ public class StoredMetricTest { LabelDescriptor.create("label1", "bar"), LabelDescriptor.create("label2", "bar")), Boolean.class); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "The count of labelValues must be equal to the underlying Metric's count of labels."); - - dimensionalMetric.set(true, "foo"); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> dimensionalMetric.set(true, "foo")); + assertThat(thrown) + .hasMessageThat() + .contains( + "The count of labelValues must be equal to the underlying Metric's count of labels."); } @Test diff --git a/javatests/google/registry/monitoring/metrics/contrib/BUILD b/javatests/google/registry/monitoring/metrics/contrib/BUILD index 813687ed0..3d35e1445 100644 --- a/javatests/google/registry/monitoring/metrics/contrib/BUILD +++ b/javatests/google/registry/monitoring/metrics/contrib/BUILD @@ -13,7 +13,7 @@ java_library( deps = [ "//java/google/registry/monitoring/metrics", "//java/google/registry/monitoring/metrics/contrib", - "//javatests/google/registry/testing", + "//javatests/google/registry/monitoring/metrics", "@com_google_guava", "@com_google_truth", "@com_google_truth_extensions_truth_java8_extension", diff --git a/javatests/google/registry/monitoring/metrics/contrib/DistributionMetricSubjectTest.java b/javatests/google/registry/monitoring/metrics/contrib/DistributionMetricSubjectTest.java index 832415691..7fd0db04a 100644 --- a/javatests/google/registry/monitoring/metrics/contrib/DistributionMetricSubjectTest.java +++ b/javatests/google/registry/monitoring/metrics/contrib/DistributionMetricSubjectTest.java @@ -15,8 +15,8 @@ package google.registry.monitoring.metrics.contrib; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; import static google.registry.monitoring.metrics.contrib.DistributionMetricSubject.assertThat; -import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableSet; import google.registry.monitoring.metrics.EventMetric; diff --git a/javatests/google/registry/monitoring/metrics/contrib/LongMetricSubjectTest.java b/javatests/google/registry/monitoring/metrics/contrib/LongMetricSubjectTest.java index daaece1e0..b78abf8d2 100644 --- a/javatests/google/registry/monitoring/metrics/contrib/LongMetricSubjectTest.java +++ b/javatests/google/registry/monitoring/metrics/contrib/LongMetricSubjectTest.java @@ -15,8 +15,8 @@ package google.registry.monitoring.metrics.contrib; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.expectThrows; import static google.registry.monitoring.metrics.contrib.LongMetricSubject.assertThat; -import static org.junit.Assert.fail; import com.google.common.collect.ImmutableSet; import google.registry.monitoring.metrics.IncrementableMetric; @@ -52,16 +52,14 @@ public class LongMetricSubjectTest { @Test public void testWrongNumberOfLabels_fails() { - try { - assertThat(metric).hasValueForLabels(1, "Domestic"); - fail("Expected assertion error"); - } catch (AssertionError e) { - assertThat(e) - .hasMessageThat() - .isEqualTo( - "Not true that has a value for labels ." - + " It has labeled values <[Bighorn:Blue => 2, Domestic:Green => 1]>"); - } + AssertionError e = + expectThrows( + AssertionError.class, () -> assertThat(metric).hasValueForLabels(1, "Domestic")); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Not true that has a value for labels ." + + " It has labeled values <[Bighorn:Blue => 2, Domestic:Green => 1]>"); } @Test @@ -96,43 +94,44 @@ public class LongMetricSubjectTest { @Test public void testDoesNotHaveValueForLabels_failure() { - try { - assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Green"); - fail("Expected assertion error"); - } catch (AssertionError e) { - assertThat(e) - .hasMessageThat() - .isEqualTo( - "Not true that has no value for labels ." - + " It has a value of <1>"); - } + AssertionError e = + expectThrows( + AssertionError.class, + () -> assertThat(metric).doesNotHaveAnyValueForLabels("Domestic", "Green")); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Not true that has no value for labels ." + + " It has a value of <1>"); } @Test public void testWrongValue_failure() { - try { - assertThat(metric).hasValueForLabels(2, "Domestic", "Green"); - fail("Expected assertion error"); - } catch (AssertionError e) { - assertThat(e) - .hasMessageThat() - .isEqualTo( - "Not true that has a value of 2" - + " for labels . It has a value of <1>"); - } + AssertionError e = + expectThrows( + AssertionError.class, + () -> assertThat(metric).hasValueForLabels(2, "Domestic", "Green")); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Not true that has a value of 2" + + " for labels . It has a value of <1>"); } @Test public void testUnexpectedValue_failure() { - try { - assertThat(metric).hasValueForLabels(1, "Domestic", "Green").and().hasNoOtherValues(); - fail("Expected assertion error"); - } catch (AssertionError e) { - assertThat(e) - .hasMessageThat() - .isEqualTo( - "Not true that has ." - + " It has labeled values <[Bighorn:Blue => 2, Domestic:Green => 1]>"); - } + AssertionError e = + expectThrows( + AssertionError.class, + () -> + assertThat(metric) + .hasValueForLabels(1, "Domestic", "Green") + .and() + .hasNoOtherValues()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "Not true that has ." + + " It has labeled values <[Bighorn:Blue => 2, Domestic:Green => 1]>"); } } diff --git a/javatests/google/registry/monitoring/metrics/stackdriver/BUILD b/javatests/google/registry/monitoring/metrics/stackdriver/BUILD index 84e6fd6e8..fd3b26751 100644 --- a/javatests/google/registry/monitoring/metrics/stackdriver/BUILD +++ b/javatests/google/registry/monitoring/metrics/stackdriver/BUILD @@ -13,6 +13,7 @@ java_library( deps = [ "//java/google/registry/monitoring/metrics", "//java/google/registry/monitoring/metrics/stackdriver", + "//javatests/google/registry/monitoring/metrics", "@com_google_api_client", "@com_google_apis_google_api_services_monitoring", "@com_google_guava", diff --git a/javatests/google/registry/monitoring/metrics/stackdriver/StackdriverWriterTest.java b/javatests/google/registry/monitoring/metrics/stackdriver/StackdriverWriterTest.java index 51e73f073..51dfaab60 100644 --- a/javatests/google/registry/monitoring/metrics/stackdriver/StackdriverWriterTest.java +++ b/javatests/google/registry/monitoring/metrics/stackdriver/StackdriverWriterTest.java @@ -15,8 +15,8 @@ package google.registry.monitoring.metrics.stackdriver; import static com.google.common.truth.Truth.assertThat; +import static google.registry.monitoring.metrics.JUnitBackports.assertThrows; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.never; @@ -184,10 +184,7 @@ public class StackdriverWriterTest { new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); for (MetricPoint point : metric.getTimestampedValues()) { - try { - writer.write(point); - fail("expected IllegalArgumentException"); - } catch (IOException expected) {} + assertThrows(IOException.class, () -> writer.write(point)); } } @@ -272,12 +269,8 @@ public class StackdriverWriterTest { StackdriverWriter writer = new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST); - try { - writer.registerMetric(metric); - fail("Expected GoogleJsonResponseException"); - } catch (GoogleJsonResponseException expected) { - assertThat(exception.getStatusCode()).isEqualTo(404); - } + assertThrows(GoogleJsonResponseException.class, () -> writer.registerMetric(metric)); + assertThat(exception.getStatusCode()).isEqualTo(404); } @Test