diff --git a/javatests/google/registry/batch/DeleteContactsAndHostsActionTest.java b/javatests/google/registry/batch/DeleteContactsAndHostsActionTest.java index 52065b2f9..118e761f5 100644 --- a/javatests/google/registry/batch/DeleteContactsAndHostsActionTest.java +++ b/javatests/google/registry/batch/DeleteContactsAndHostsActionTest.java @@ -102,7 +102,6 @@ import org.joda.time.Duration; 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; @@ -111,9 +110,6 @@ import org.junit.runners.JUnit4; public class DeleteContactsAndHostsActionTest extends MapreduceTestCase { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); diff --git a/javatests/google/registry/batch/DeleteProberDataActionTest.java b/javatests/google/registry/batch/DeleteProberDataActionTest.java index 28033c11f..606fe2e41 100644 --- a/javatests/google/registry/batch/DeleteProberDataActionTest.java +++ b/javatests/google/registry/batch/DeleteProberDataActionTest.java @@ -49,9 +49,7 @@ import java.util.Set; import org.joda.money.Money; import org.joda.time.DateTime; 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; @@ -61,9 +59,6 @@ public class DeleteProberDataActionTest extends MapreduceTestCase { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -649,18 +645,22 @@ public class ExpandRecurringBillingEventsActionTest @Test public void testFailure_cursorAfterExecutionTime() throws Exception { action.cursorTimeParam = Optional.of(clock.nowUtc().plusYears(1)); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Cursor time must be earlier than execution time."); - runMapreduce(); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> runMapreduce()); + assertThat(thrown) + .hasMessageThat() + .contains("Cursor time must be earlier than execution time."); } @Test public void testFailure_cursorAtExecutionTime() throws Exception { // The clock advances one milli on runMapreduce. action.cursorTimeParam = Optional.of(clock.nowUtc().plusMillis(1)); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Cursor time must be earlier than execution time."); - runMapreduce(); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> runMapreduce()); + assertThat(thrown) + .hasMessageThat() + .contains("Cursor time must be earlier than execution time."); } @Test diff --git a/javatests/google/registry/batch/MapreduceEntityCleanupActionTest.java b/javatests/google/registry/batch/MapreduceEntityCleanupActionTest.java index 3582f3aec..9682f24fe 100644 --- a/javatests/google/registry/batch/MapreduceEntityCleanupActionTest.java +++ b/javatests/google/registry/batch/MapreduceEntityCleanupActionTest.java @@ -52,9 +52,7 @@ import google.registry.testing.mapreduce.MapreduceTestCase; import java.util.List; import java.util.Optional; import org.joda.time.DateTime; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -62,8 +60,6 @@ import org.junit.runners.JUnit4; public class MapreduceEntityCleanupActionTest extends MapreduceTestCase { - @Rule public final ExpectedException thrown = ExpectedException.none(); - private static final DatastoreService datastore = getDatastoreService(); private static final FetchOptions FETCH_OPTIONS = FetchOptions.Builder.withChunkSize(200); private static final String QUEUE_NAME = "mapreduce"; diff --git a/javatests/google/registry/batch/RefreshDnsOnHostRenameActionTest.java b/javatests/google/registry/batch/RefreshDnsOnHostRenameActionTest.java index d34cf8474..c7158d937 100644 --- a/javatests/google/registry/batch/RefreshDnsOnHostRenameActionTest.java +++ b/javatests/google/registry/batch/RefreshDnsOnHostRenameActionTest.java @@ -60,7 +60,6 @@ import org.joda.time.Duration; 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; @@ -69,9 +68,6 @@ import org.junit.runners.JUnit4; public class RefreshDnsOnHostRenameActionTest extends MapreduceTestCase { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public InjectRule inject = new InjectRule(); diff --git a/javatests/google/registry/bigquery/BigqueryUtilsTest.java b/javatests/google/registry/bigquery/BigqueryUtilsTest.java index 972bc730f..06af3de7f 100644 --- a/javatests/google/registry/bigquery/BigqueryUtilsTest.java +++ b/javatests/google/registry/bigquery/BigqueryUtilsTest.java @@ -19,6 +19,7 @@ import static google.registry.bigquery.BigqueryUtils.fromBigqueryTimestampString import static google.registry.bigquery.BigqueryUtils.toBigqueryTimestamp; import static google.registry.bigquery.BigqueryUtils.toBigqueryTimestampString; import static google.registry.bigquery.BigqueryUtils.toJobReferenceString; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME; @@ -26,19 +27,13 @@ import com.google.api.services.bigquery.model.JobReference; import java.util.concurrent.TimeUnit; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -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 BigqueryUtils}. */ @RunWith(JUnit4.class) public class BigqueryUtilsTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private static final DateTime DATE_0 = DateTime.parse("2014-07-17T20:35:42Z"); private static final DateTime DATE_1 = DateTime.parse("2014-07-17T20:35:42.1Z"); private static final DateTime DATE_2 = DateTime.parse("2014-07-17T20:35:42.12Z"); @@ -84,20 +79,22 @@ public class BigqueryUtilsTest { @Test public void testFailure_fromBigqueryTimestampString_nonUtcTimeZone() throws Exception { - thrown.expect(IllegalArgumentException.class); - fromBigqueryTimestampString("2014-01-01 01:01:01 +05:00"); + assertThrows( + IllegalArgumentException.class, + () -> fromBigqueryTimestampString("2014-01-01 01:01:01 +05:00")); } @Test public void testFailure_fromBigqueryTimestampString_noTimeZone() throws Exception { - thrown.expect(IllegalArgumentException.class); - fromBigqueryTimestampString("2014-01-01 01:01:01"); + assertThrows( + IllegalArgumentException.class, () -> fromBigqueryTimestampString("2014-01-01 01:01:01")); } @Test public void testFailure_fromBigqueryTimestampString_tooManyMillisecondDigits() throws Exception { - thrown.expect(IllegalArgumentException.class); - fromBigqueryTimestampString("2014-01-01 01:01:01.1234 UTC"); + assertThrows( + IllegalArgumentException.class, + () -> fromBigqueryTimestampString("2014-01-01 01:01:01.1234 UTC")); } @Test @@ -142,7 +139,6 @@ public class BigqueryUtilsTest { @Test public void test_toJobReferenceString_nullThrowsNpe() throws Exception { - thrown.expect(NullPointerException.class); - toJobReferenceString(null); + assertThrows(NullPointerException.class, () -> toJobReferenceString(null)); } } diff --git a/javatests/google/registry/cron/CommitLogFanoutActionTest.java b/javatests/google/registry/cron/CommitLogFanoutActionTest.java index dd3df5f8f..1fda93201 100644 --- a/javatests/google/registry/cron/CommitLogFanoutActionTest.java +++ b/javatests/google/registry/cron/CommitLogFanoutActionTest.java @@ -28,7 +28,6 @@ import java.util.List; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -39,9 +38,6 @@ public class CommitLogFanoutActionTest { private static final String ENDPOINT = "/the/servlet"; private static final String QUEUE = "the-queue"; - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() diff --git a/javatests/google/registry/cron/TldFanoutActionTest.java b/javatests/google/registry/cron/TldFanoutActionTest.java index 1f91b3411..31ead3030 100644 --- a/javatests/google/registry/cron/TldFanoutActionTest.java +++ b/javatests/google/registry/cron/TldFanoutActionTest.java @@ -41,7 +41,6 @@ import java.util.Optional; 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; @@ -53,9 +52,6 @@ public class TldFanoutActionTest { private static final String QUEUE = "the-queue"; private final FakeResponse response = new FakeResponse(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() diff --git a/javatests/google/registry/dns/DnsInjectionTest.java b/javatests/google/registry/dns/DnsInjectionTest.java index 6e4a6fd1d..3ee29847a 100644 --- a/javatests/google/registry/dns/DnsInjectionTest.java +++ b/javatests/google/registry/dns/DnsInjectionTest.java @@ -14,9 +14,11 @@ package google.registry.dns; +import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHost; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.TaskQueueHelper.assertDnsTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertNoDnsTasksEnqueued; import static org.mockito.Mockito.mock; @@ -36,7 +38,6 @@ import org.joda.time.DateTime; 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; @@ -50,9 +51,6 @@ public final class DnsInjectionTest { .withTaskQueue() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -97,9 +95,9 @@ public final class DnsInjectionTest { public void testRefreshDns_missingDomain_throwsNotFound() throws Exception { when(req.getParameter("type")).thenReturn("domain"); when(req.getParameter("name")).thenReturn("example.lol"); - thrown.expect(NotFoundException.class); - thrown.expectMessage("domain example.lol not found"); - component.refreshDns().run(); + NotFoundException thrown = + expectThrows(NotFoundException.class, () -> component.refreshDns().run()); + assertThat(thrown).hasMessageThat().contains("domain example.lol not found"); } @Test @@ -115,8 +113,8 @@ public final class DnsInjectionTest { public void testRefreshDns_missingHost_throwsNotFound() throws Exception { when(req.getParameter("type")).thenReturn("host"); when(req.getParameter("name")).thenReturn("ns1.example.lol"); - thrown.expect(NotFoundException.class); - thrown.expectMessage("host ns1.example.lol not found"); - component.refreshDns().run(); + NotFoundException thrown = + expectThrows(NotFoundException.class, () -> component.refreshDns().run()); + assertThat(thrown).hasMessageThat().contains("host ns1.example.lol not found"); } } diff --git a/javatests/google/registry/dns/DnsQueueTest.java b/javatests/google/registry/dns/DnsQueueTest.java index e0e013e5f..5829945ac 100644 --- a/javatests/google/registry/dns/DnsQueueTest.java +++ b/javatests/google/registry/dns/DnsQueueTest.java @@ -14,7 +14,9 @@ package google.registry.dns; +import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatastoreHelper.createTld; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; @@ -23,7 +25,6 @@ import google.registry.testing.TaskQueueHelper.TaskMatcher; 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; @@ -36,10 +37,6 @@ public class DnsQueueTest { .withDatastore() .withTaskQueue() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private DnsQueue dnsQueue; @Before @@ -62,13 +59,19 @@ public class DnsQueueTest { @Test public void test_addHostRefreshTask_failsOnUnknownTld() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("octopus.notatld is not a subordinate host to a known tld"); - try { - dnsQueue.addHostRefreshTask("octopus.notatld"); - } finally { - assertNoTasksEnqueued("dns-pull"); - } + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> { + try { + dnsQueue.addHostRefreshTask("octopus.notatld"); + } finally { + assertNoTasksEnqueued("dns-pull"); + } + }); + assertThat(thrown) + .hasMessageThat() + .contains("octopus.notatld is not a subordinate host to a known tld"); } @Test @@ -85,13 +88,17 @@ public class DnsQueueTest { @Test public void test_addDomainRefreshTask_failsOnUnknownTld() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("TLD notatld does not exist"); - try { - dnsQueue.addDomainRefreshTask("fake.notatld"); - } finally { - assertNoTasksEnqueued("dns-pull"); - } + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> { + try { + dnsQueue.addDomainRefreshTask("fake.notatld"); + } finally { + assertNoTasksEnqueued("dns-pull"); + } + }); + assertThat(thrown).hasMessageThat().contains("TLD notatld does not exist"); } } diff --git a/javatests/google/registry/dns/PublishDnsUpdatesActionTest.java b/javatests/google/registry/dns/PublishDnsUpdatesActionTest.java index 3966883fd..82b42befe 100644 --- a/javatests/google/registry/dns/PublishDnsUpdatesActionTest.java +++ b/javatests/google/registry/dns/PublishDnsUpdatesActionTest.java @@ -14,10 +14,12 @@ package google.registry.dns; +import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHost; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -40,7 +42,6 @@ import org.joda.time.Duration; 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; @@ -56,10 +57,6 @@ public class PublishDnsUpdatesActionTest { @Rule public final InjectRule inject = new InjectRule(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final FakeClock clock = new FakeClock(DateTime.parse("1971-01-01TZ")); private final FakeLockHandler lockHandler = new FakeLockHandler(true); private final DnsWriter dnsWriter = mock(DnsWriter.class); @@ -187,19 +184,24 @@ public class PublishDnsUpdatesActionTest { @Test public void testLockIsntAvailable() throws Exception { - thrown.expect(ServiceUnavailableException.class); - thrown.expectMessage("Lock failure"); - action = createAction("xn--q9jyb4c"); - action.domains = ImmutableSet.of("example.com", "example2.com"); - action.hosts = ImmutableSet.of("ns1.example.com", "ns2.example.com", "ns1.example2.com"); - action.lockHandler = new FakeLockHandler(false); - action.run(); + ServiceUnavailableException thrown = + expectThrows( + ServiceUnavailableException.class, + () -> { + action = createAction("xn--q9jyb4c"); + action.domains = ImmutableSet.of("example.com", "example2.com"); + action.hosts = + ImmutableSet.of("ns1.example.com", "ns2.example.com", "ns1.example2.com"); + action.lockHandler = new FakeLockHandler(false); + action.run(); - verifyNoMoreInteractions(dnsWriter); + verifyNoMoreInteractions(dnsWriter); - verifyNoMoreInteractions(dnsMetrics); + verifyNoMoreInteractions(dnsMetrics); - verifyNoMoreInteractions(dnsQueue); + verifyNoMoreInteractions(dnsQueue); + }); + assertThat(thrown).hasMessageThat().contains("Lock failure"); } @Test diff --git a/javatests/google/registry/dns/RefreshDnsActionTest.java b/javatests/google/registry/dns/RefreshDnsActionTest.java index 29736d486..b42751169 100644 --- a/javatests/google/registry/dns/RefreshDnsActionTest.java +++ b/javatests/google/registry/dns/RefreshDnsActionTest.java @@ -14,10 +14,13 @@ package google.registry.dns; +import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistActiveHost; import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHost; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -31,7 +34,6 @@ import google.registry.testing.FakeClock; 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; @@ -44,10 +46,6 @@ public class RefreshDnsActionTest { .withDatastore() .withTaskQueue() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final DnsQueue dnsQueue = mock(DnsQueue.class); private final FakeClock clock = new FakeClock(); @@ -78,13 +76,19 @@ public class RefreshDnsActionTest { public void testSuccess_externalHostNotEnqueued() throws Exception { persistActiveDomain("example.xn--q9jyb4c"); persistActiveHost("ns1.example.xn--q9jyb4c"); - thrown.expect(BadRequestException.class); - thrown.expectMessage("ns1.example.xn--q9jyb4c isn't a subordinate hostname"); - try { - run(TargetType.HOST, "ns1.example.xn--q9jyb4c"); - } finally { - verifyNoMoreInteractions(dnsQueue); - } + BadRequestException thrown = + expectThrows( + BadRequestException.class, + () -> { + try { + run(TargetType.HOST, "ns1.example.xn--q9jyb4c"); + } finally { + verifyNoMoreInteractions(dnsQueue); + } + }); + assertThat(thrown) + .hasMessageThat() + .contains("ns1.example.xn--q9jyb4c isn't a subordinate hostname"); } @Test @@ -97,19 +101,16 @@ public class RefreshDnsActionTest { @Test public void testFailure_unqualifiedName() throws Exception { - thrown.expect(BadRequestException.class); - run(TargetType.DOMAIN, "example"); + assertThrows(BadRequestException.class, () -> run(TargetType.DOMAIN, "example")); } @Test public void testFailure_hostDoesNotExist() throws Exception { - thrown.expect(NotFoundException.class); - run(TargetType.HOST, "ns1.example.xn--q9jyb4c"); + assertThrows(NotFoundException.class, () -> run(TargetType.HOST, "ns1.example.xn--q9jyb4c")); } @Test public void testFailure_domainDoesNotExist() throws Exception { - thrown.expect(NotFoundException.class); - run(TargetType.DOMAIN, "example.xn--q9jyb4c"); + assertThrows(NotFoundException.class, () -> run(TargetType.DOMAIN, "example.xn--q9jyb4c")); } } diff --git a/javatests/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java b/javatests/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java index 3b198c7e0..494b94f81 100644 --- a/javatests/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java +++ b/javatests/google/registry/dns/writer/clouddns/CloudDnsWriterTest.java @@ -56,7 +56,6 @@ import org.joda.time.Duration; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -85,8 +84,6 @@ public class CloudDnsWriterTest { private CloudDnsWriter writer; private ImmutableSet stubZone; - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); /* diff --git a/javatests/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java b/javatests/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java index af474a6e3..56db82bc8 100644 --- a/javatests/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java +++ b/javatests/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java @@ -17,6 +17,7 @@ package google.registry.dns.writer.dnsupdate; import static com.google.common.io.BaseEncoding.base16; import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -34,9 +35,7 @@ import java.util.Arrays; import javax.net.SocketFactory; import org.joda.time.Duration; 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; import org.xbill.DNS.ARecord; @@ -62,10 +61,6 @@ public class DnsMessageTransportTest { private Message simpleQuery; private Message expectedResponse; private DnsMessageTransport resolver; - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Before public void before() throws Exception { simpleQuery = @@ -114,9 +109,7 @@ public class DnsMessageTransportTest { new ByteArrayInputStream(Arrays.copyOf(messageBytes, messageBytes.length - 1)); when(mockSocket.getInputStream()).thenReturn(inputStream); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); - thrown.expect(EOFException.class); - - resolver.send(new Message()); + assertThrows(EOFException.class, () -> resolver.send(new Message())); } @Test @@ -145,10 +138,9 @@ public class DnsMessageTransportTest { } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(mockSocket.getOutputStream()).thenReturn(outputStream); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("message larger than maximum"); - - resolver.send(oversize); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> resolver.send(oversize)); + assertThat(thrown).hasMessageThat().contains("message larger than maximum"); } @Test @@ -157,13 +149,14 @@ public class DnsMessageTransportTest { when(mockSocket.getInputStream()) .thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse))); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); - thrown.expect(VerifyException.class); - thrown.expectMessage("response ID " - + expectedResponse.getHeader().getID() - + " does not match query ID " - + simpleQuery.getHeader().getID()); - - resolver.send(simpleQuery); + VerifyException thrown = expectThrows(VerifyException.class, () -> resolver.send(simpleQuery)); + assertThat(thrown) + .hasMessageThat() + .contains( + "response ID " + + expectedResponse.getHeader().getID() + + " does not match query ID " + + simpleQuery.getHeader().getID()); } @Test @@ -173,10 +166,10 @@ public class DnsMessageTransportTest { when(mockSocket.getInputStream()) .thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse))); when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream()); - thrown.expect(VerifyException.class); - thrown.expectMessage("response opcode 'STATUS' does not match query opcode 'QUERY'"); - - resolver.send(simpleQuery); + VerifyException thrown = expectThrows(VerifyException.class, () -> resolver.send(simpleQuery)); + assertThat(thrown) + .hasMessageThat() + .contains("response opcode 'STATUS' does not match query opcode 'QUERY'"); } private Message responseMessageWithCode(Message query, int responseCode) { diff --git a/javatests/google/registry/dns/writer/dnsupdate/DnsUpdateWriterTest.java b/javatests/google/registry/dns/writer/dnsupdate/DnsUpdateWriterTest.java index 8dac2e859..8df7af845 100644 --- a/javatests/google/registry/dns/writer/dnsupdate/DnsUpdateWriterTest.java +++ b/javatests/google/registry/dns/writer/dnsupdate/DnsUpdateWriterTest.java @@ -26,6 +26,7 @@ import static google.registry.testing.DatastoreHelper.persistActiveSubordinateHo import static google.registry.testing.DatastoreHelper.persistDeletedDomain; import static google.registry.testing.DatastoreHelper.persistDeletedHost; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -52,7 +53,6 @@ import org.joda.time.Duration; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -76,9 +76,6 @@ public class DnsUpdateWriterTest { public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().withTaskQueue().build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -390,11 +387,14 @@ public class DnsUpdateWriterTest { .build(); persistResource(domain); when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL)); - thrown.expect(VerifyException.class); - thrown.expectMessage("SERVFAIL"); - - writer.publishDomain("example.tld"); - writer.commit(); + VerifyException thrown = + expectThrows( + VerifyException.class, + () -> { + writer.publishDomain("example.tld"); + writer.commit(); + }); + assertThat(thrown).hasMessageThat().contains("SERVFAIL"); } @Test @@ -406,11 +406,14 @@ public class DnsUpdateWriterTest { .build(); persistResource(host); when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL)); - thrown.expect(VerifyException.class); - thrown.expectMessage("SERVFAIL"); - - writer.publishHost("ns1.example.tld"); - writer.commit(); + VerifyException thrown = + expectThrows( + VerifyException.class, + () -> { + writer.publishHost("ns1.example.tld"); + writer.commit(); + }); + assertThat(thrown).hasMessageThat().contains("SERVFAIL"); } private void assertThatUpdatedZoneIs(Update update, String zoneName) { diff --git a/javatests/google/registry/export/BigqueryPollJobActionTest.java b/javatests/google/registry/export/BigqueryPollJobActionTest.java index 9844b1977..9ce3f3b10 100644 --- a/javatests/google/registry/export/BigqueryPollJobActionTest.java +++ b/javatests/google/registry/export/BigqueryPollJobActionTest.java @@ -18,6 +18,8 @@ import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assert_; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.logging.Level.INFO; @@ -55,7 +57,6 @@ import java.util.logging.Logger; 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; @@ -68,10 +69,6 @@ public class BigqueryPollJobActionTest { .withDatastore() .withTaskQueue() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private static final String PROJECT_ID = "project_id"; private static final String JOB_ID = "job_id"; private static final String CHAINED_QUEUE_NAME = UpdateSnapshotViewAction.QUEUE; @@ -192,15 +189,13 @@ public class BigqueryPollJobActionTest { public void testJobPending() throws Exception { when(bigqueryJobsGet.execute()).thenReturn( new Job().setStatus(new JobStatus().setState("PENDING"))); - thrown.expect(NotModifiedException.class); - action.run(); + assertThrows(NotModifiedException.class, () -> action.run()); } @Test public void testJobStatusUnreadable() throws Exception { when(bigqueryJobsGet.execute()).thenThrow(IOException.class); - thrown.expect(NotModifiedException.class); - action.run(); + assertThrows(NotModifiedException.class, () -> action.run()); } @Test @@ -208,8 +203,7 @@ public class BigqueryPollJobActionTest { when(bigqueryJobsGet.execute()).thenReturn( new Job().setStatus(new JobStatus().setState("DONE"))); action.payload = "payload".getBytes(UTF_8); - thrown.expect(BadRequestException.class); - thrown.expectMessage("Cannot deserialize task from payload"); - action.run(); + BadRequestException thrown = expectThrows(BadRequestException.class, () -> action.run()); + assertThat(thrown).hasMessageThat().contains("Cannot deserialize task from payload"); } } diff --git a/javatests/google/registry/export/CheckSnapshotActionTest.java b/javatests/google/registry/export/CheckSnapshotActionTest.java index 6568dc2ab..22fab01c0 100644 --- a/javatests/google/registry/export/CheckSnapshotActionTest.java +++ b/javatests/google/registry/export/CheckSnapshotActionTest.java @@ -17,6 +17,7 @@ package google.registry.export; import static com.google.common.truth.Truth.assertThat; import static google.registry.export.CheckSnapshotAction.CHECK_SNAPSHOT_KINDS_TO_LOAD_PARAM; import static google.registry.export.CheckSnapshotAction.CHECK_SNAPSHOT_NAME_PARAM; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static org.mockito.Mockito.mock; @@ -40,7 +41,6 @@ import org.joda.time.Duration; 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; @@ -53,8 +53,6 @@ public class CheckSnapshotActionTest { @Rule public final InjectRule inject = new InjectRule(); @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withTaskQueue().build(); - @Rule public final ExpectedException thrown = ExpectedException.none(); - private final DatastoreBackupService backupService = mock(DatastoreBackupService.class); private DatastoreBackupInfo backupInfo; @@ -124,9 +122,8 @@ public class CheckSnapshotActionTest { public void testPost_forPendingBackup_returnsNotModified() throws Exception { setPendingBackup(); - thrown.expect(NotModifiedException.class); - thrown.expectMessage("Datastore backup some_backup still pending"); - action.run(); + NotModifiedException thrown = expectThrows(NotModifiedException.class, () -> action.run()); + assertThat(thrown).hasMessageThat().contains("Datastore backup some_backup still pending"); } @Test @@ -141,11 +138,12 @@ public class CheckSnapshotActionTest { .plus(Duration.standardMinutes(3)) .plus(Duration.millis(1234))); - thrown.expect(NoContentException.class); - thrown.expectMessage("Datastore backup some_backup abandoned - " - + "not complete after 20 hours, 3 minutes and 1 second"); - - action.run(); + NoContentException thrown = expectThrows(NoContentException.class, () -> action.run()); + assertThat(thrown) + .hasMessageThat() + .contains( + "Datastore backup some_backup abandoned - " + + "not complete after 20 hours, 3 minutes and 1 second"); } @Test @@ -188,10 +186,8 @@ public class CheckSnapshotActionTest { when(backupService.findByName("some_backup")) .thenThrow(new IllegalArgumentException("No backup found")); - thrown.expect(BadRequestException.class); - thrown.expectMessage("Bad backup name some_backup: No backup found"); - - action.run(); + BadRequestException thrown = expectThrows(BadRequestException.class, () -> action.run()); + assertThat(thrown).hasMessageThat().contains("Bad backup name some_backup: No backup found"); } @Test @@ -220,9 +216,7 @@ public class CheckSnapshotActionTest { when(backupService.findByName("some_backup")) .thenThrow(new IllegalArgumentException("No backup found")); - thrown.expect(BadRequestException.class); - thrown.expectMessage("Bad backup name some_backup: No backup found"); - - action.run(); + BadRequestException thrown = expectThrows(BadRequestException.class, () -> action.run()); + assertThat(thrown).hasMessageThat().contains("Bad backup name some_backup: No backup found"); } } diff --git a/javatests/google/registry/export/DatastoreBackupInfoTest.java b/javatests/google/registry/export/DatastoreBackupInfoTest.java index 2d83a589f..d885cbcfa 100644 --- a/javatests/google/registry/export/DatastoreBackupInfoTest.java +++ b/javatests/google/registry/export/DatastoreBackupInfoTest.java @@ -17,6 +17,7 @@ package google.registry.export; import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; @@ -32,17 +33,12 @@ import org.joda.time.Duration; 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; /** Unit tests for {@link DatastoreBackupInfo}. */ @RunWith(JUnit4.class) public class DatastoreBackupInfoTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -107,28 +103,28 @@ public class DatastoreBackupInfoTest { @Test public void testFailure_missingName() throws Exception { backupEntity.removeProperty("name"); - thrown.expect(NullPointerException.class); - new DatastoreBackupInfo(persistEntity(backupEntity)); + assertThrows( + NullPointerException.class, () -> new DatastoreBackupInfo(persistEntity(backupEntity))); } @Test public void testFailure_missingKinds() throws Exception { backupEntity.removeProperty("kinds"); - thrown.expect(NullPointerException.class); - new DatastoreBackupInfo(persistEntity(backupEntity)); + assertThrows( + NullPointerException.class, () -> new DatastoreBackupInfo(persistEntity(backupEntity))); } @Test public void testFailure_missingStartTime() throws Exception { backupEntity.removeProperty("start_time"); - thrown.expect(NullPointerException.class); - new DatastoreBackupInfo(persistEntity(backupEntity)); + assertThrows( + NullPointerException.class, () -> new DatastoreBackupInfo(persistEntity(backupEntity))); } @Test public void testFailure_badGcsFilenameFormat() throws Exception { backupEntity.setProperty("gs_handle", new Text("foo")); - thrown.expect(IllegalArgumentException.class); - new DatastoreBackupInfo(persistEntity(backupEntity)); + assertThrows( + IllegalArgumentException.class, () -> new DatastoreBackupInfo(persistEntity(backupEntity))); } } diff --git a/javatests/google/registry/export/DatastoreBackupServiceTest.java b/javatests/google/registry/export/DatastoreBackupServiceTest.java index 667a0dd85..6bc4f0e22 100644 --- a/javatests/google/registry/export/DatastoreBackupServiceTest.java +++ b/javatests/google/registry/export/DatastoreBackupServiceTest.java @@ -17,6 +17,7 @@ package google.registry.export; import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService; import static com.google.common.collect.Iterables.transform; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -33,7 +34,6 @@ import org.joda.time.DateTime; 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; @@ -41,9 +41,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DatastoreBackupServiceTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -119,13 +116,11 @@ public class DatastoreBackupServiceTest { @Test public void testFailure_findByName_multipleMatchingBackups() throws Exception { - thrown.expect(IllegalArgumentException.class); - backupService.findByName("backupA"); + assertThrows(IllegalArgumentException.class, () -> backupService.findByName("backupA")); } @Test public void testFailure_findByName_noMatchingBackups() throws Exception { - thrown.expect(IllegalArgumentException.class); - backupService.findByName("backupX"); + assertThrows(IllegalArgumentException.class, () -> backupService.findByName("backupX")); } } diff --git a/javatests/google/registry/export/LoadSnapshotActionTest.java b/javatests/google/registry/export/LoadSnapshotActionTest.java index d4e5f24ab..626f4c2ff 100644 --- a/javatests/google/registry/export/LoadSnapshotActionTest.java +++ b/javatests/google/registry/export/LoadSnapshotActionTest.java @@ -22,6 +22,7 @@ import static google.registry.export.LoadSnapshotAction.LOAD_SNAPSHOT_KINDS_PARA import static google.registry.export.LoadSnapshotAction.PATH; import static google.registry.export.LoadSnapshotAction.QUEUE; import static google.registry.export.LoadSnapshotAction.enqueueLoadSnapshotTask; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static org.joda.time.DateTimeZone.UTC; import static org.mockito.Matchers.any; @@ -52,7 +53,6 @@ import org.joda.time.DateTime; 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; import org.mockito.ArgumentCaptor; @@ -65,10 +65,6 @@ public class LoadSnapshotActionTest { public final AppEngineRule appEngine = AppEngineRule.builder() .withTaskQueue() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final BigqueryFactory bigqueryFactory = mock(BigqueryFactory.class); private final Bigquery bigquery = mock(Bigquery.class); private final Bigquery.Jobs bigqueryJobs = mock(Bigquery.Jobs.class); @@ -186,16 +182,19 @@ public class LoadSnapshotActionTest { @Test public void testFailure_doPost_badGcsFilename() throws Exception { action.snapshotFile = "gs://bucket/snapshot"; - thrown.expect(BadRequestException.class); - thrown.expectMessage("Error calling load snapshot: backup info file extension missing"); - action.run(); + BadRequestException thrown = expectThrows(BadRequestException.class, () -> action.run()); + assertThat(thrown) + .hasMessageThat() + .contains("Error calling load snapshot: backup info file extension missing"); } @Test public void testFailure_doPost_bigqueryThrowsException() throws Exception { when(bigqueryJobsInsert.execute()).thenThrow(new IOException("The Internet has gone missing")); - thrown.expect(InternalServerErrorException.class); - thrown.expectMessage("Error loading snapshot: The Internet has gone missing"); - action.run(); + InternalServerErrorException thrown = + expectThrows(InternalServerErrorException.class, () -> action.run()); + assertThat(thrown) + .hasMessageThat() + .contains("Error loading snapshot: The Internet has gone missing"); } } diff --git a/javatests/google/registry/export/PublishDetailReportActionTest.java b/javatests/google/registry/export/PublishDetailReportActionTest.java index a84ca2c3a..72a9ed60f 100644 --- a/javatests/google/registry/export/PublishDetailReportActionTest.java +++ b/javatests/google/registry/export/PublishDetailReportActionTest.java @@ -21,6 +21,7 @@ import static google.registry.export.PublishDetailReportAction.GCS_FOLDER_PREFIX import static google.registry.export.PublishDetailReportAction.REGISTRAR_ID_PARAM; import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; @@ -45,17 +46,12 @@ import java.util.Map; 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; /** Unit tests for {@link PublishDetailReportAction}. */ @RunWith(JUnit4.class) public class PublishDetailReportActionTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() @@ -108,88 +104,120 @@ public class PublishDetailReportActionTest { @Test public void testFailure_noRegistrarParameter() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage(REGISTRAR_ID_PARAM); - action.handleJsonRequest(ImmutableMap.of( - GCS_BUCKET_PARAM, "mah-buckit", - GCS_FOLDER_PREFIX_PARAM, "some/folder/", - DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); + BadRequestException thrown = + expectThrows( + BadRequestException.class, + () -> + action.handleJsonRequest( + ImmutableMap.of( + GCS_BUCKET_PARAM, "mah-buckit", + GCS_FOLDER_PREFIX_PARAM, "some/folder/", + DETAIL_REPORT_NAME_PARAM, "detail_report.csv"))); + assertThat(thrown).hasMessageThat().contains(REGISTRAR_ID_PARAM); } @Test public void testFailure_noGcsBucketParameter() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage(GCS_BUCKET_PARAM); - action.handleJsonRequest(ImmutableMap.of( - REGISTRAR_ID_PARAM, "TheRegistrar", - GCS_FOLDER_PREFIX_PARAM, "some/folder/", - DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); + BadRequestException thrown = + expectThrows( + BadRequestException.class, + () -> + action.handleJsonRequest( + ImmutableMap.of( + REGISTRAR_ID_PARAM, "TheRegistrar", + GCS_FOLDER_PREFIX_PARAM, "some/folder/", + DETAIL_REPORT_NAME_PARAM, "detail_report.csv"))); + assertThat(thrown).hasMessageThat().contains(GCS_BUCKET_PARAM); } @Test public void testFailure_noGcsFolderPrefixParameter() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage(GCS_FOLDER_PREFIX_PARAM); - action.handleJsonRequest(ImmutableMap.of( - REGISTRAR_ID_PARAM, "TheRegistrar", - GCS_BUCKET_PARAM, "mah-buckit", - DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); + BadRequestException thrown = + expectThrows( + BadRequestException.class, + () -> + action.handleJsonRequest( + ImmutableMap.of( + REGISTRAR_ID_PARAM, "TheRegistrar", + GCS_BUCKET_PARAM, "mah-buckit", + DETAIL_REPORT_NAME_PARAM, "detail_report.csv"))); + assertThat(thrown).hasMessageThat().contains(GCS_FOLDER_PREFIX_PARAM); } @Test public void testFailure_noReportNameParameter() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage(DETAIL_REPORT_NAME_PARAM); - action.handleJsonRequest(ImmutableMap.of( - REGISTRAR_ID_PARAM, "TheRegistrar", - GCS_BUCKET_PARAM, "mah-buckit", - GCS_FOLDER_PREFIX_PARAM, "some/folder/")); + BadRequestException thrown = + expectThrows( + BadRequestException.class, + () -> + action.handleJsonRequest( + ImmutableMap.of( + REGISTRAR_ID_PARAM, "TheRegistrar", + GCS_BUCKET_PARAM, "mah-buckit", + GCS_FOLDER_PREFIX_PARAM, "some/folder/"))); + assertThat(thrown).hasMessageThat().contains(DETAIL_REPORT_NAME_PARAM); } @Test public void testFailure_registrarNotFound() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage("FakeRegistrar"); - action.handleJsonRequest(ImmutableMap.of( - REGISTRAR_ID_PARAM, "FakeRegistrar", - GCS_BUCKET_PARAM, "mah-buckit", - GCS_FOLDER_PREFIX_PARAM, "some/folder/", - DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); + BadRequestException thrown = + expectThrows( + BadRequestException.class, + () -> + action.handleJsonRequest( + ImmutableMap.of( + REGISTRAR_ID_PARAM, "FakeRegistrar", + GCS_BUCKET_PARAM, "mah-buckit", + GCS_FOLDER_PREFIX_PARAM, "some/folder/", + DETAIL_REPORT_NAME_PARAM, "detail_report.csv"))); + assertThat(thrown).hasMessageThat().contains("FakeRegistrar"); } @Test public void testFailure_registrarHasNoDriveFolder() throws Exception { persistResource( loadRegistrar("TheRegistrar").asBuilder().setDriveFolderId(null).build()); - thrown.expect(BadRequestException.class); - thrown.expectMessage("drive folder"); - action.handleJsonRequest(ImmutableMap.of( - REGISTRAR_ID_PARAM, "TheRegistrar", - GCS_BUCKET_PARAM, "mah-buckit", - GCS_FOLDER_PREFIX_PARAM, "some/folder/", - DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); + BadRequestException thrown = + expectThrows( + BadRequestException.class, + () -> + action.handleJsonRequest( + ImmutableMap.of( + REGISTRAR_ID_PARAM, "TheRegistrar", + GCS_BUCKET_PARAM, "mah-buckit", + GCS_FOLDER_PREFIX_PARAM, "some/folder/", + DETAIL_REPORT_NAME_PARAM, "detail_report.csv"))); + assertThat(thrown).hasMessageThat().contains("drive folder"); } @Test public void testFailure_gcsBucketNotFound() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage("fake-buckit"); - action.handleJsonRequest(ImmutableMap.of( - REGISTRAR_ID_PARAM, "TheRegistrar", - GCS_BUCKET_PARAM, "fake-buckit", - GCS_FOLDER_PREFIX_PARAM, "some/folder/", - DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); + BadRequestException thrown = + expectThrows( + BadRequestException.class, + () -> + action.handleJsonRequest( + ImmutableMap.of( + REGISTRAR_ID_PARAM, "TheRegistrar", + GCS_BUCKET_PARAM, "fake-buckit", + GCS_FOLDER_PREFIX_PARAM, "some/folder/", + DETAIL_REPORT_NAME_PARAM, "detail_report.csv"))); + assertThat(thrown).hasMessageThat().contains("fake-buckit"); } @Test public void testFailure_gcsFileNotFound() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage("some/folder/fake_file.csv"); - action.handleJsonRequest(ImmutableMap.of( - REGISTRAR_ID_PARAM, "TheRegistrar", - GCS_BUCKET_PARAM, "mah-buckit", - GCS_FOLDER_PREFIX_PARAM, "some/folder/", - DETAIL_REPORT_NAME_PARAM, "fake_file.csv")); + BadRequestException thrown = + expectThrows( + BadRequestException.class, + () -> + action.handleJsonRequest( + ImmutableMap.of( + REGISTRAR_ID_PARAM, "TheRegistrar", + GCS_BUCKET_PARAM, "mah-buckit", + GCS_FOLDER_PREFIX_PARAM, "some/folder/", + DETAIL_REPORT_NAME_PARAM, "fake_file.csv"))); + assertThat(thrown).hasMessageThat().contains("some/folder/fake_file.csv"); } @Test @@ -197,12 +225,16 @@ public class PublishDetailReportActionTest { when(driveConnection.createFile( anyString(), any(MediaType.class), anyString(), any(byte[].class))) .thenThrow(new IOException("Drive is down")); - thrown.expect(InternalServerErrorException.class); - thrown.expectMessage("Drive is down"); - action.handleJsonRequest(ImmutableMap.of( - REGISTRAR_ID_PARAM, "TheRegistrar", - GCS_BUCKET_PARAM, "mah-buckit", - GCS_FOLDER_PREFIX_PARAM, "some/folder/", - DETAIL_REPORT_NAME_PARAM, "detail_report.csv")); + InternalServerErrorException thrown = + expectThrows( + InternalServerErrorException.class, + () -> + action.handleJsonRequest( + ImmutableMap.of( + REGISTRAR_ID_PARAM, "TheRegistrar", + GCS_BUCKET_PARAM, "mah-buckit", + GCS_FOLDER_PREFIX_PARAM, "some/folder/", + DETAIL_REPORT_NAME_PARAM, "detail_report.csv"))); + assertThat(thrown).hasMessageThat().contains("Drive is down"); } } diff --git a/javatests/google/registry/export/SyncGroupMembersActionTest.java b/javatests/google/registry/export/SyncGroupMembersActionTest.java index 9050e9695..a0f3c6c1c 100644 --- a/javatests/google/registry/export/SyncGroupMembersActionTest.java +++ b/javatests/google/registry/export/SyncGroupMembersActionTest.java @@ -47,7 +47,6 @@ import google.registry.util.Retrier; import java.io.IOException; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -65,9 +64,6 @@ public class SyncGroupMembersActionTest { .withDatastore() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); diff --git a/javatests/google/registry/export/UpdateSnapshotViewActionTest.java b/javatests/google/registry/export/UpdateSnapshotViewActionTest.java index cb6262da4..5b308953e 100644 --- a/javatests/google/registry/export/UpdateSnapshotViewActionTest.java +++ b/javatests/google/registry/export/UpdateSnapshotViewActionTest.java @@ -21,6 +21,7 @@ import static google.registry.export.UpdateSnapshotViewAction.UPDATE_SNAPSHOT_DA import static google.registry.export.UpdateSnapshotViewAction.UPDATE_SNAPSHOT_KIND_PARAM; import static google.registry.export.UpdateSnapshotViewAction.UPDATE_SNAPSHOT_TABLE_ID_PARAM; import static google.registry.export.UpdateSnapshotViewAction.createViewUpdateTask; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; @@ -41,7 +42,6 @@ import java.io.IOException; 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; import org.mockito.ArgumentCaptor; @@ -55,10 +55,6 @@ public class UpdateSnapshotViewActionTest { public final AppEngineRule appEngine = AppEngineRule.builder() .withTaskQueue() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final BigqueryFactory bigqueryFactory = mock(BigqueryFactory.class); private final Bigquery bigquery = mock(Bigquery.class); private final Bigquery.Datasets bigqueryDatasets = mock(Bigquery.Datasets.class); @@ -127,8 +123,8 @@ public class UpdateSnapshotViewActionTest { public void testFailure_bigqueryConnectionThrowsError() throws Exception { when(bigqueryTables.update(anyString(), anyString(), anyString(), any(Table.class))) .thenThrow(new IOException("I'm sorry Dave, I can't let you do that")); - thrown.expect(InternalServerErrorException.class); - thrown.expectMessage("Error in update snapshot view action"); - action.run(); + InternalServerErrorException thrown = + expectThrows(InternalServerErrorException.class, () -> action.run()); + assertThat(thrown).hasMessageThat().contains("Error in update snapshot view action"); } } diff --git a/javatests/google/registry/groups/DirectoryGroupsConnectionTest.java b/javatests/google/registry/groups/DirectoryGroupsConnectionTest.java index 577acc01c..515ba4647 100644 --- a/javatests/google/registry/groups/DirectoryGroupsConnectionTest.java +++ b/javatests/google/registry/groups/DirectoryGroupsConnectionTest.java @@ -16,6 +16,8 @@ package google.registry.groups; import static com.google.common.truth.Truth.assertThat; import static google.registry.groups.DirectoryGroupsConnection.getDefaultGroupPermissions; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static javax.servlet.http.HttpServletResponse.SC_CONFLICT; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; @@ -50,9 +52,7 @@ import google.registry.groups.GroupsConnection.Role; import java.io.IOException; import java.util.Set; 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; @@ -61,10 +61,6 @@ import org.junit.runners.JUnit4; */ @RunWith(JUnit4.class) public class DirectoryGroupsConnectionTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final Directory directory = mock(Directory.class); private final Groupssettings groupsSettings = mock(Groupssettings.class); private final Directory.Members members = mock(Directory.Members.class); @@ -118,18 +114,22 @@ public class DirectoryGroupsConnectionTest { public void test_addMemberToGroup_handlesExceptionThrownByDirectoryService() throws Exception { when(membersInsert.execute()).thenThrow( makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server.")); - thrown.expect(GoogleJsonResponseException.class); - runAddMemberTest(); + assertThrows(GoogleJsonResponseException.class, () -> runAddMemberTest()); } @Test public void test_addMemberToGroup_handlesMemberKeyNotFoundException() throws Exception { when(membersInsert.execute()).thenThrow( makeResponseException(SC_NOT_FOUND, "Resource Not Found: memberKey")); - thrown.expect(RuntimeException.class); - thrown.expectMessage("Adding member jim@example.com to group spam@example.com " - + "failed because the member wasn't found."); - connection.addMemberToGroup("spam@example.com", "jim@example.com", Role.MEMBER); + RuntimeException thrown = + expectThrows( + RuntimeException.class, + () -> connection.addMemberToGroup("spam@example.com", "jim@example.com", Role.MEMBER)); + assertThat(thrown) + .hasMessageThat() + .contains( + "Adding member jim@example.com to group spam@example.com " + + "failed because the member wasn't found."); } @Test @@ -178,8 +178,7 @@ public class DirectoryGroupsConnectionTest { public void test_createGroup_handlesExceptionThrownByDirectoryService() throws Exception { when(groupsInsert.execute()).thenThrow( makeResponseException(SC_INTERNAL_SERVER_ERROR, "Could not contact Directory server.")); - thrown.expect(GoogleJsonResponseException.class); - runCreateGroupTest(); + assertThrows(GoogleJsonResponseException.class, () -> runCreateGroupTest()); } @Test diff --git a/javatests/google/registry/mapreduce/inputs/ChildEntityInputTest.java b/javatests/google/registry/mapreduce/inputs/ChildEntityInputTest.java index 053cffde8..26870c0eb 100644 --- a/javatests/google/registry/mapreduce/inputs/ChildEntityInputTest.java +++ b/javatests/google/registry/mapreduce/inputs/ChildEntityInputTest.java @@ -24,6 +24,7 @@ import static google.registry.testing.DatastoreHelper.newDomainResource; import static google.registry.testing.DatastoreHelper.persistEppResourceInFirstBucket; import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistSimpleResource; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.util.DateTimeUtils.END_OF_TIME; import static org.joda.money.CurrencyUnit.USD; @@ -51,7 +52,6 @@ import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -63,10 +63,6 @@ public class ChildEntityInputTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - DomainResource domainA; DomainResource domainB; HistoryEntry domainHistoryEntryA; @@ -173,9 +169,12 @@ public class ChildEntityInputTest { reader = serializeAndDeserialize(reader); reader.beginSlice(); if (i == 7) { - thrown.expect(NoSuchElementException.class); + // This final readerCopy is needed for the assertThrows lambda. + final InputReader readerCopy = reader; + assertThrows(NoSuchElementException.class, () -> seen.add(readerCopy.next())); + } else { + seen.add(reader.next()); } - seen.add(reader.next()); } assertThat(seen).containsExactly( domainHistoryEntryA, @@ -300,7 +299,6 @@ public class ChildEntityInputTest { assertThat(seen).containsExactlyElementsIn(historyEntries); } - @Test public void testSuccess_childEntityReader_survivesAcrossSerialization() throws Exception { setupResources(); @@ -315,13 +313,12 @@ public class ChildEntityInputTest { seen.add(reader.next()); seen.add(reader.next()); reader.endSlice(); - reader = serializeAndDeserialize(reader); - reader.beginSlice(); - seen.add(reader.next()); - seen.add(reader.next()); - assertThat(seen).containsExactly( - domainHistoryEntryA, contactHistoryEntry, oneTimeA, recurringA); - thrown.expect(NoSuchElementException.class); - reader.next(); + InputReader deserializedReader = serializeAndDeserialize(reader); + deserializedReader.beginSlice(); + seen.add(deserializedReader.next()); + seen.add(deserializedReader.next()); + assertThat(seen) + .containsExactly(domainHistoryEntryA, contactHistoryEntry, oneTimeA, recurringA); + assertThrows(NoSuchElementException.class, deserializedReader::next); } } diff --git a/javatests/google/registry/mapreduce/inputs/EppResourceInputsTest.java b/javatests/google/registry/mapreduce/inputs/EppResourceInputsTest.java index d32598bc4..be9f4800b 100644 --- a/javatests/google/registry/mapreduce/inputs/EppResourceInputsTest.java +++ b/javatests/google/registry/mapreduce/inputs/EppResourceInputsTest.java @@ -28,6 +28,8 @@ import static google.registry.testing.DatastoreHelper.persistActiveContact; import static google.registry.testing.DatastoreHelper.persistEppResourceInFirstBucket; import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistSimpleResource; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.appengine.tools.mapreduce.InputReader; import com.googlecode.objectify.Key; @@ -48,7 +50,6 @@ import java.util.NoSuchElementException; import java.util.Set; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -60,10 +61,6 @@ public class EppResourceInputsTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @SuppressWarnings("unchecked") private T serializeAndDeserialize(T obj) throws Exception { try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); @@ -83,16 +80,18 @@ public class EppResourceInputsTest { @Test public void testFailure_keyInputType_polymorphicSubclass() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("non-polymorphic"); - createKeyInput(DomainResource.class); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> createKeyInput(DomainResource.class)); + assertThat(thrown).hasMessageThat().contains("non-polymorphic"); } @Test public void testFailure_keyInputType_noInheritanceBetweenTypes_eppResource() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("inheritance"); - createKeyInput(EppResource.class, DomainBase.class); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> createKeyInput(EppResource.class, DomainBase.class)); + assertThat(thrown).hasMessageThat().contains("inheritance"); } @Test @@ -104,16 +103,20 @@ public class EppResourceInputsTest { @Test public void testFailure_entityInputType_noInheritanceBetweenTypes_eppResource() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("inheritance"); - createEntityInput(EppResource.class, DomainResource.class); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> createEntityInput(EppResource.class, DomainResource.class)); + assertThat(thrown).hasMessageThat().contains("inheritance"); } @Test public void testFailure_entityInputType_noInheritanceBetweenTypes_subclasses() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("inheritance"); - createEntityInput(DomainBase.class, DomainResource.class); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> createEntityInput(DomainBase.class, DomainResource.class)); + assertThat(thrown).hasMessageThat().contains("inheritance"); } @Test @@ -191,8 +194,7 @@ public class EppResourceInputsTest { seen.add(reader.next()); assertThat(reader.getProgress()).isWithin(EPSILON).of(1); assertThat(seen).containsExactly(Key.create(domainA), Key.create(domainB)); - thrown.expect(NoSuchElementException.class); - reader.next(); + assertThrows(NoSuchElementException.class, reader::next); } @Test @@ -211,16 +213,15 @@ public class EppResourceInputsTest { seen.add(reader.next()); assertThat(reader.getProgress()).isWithin(EPSILON).of(0.5); reader.endSlice(); - reader = serializeAndDeserialize(reader); - reader.beginSlice(); - assertThat(reader.getProgress()).isWithin(EPSILON).of(0.5); - seen.add(reader.next()); - assertThat(reader.getProgress()).isWithin(EPSILON).of(1); - reader.endSlice(); - reader.endShard(); + InputReader deserializedReader = serializeAndDeserialize(reader); + deserializedReader.beginSlice(); + assertThat(deserializedReader.getProgress()).isWithin(EPSILON).of(0.5); + seen.add(deserializedReader.next()); + assertThat(deserializedReader.getProgress()).isWithin(EPSILON).of(1); + deserializedReader.endSlice(); + deserializedReader.endShard(); assertThat(seen).containsExactly(domainA, domainB); - thrown.expect(NoSuchElementException.class); - reader.next(); + assertThrows(NoSuchElementException.class, deserializedReader::next); } @Test @@ -238,8 +239,7 @@ public class EppResourceInputsTest { seen.add(reader.next()); assertThat(reader.getProgress()).isWithin(EPSILON).of(1.0); assertThat(seen).containsExactly(domain, application); - thrown.expect(NoSuchElementException.class); - reader.next(); + assertThrows(NoSuchElementException.class, reader::next); } @Test @@ -256,8 +256,7 @@ public class EppResourceInputsTest { // We can't reliably assert getProgress() here, since it counts before the postfilter that weeds // out polymorphic mismatches, and so depending on whether the domain or the application was // seen first it will be 0.5 or 1.0. However, there should be nothing left when we call next(). - thrown.expect(NoSuchElementException.class); - reader.next(); + assertThrows(NoSuchElementException.class, reader::next); } @Test @@ -278,8 +277,7 @@ public class EppResourceInputsTest { seen.add(reader.next()); assertThat(reader.getProgress()).isWithin(EPSILON).of(1.0); assertThat(seen).containsExactly(domain, host); - thrown.expect(NoSuchElementException.class); - reader.next(); + assertThrows(NoSuchElementException.class, reader::next); } @Test @@ -305,7 +303,6 @@ public class EppResourceInputsTest { seen.add(reader.next()); assertThat(reader.getProgress()).isWithin(EPSILON).of(1.0); assertThat(seen).containsExactly(domain, host, application, contact); - thrown.expect(NoSuchElementException.class); - reader.next(); + assertThrows(NoSuchElementException.class, reader::next); } } diff --git a/javatests/google/registry/model/EppResourceUtilsTest.java b/javatests/google/registry/model/EppResourceUtilsTest.java index 7350efe2d..102069b1d 100644 --- a/javatests/google/registry/model/EppResourceUtilsTest.java +++ b/javatests/google/registry/model/EppResourceUtilsTest.java @@ -33,7 +33,6 @@ import org.joda.time.Duration; 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; @@ -47,9 +46,6 @@ public class EppResourceUtilsTest { .withTaskQueue() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); diff --git a/javatests/google/registry/model/ModelUtilsTest.java b/javatests/google/registry/model/ModelUtilsTest.java index 6745eefd1..75be7d22f 100644 --- a/javatests/google/registry/model/ModelUtilsTest.java +++ b/javatests/google/registry/model/ModelUtilsTest.java @@ -24,7 +24,6 @@ import java.util.Map; 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; @@ -32,9 +31,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ModelUtilsTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public AppEngineRule appEngineRule = new AppEngineRule.Builder().build(); diff --git a/javatests/google/registry/model/billing/BillingEventTest.java b/javatests/google/registry/model/billing/BillingEventTest.java index 22988fd26..2bd79f56c 100644 --- a/javatests/google/registry/model/billing/BillingEventTest.java +++ b/javatests/google/registry/model/billing/BillingEventTest.java @@ -19,6 +19,7 @@ import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistActiveDomain; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.DateTimeUtils.END_OF_TIME; import static org.joda.money.CurrencyUnit.USD; import static org.joda.time.DateTimeZone.UTC; @@ -35,16 +36,10 @@ import google.registry.model.reporting.HistoryEntry; import org.joda.money.Money; import org.joda.time.DateTime; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link BillingEvent}. */ public class BillingEventTest extends EntityTestCase { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final DateTime now = DateTime.now(UTC); HistoryEntry historyEntry; @@ -182,44 +177,64 @@ public class BillingEventTest extends EntityTestCase { @Test public void testFailure_syntheticFlagWithoutCreationTime() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "Synthetic creation time must be set if and only if the SYNTHETIC flag is set."); - oneTime.asBuilder() - .setFlags(ImmutableSet.of(BillingEvent.Flag.SYNTHETIC)) - .setCancellationMatchingBillingEvent(Key.create(recurring)) - .build(); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> + oneTime + .asBuilder() + .setFlags(ImmutableSet.of(BillingEvent.Flag.SYNTHETIC)) + .setCancellationMatchingBillingEvent(Key.create(recurring)) + .build()); + assertThat(thrown) + .hasMessageThat() + .contains("Synthetic creation time must be set if and only if the SYNTHETIC flag is set."); } @Test public void testFailure_syntheticCreationTimeWithoutFlag() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "Synthetic creation time must be set if and only if the SYNTHETIC flag is set"); - oneTime.asBuilder() - .setSyntheticCreationTime(now.plusDays(10)) - .build(); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> oneTime.asBuilder().setSyntheticCreationTime(now.plusDays(10)).build()); + assertThat(thrown) + .hasMessageThat() + .contains("Synthetic creation time must be set if and only if the SYNTHETIC flag is set"); } @Test public void testFailure_syntheticFlagWithoutCancellationMatchingKey() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "Cancellation matching billing event must be set if and only if the SYNTHETIC flag is set"); - oneTime.asBuilder() - .setFlags(ImmutableSet.of(BillingEvent.Flag.SYNTHETIC)) - .setSyntheticCreationTime(END_OF_TIME) - .build(); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> + oneTime + .asBuilder() + .setFlags(ImmutableSet.of(BillingEvent.Flag.SYNTHETIC)) + .setSyntheticCreationTime(END_OF_TIME) + .build()); + assertThat(thrown) + .hasMessageThat() + .contains( + "Cancellation matching billing event must be set " + + "if and only if the SYNTHETIC flag is set"); } @Test public void testFailure_cancellationMatchingKeyWithoutFlag() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "Cancellation matching billing event must be set if and only if the SYNTHETIC flag is set"); - oneTime.asBuilder() - .setCancellationMatchingBillingEvent(Key.create(recurring)) - .build(); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> + oneTime + .asBuilder() + .setCancellationMatchingBillingEvent(Key.create(recurring)) + .build()); + assertThat(thrown) + .hasMessageThat() + .contains( + "Cancellation matching billing event must be set " + + "if and only if the SYNTHETIC flag is set"); } @Test @@ -250,32 +265,44 @@ public class BillingEventTest extends EntityTestCase { @Test public void testFailure_cancellation_forGracePeriodWithoutBillingEvent() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("grace period without billing event"); - BillingEvent.Cancellation.forGracePeriod( - GracePeriod.createWithoutBillingEvent( - GracePeriodStatus.REDEMPTION, - now.plusDays(1), - "a registrar"), - historyEntry, - "foo.tld"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + BillingEvent.Cancellation.forGracePeriod( + GracePeriod.createWithoutBillingEvent( + GracePeriodStatus.REDEMPTION, now.plusDays(1), "a registrar"), + historyEntry, + "foo.tld")); + assertThat(thrown).hasMessageThat().contains("grace period without billing event"); } @Test public void testFailure_cancellationWithNoBillingEvent() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("exactly one billing event"); - cancellationOneTime.asBuilder().setOneTimeEventKey(null).setRecurringEventKey(null).build(); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> + cancellationOneTime + .asBuilder() + .setOneTimeEventKey(null) + .setRecurringEventKey(null) + .build()); + assertThat(thrown).hasMessageThat().contains("exactly one billing event"); } @Test public void testFailure_cancellationWithBothBillingEvents() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("exactly one billing event"); - cancellationOneTime.asBuilder() - .setOneTimeEventKey(Key.create(oneTime)) - .setRecurringEventKey(Key.create(recurring)) - .build(); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> + cancellationOneTime + .asBuilder() + .setOneTimeEventKey(Key.create(oneTime)) + .setRecurringEventKey(Key.create(recurring)) + .build()); + assertThat(thrown).hasMessageThat().contains("exactly one billing event"); } @Test diff --git a/javatests/google/registry/model/billing/RegistrarBillingEntryTest.java b/javatests/google/registry/model/billing/RegistrarBillingEntryTest.java index 84d0ddb13..9e48959e6 100644 --- a/javatests/google/registry/model/billing/RegistrarBillingEntryTest.java +++ b/javatests/google/registry/model/billing/RegistrarBillingEntryTest.java @@ -17,6 +17,8 @@ package google.registry.model.billing; import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.joda.money.CurrencyUnit.USD; import com.google.common.collect.ImmutableMap; @@ -25,9 +27,7 @@ import google.registry.model.EntityTestCase; import org.joda.money.CurrencyMismatchException; import org.joda.money.Money; import org.joda.time.DateTime; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -35,9 +35,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class RegistrarBillingEntryTest extends EntityTestCase { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testIndexing() throws Exception { verifyIndexing( @@ -100,77 +97,88 @@ public final class RegistrarBillingEntryTest extends EntityTestCase { @Test public void testBadTimeOrdering_causesError() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Created timestamp not after previous"); - new RegistrarBillingEntry.Builder() - .setPrevious( - new RegistrarBillingEntry.Builder() - .setPrevious(null) - .setParent(loadRegistrar("NewRegistrar")) - .setCreated(DateTime.parse("1984-12-18TZ")) - .setDescription("USD Invoice for December") - .setAmount(Money.parse("USD 10.00")) - .build()) - .setParent(loadRegistrar("NewRegistrar")) - .setCreated(DateTime.parse("1984-12-17TZ")) - .setTransactionId("goblin") - .setDescription("USD Invoice for August") - .setAmount(Money.parse("USD 3.50")) - .build(); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> + new RegistrarBillingEntry.Builder() + .setPrevious( + new RegistrarBillingEntry.Builder() + .setPrevious(null) + .setParent(loadRegistrar("NewRegistrar")) + .setCreated(DateTime.parse("1984-12-18TZ")) + .setDescription("USD Invoice for December") + .setAmount(Money.parse("USD 10.00")) + .build()) + .setParent(loadRegistrar("NewRegistrar")) + .setCreated(DateTime.parse("1984-12-17TZ")) + .setTransactionId("goblin") + .setDescription("USD Invoice for August") + .setAmount(Money.parse("USD 3.50")) + .build()); + assertThat(thrown).hasMessageThat().contains("Created timestamp not after previous"); } @Test public void testRegistrarMismatch_causesError() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Parent not same as previous"); - new RegistrarBillingEntry.Builder() - .setPrevious( - new RegistrarBillingEntry.Builder() - .setPrevious(null) - .setParent(loadRegistrar("NewRegistrar")) - .setCreated(DateTime.parse("1984-12-18TZ")) - .setDescription("USD Invoice for December") - .setAmount(Money.parse("USD 10.00")) - .build()) - .setParent(loadRegistrar("TheRegistrar")) - .setCreated(DateTime.parse("1984-12-17TZ")) - .setTransactionId("goblin") - .setDescription("USD Invoice for August") - .setAmount(Money.parse("USD 3.50")) - .build(); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> + new RegistrarBillingEntry.Builder() + .setPrevious( + new RegistrarBillingEntry.Builder() + .setPrevious(null) + .setParent(loadRegistrar("NewRegistrar")) + .setCreated(DateTime.parse("1984-12-18TZ")) + .setDescription("USD Invoice for December") + .setAmount(Money.parse("USD 10.00")) + .build()) + .setParent(loadRegistrar("TheRegistrar")) + .setCreated(DateTime.parse("1984-12-17TZ")) + .setTransactionId("goblin") + .setDescription("USD Invoice for August") + .setAmount(Money.parse("USD 3.50")) + .build()); + assertThat(thrown).hasMessageThat().contains("Parent not same as previous"); } @Test public void testCurrencyMismatch_causesError() throws Exception { - thrown.expect(CurrencyMismatchException.class); - new RegistrarBillingEntry.Builder() - .setPrevious( + assertThrows( + CurrencyMismatchException.class, + () -> new RegistrarBillingEntry.Builder() - .setPrevious(null) + .setPrevious( + new RegistrarBillingEntry.Builder() + .setPrevious(null) + .setParent(loadRegistrar("NewRegistrar")) + .setCreated(DateTime.parse("1984-12-18TZ")) + .setDescription("USD Invoice for December") + .setAmount(Money.parse("USD 10.00")) + .build()) .setParent(loadRegistrar("NewRegistrar")) - .setCreated(DateTime.parse("1984-12-18TZ")) - .setDescription("USD Invoice for December") - .setAmount(Money.parse("USD 10.00")) - .build()) - .setParent(loadRegistrar("NewRegistrar")) - .setCreated(DateTime.parse("1984-12-17TZ")) - .setTransactionId("goblin") - .setDescription("JPY Invoice for August") - .setAmount(Money.parse("JPY 350")) - .build(); + .setCreated(DateTime.parse("1984-12-17TZ")) + .setTransactionId("goblin") + .setDescription("JPY Invoice for August") + .setAmount(Money.parse("JPY 350")) + .build()); } @Test public void testZeroAmount_causesError() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Amount can't be zero"); - new RegistrarBillingEntry.Builder() - .setPrevious(null) - .setParent(loadRegistrar("NewRegistrar")) - .setCreated(DateTime.parse("1984-12-18TZ")) - .setDescription("USD Invoice for December") - .setAmount(Money.zero(USD)) - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + new RegistrarBillingEntry.Builder() + .setPrevious(null) + .setParent(loadRegistrar("NewRegistrar")) + .setCreated(DateTime.parse("1984-12-18TZ")) + .setDescription("USD Invoice for December") + .setAmount(Money.zero(USD)) + .build()); + assertThat(thrown).hasMessageThat().contains("Amount can't be zero"); } @Test diff --git a/javatests/google/registry/model/billing/RegistrarCreditBalanceTest.java b/javatests/google/registry/model/billing/RegistrarCreditBalanceTest.java index 8f87b4d76..65d277908 100644 --- a/javatests/google/registry/model/billing/RegistrarCreditBalanceTest.java +++ b/javatests/google/registry/model/billing/RegistrarCreditBalanceTest.java @@ -20,6 +20,7 @@ import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME; @@ -33,16 +34,10 @@ import org.joda.money.CurrencyUnit; import org.joda.money.Money; import org.joda.time.DateTime; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link RegistrarCreditBalance}. */ public class RegistrarCreditBalanceTest extends EntityTestCase { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - private DateTime then = clock.nowUtc().plusDays(1); private Registrar theRegistrar; @@ -100,19 +95,21 @@ public class RegistrarCreditBalanceTest extends EntityTestCase { @Test public void testFailure_balanceNotInCreditCurrency() throws Exception { - thrown.expect(IllegalStateException.class); - balance.asBuilder() - .setAmount(Money.parse("JPY 1")) - .build(); + assertThrows( + IllegalStateException.class, + () -> balance.asBuilder().setAmount(Money.parse("JPY 1")).build()); } @Test public void testFailure_balanceNotInCreditCurrencyWithUnpersistedCredit() throws Exception { - thrown.expect(IllegalStateException.class); - balance.asBuilder() - .setParent(unpersistedCredit) - .setAmount(Money.parse("JPY 1")) - .build(); + assertThrows( + IllegalStateException.class, + () -> + balance + .asBuilder() + .setParent(unpersistedCredit) + .setAmount(Money.parse("JPY 1")) + .build()); } @Test diff --git a/javatests/google/registry/model/billing/RegistrarCreditTest.java b/javatests/google/registry/model/billing/RegistrarCreditTest.java index 3a0ea0b1f..72c395750 100644 --- a/javatests/google/registry/model/billing/RegistrarCreditTest.java +++ b/javatests/google/registry/model/billing/RegistrarCreditTest.java @@ -19,6 +19,7 @@ import static google.registry.model.common.EntityGroupRoot.getCrossTldKey; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.joda.money.CurrencyUnit.JPY; import static org.joda.money.CurrencyUnit.USD; @@ -28,16 +29,10 @@ import google.registry.model.registrar.Registrar; import google.registry.model.registry.Registry; import org.joda.money.CurrencyUnit; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link RegistrarCredit}. */ public class RegistrarCreditTest extends EntityTestCase { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - private RegistrarCredit auctionCredit; private RegistrarCredit promoCredit; @@ -81,23 +76,28 @@ public class RegistrarCreditTest extends EntityTestCase { @Test public void testFailure_missingTld() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("tld"); - promoCredit.asBuilder().setTld(null).build(); + NullPointerException thrown = + expectThrows( + NullPointerException.class, () -> promoCredit.asBuilder().setTld(null).build()); + assertThat(thrown).hasMessageThat().contains("tld"); } @Test public void testFailure_NonexistentTld() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("example"); - promoCredit.asBuilder().setTld("example").build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> promoCredit.asBuilder().setTld("example").build()); + assertThat(thrown).hasMessageThat().contains("example"); } @Test public void testFailure_CurrencyDoesNotMatchTldCurrency() throws Exception { assertThat(Registry.get("tld").getCurrency()).isEqualTo(USD); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("currency"); - promoCredit.asBuilder().setTld("tld").setCurrency(JPY).build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> promoCredit.asBuilder().setTld("tld").setCurrency(JPY).build()); + assertThat(thrown).hasMessageThat().contains("currency"); } } diff --git a/javatests/google/registry/model/common/CursorTest.java b/javatests/google/registry/model/common/CursorTest.java index 8ffe96bd5..710b4e440 100644 --- a/javatests/google/registry/model/common/CursorTest.java +++ b/javatests/google/registry/model/common/CursorTest.java @@ -21,21 +21,17 @@ import static google.registry.model.common.Cursor.CursorType.RECURRING_BILLING; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistActiveDomain; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.DateTimeUtils.START_OF_TIME; import google.registry.model.EntityTestCase; import google.registry.model.domain.DomainResource; import google.registry.model.registry.Registry; import org.joda.time.DateTime; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link Cursor}. */ public class CursorTest extends EntityTestCase { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Test public void testSuccess_persistScopedCursor() { createTld("tld"); @@ -74,54 +70,72 @@ public class CursorTest extends EntityTestCase { clock.advanceOneMilli(); final DateTime time = DateTime.parse("2012-07-12T03:30:00.000Z"); final DomainResource domain = persistActiveDomain("notaregistry.tld"); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Class required for cursor does not match scope class"); - ofy().transact(() -> ofy().save().entity(Cursor.create(RDE_UPLOAD, time, domain))); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + ofy().transact(() -> ofy().save().entity(Cursor.create(RDE_UPLOAD, time, domain)))); + assertThat(thrown) + .hasMessageThat() + .contains("Class required for cursor does not match scope class"); } @Test public void testFailure_invalidScopeOnKeyCreate() throws Exception { createTld("tld"); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Class required for cursor does not match scope class"); - Cursor.createKey(RDE_UPLOAD, persistActiveDomain("notaregistry.tld")); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> Cursor.createKey(RDE_UPLOAD, persistActiveDomain("notaregistry.tld"))); + assertThat(thrown) + .hasMessageThat() + .contains("Class required for cursor does not match scope class"); } @Test public void testFailure_createGlobalKeyForScopedCursorType() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Cursor type is not a global cursor"); - Cursor.createGlobalKey(RDE_UPLOAD); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> Cursor.createGlobalKey(RDE_UPLOAD)); + assertThat(thrown).hasMessageThat().contains("Cursor type is not a global cursor"); } @Test public void testFailure_invalidScopeOnGlobalKeyCreate() throws Exception { createTld("tld"); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Class required for cursor does not match scope class"); - Cursor.createKey(RECURRING_BILLING, persistActiveDomain("notaregistry.tld")); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> Cursor.createKey(RECURRING_BILLING, persistActiveDomain("notaregistry.tld"))); + assertThat(thrown) + .hasMessageThat() + .contains("Class required for cursor does not match scope class"); } @Test public void testFailure_nullScope() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Cursor scope cannot be null"); - Cursor.create(RECURRING_BILLING, START_OF_TIME, null); + NullPointerException thrown = + expectThrows( + NullPointerException.class, + () -> Cursor.create(RECURRING_BILLING, START_OF_TIME, null)); + assertThat(thrown).hasMessageThat().contains("Cursor scope cannot be null"); } @Test public void testFailure_nullCursorType() throws Exception { createTld("tld"); - thrown.expect(NullPointerException.class); - thrown.expectMessage("Cursor type cannot be null"); - Cursor.create(null, START_OF_TIME, Registry.get("tld")); + NullPointerException thrown = + expectThrows( + NullPointerException.class, + () -> Cursor.create(null, START_OF_TIME, Registry.get("tld"))); + assertThat(thrown).hasMessageThat().contains("Cursor type cannot be null"); } @Test public void testFailure_nullTime() throws Exception { createTld("tld"); - thrown.expect(NullPointerException.class); - thrown.expectMessage("Cursor time cannot be null"); - Cursor.create(RDE_UPLOAD, null, Registry.get("tld")); + NullPointerException thrown = + expectThrows( + NullPointerException.class, () -> Cursor.create(RDE_UPLOAD, null, Registry.get("tld"))); + assertThat(thrown).hasMessageThat().contains("Cursor time cannot be null"); } } diff --git a/javatests/google/registry/model/common/TimeOfYearTest.java b/javatests/google/registry/model/common/TimeOfYearTest.java index e6da24a00..f4d5c4686 100644 --- a/javatests/google/registry/model/common/TimeOfYearTest.java +++ b/javatests/google/registry/model/common/TimeOfYearTest.java @@ -21,9 +21,7 @@ import static google.registry.util.DateTimeUtils.START_OF_TIME; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Range; import org.joda.time.DateTime; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -35,9 +33,6 @@ public class TimeOfYearTest { private static final DateTime february29 = DateTime.parse("2012-02-29T01:02:03.0Z"); private static final DateTime march1 = DateTime.parse("2012-03-01T01:02:03.0Z"); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testSuccess_fromDateTime() throws Exception { // We intentionally don't allow leap years in TimeOfYear, so February 29 should be February 28. diff --git a/javatests/google/registry/model/common/TimedTransitionPropertyTest.java b/javatests/google/registry/model/common/TimedTransitionPropertyTest.java index 8a2e0da31..3298b070f 100644 --- a/javatests/google/registry/model/common/TimedTransitionPropertyTest.java +++ b/javatests/google/registry/model/common/TimedTransitionPropertyTest.java @@ -16,6 +16,7 @@ package google.registry.model.common; import static com.google.common.truth.Truth.assertThat; import static google.registry.model.common.TimedTransitionProperty.forMapify; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME; import static org.joda.time.DateTimeZone.UTC; @@ -26,19 +27,13 @@ import java.util.Map; import java.util.Set; import org.joda.time.DateTime; 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; /** Unit tests for {@link TimedTransitionProperty}. */ @RunWith(JUnit4.class) public class TimedTransitionPropertyTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private static final DateTime A_LONG_TIME_AGO = new DateTime(Long.MIN_VALUE, UTC); private static final DateTime DATE_1 = DateTime.parse("2001-01-01T00:00:00.0Z"); @@ -130,31 +125,39 @@ public class TimedTransitionPropertyTest { @Test public void testFailure_valueMapNotChronologicallyOrdered() throws Exception { - thrown.expect(IllegalArgumentException.class); - TimedTransitionProperty.fromValueMap( - ImmutableSortedMap.reverseOrder().put(START_OF_TIME, "0").build(), - StringTimedTransition.class); + assertThrows( + IllegalArgumentException.class, + () -> + TimedTransitionProperty.fromValueMap( + ImmutableSortedMap.reverseOrder().put(START_OF_TIME, "0").build(), + StringTimedTransition.class)); } @Test public void testFailure_transitionTimeBeforeStartOfTime() throws Exception { - thrown.expect(IllegalArgumentException.class); - TimedTransitionProperty.fromValueMap( - ImmutableSortedMap.of(A_LONG_TIME_AGO, "?"), StringTimedTransition.class); + assertThrows( + IllegalArgumentException.class, + () -> + TimedTransitionProperty.fromValueMap( + ImmutableSortedMap.of(A_LONG_TIME_AGO, "?"), StringTimedTransition.class)); } @Test public void testFailure_noValues() throws Exception { - thrown.expect(IllegalArgumentException.class); - TimedTransitionProperty.fromValueMap( - ImmutableSortedMap.of(), StringTimedTransition.class); + assertThrows( + IllegalArgumentException.class, + () -> + TimedTransitionProperty.fromValueMap( + ImmutableSortedMap.of(), StringTimedTransition.class)); } @Test public void testFailure_noValueAtStartOfTime() throws Exception { - thrown.expect(IllegalArgumentException.class); - TimedTransitionProperty.fromValueMap( - ImmutableSortedMap.of(DATE_1, "1"), StringTimedTransition.class); + assertThrows( + IllegalArgumentException.class, + () -> + TimedTransitionProperty.fromValueMap( + ImmutableSortedMap.of(DATE_1, "1"), StringTimedTransition.class)); } @Test @@ -162,8 +165,7 @@ public class TimedTransitionPropertyTest { timedString = forMapify("0", StringTimedTransition.class); // Simulate a load from Datastore by clearing, but don't insert any transitions. timedString.clear(); - thrown.expect(IllegalStateException.class); - timedString.checkValidity(); + assertThrows(IllegalStateException.class, () -> timedString.checkValidity()); } @Test @@ -175,7 +177,6 @@ public class TimedTransitionPropertyTest { // omit a transition corresponding to START_OF_TIME. timedString.clear(); timedString.put(DATE_1, transition1); - thrown.expect(IllegalStateException.class); - timedString.checkValidity(); + assertThrows(IllegalStateException.class, () -> timedString.checkValidity()); } } diff --git a/javatests/google/registry/model/contact/ContactResourceTest.java b/javatests/google/registry/model/contact/ContactResourceTest.java index 3bf05836f..7c8c48c01 100644 --- a/javatests/google/registry/model/contact/ContactResourceTest.java +++ b/javatests/google/registry/model/contact/ContactResourceTest.java @@ -20,6 +20,7 @@ import static google.registry.testing.ContactResourceSubject.assertAboutContacts import static google.registry.testing.DatastoreHelper.cloneAndSetAutoTimestamps; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.DateTimeUtils.END_OF_TIME; import com.google.common.collect.ImmutableList; @@ -37,16 +38,10 @@ import google.registry.model.transfer.TransferData; import google.registry.model.transfer.TransferData.TransferServerApproveEntity; import google.registry.model.transfer.TransferStatus; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link ContactResource}. */ public class ContactResourceTest extends EntityTestCase { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - ContactResource contactResource; @Before @@ -206,9 +201,11 @@ public class ContactResourceTest extends EntityTestCase { @Test public void testSetCreationTime_cantBeCalledTwice() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("creationTime can only be set once"); - contactResource.asBuilder().setCreationTime(END_OF_TIME); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> contactResource.asBuilder().setCreationTime(END_OF_TIME)); + assertThat(thrown).hasMessageThat().contains("creationTime can only be set once"); } @Test diff --git a/javatests/google/registry/model/domain/DomainApplicationTest.java b/javatests/google/registry/model/domain/DomainApplicationTest.java index a083edfc8..fbd52388a 100644 --- a/javatests/google/registry/model/domain/DomainApplicationTest.java +++ b/javatests/google/registry/model/domain/DomainApplicationTest.java @@ -41,16 +41,11 @@ import google.registry.model.host.HostResource; import google.registry.model.smd.EncodedSignedMark; import org.joda.money.Money; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link DomainApplication}. */ public class DomainApplicationTest extends EntityTestCase { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - DomainApplication domainApplication; @Before diff --git a/javatests/google/registry/model/domain/DomainResourceTest.java b/javatests/google/registry/model/domain/DomainResourceTest.java index e78b07e8a..26701eb46 100644 --- a/javatests/google/registry/model/domain/DomainResourceTest.java +++ b/javatests/google/registry/model/domain/DomainResourceTest.java @@ -24,6 +24,7 @@ import static google.registry.testing.DatastoreHelper.newDomainResource; import static google.registry.testing.DatastoreHelper.newHostResource; import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DomainResourceSubject.assertAboutDomains; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.DateTimeUtils.START_OF_TIME; import static org.joda.money.CurrencyUnit.USD; @@ -55,16 +56,10 @@ import java.util.stream.Stream; import org.joda.money.Money; import org.joda.time.DateTime; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link DomainResource}. */ public class DomainResourceTest extends EntityTestCase { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - DomainResource domain; @Before @@ -445,15 +440,23 @@ public class DomainResourceTest extends EntityTestCase { @Test public void testFailure_uppercaseDomainName() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Domain name must be in puny-coded, lower-case form"); - domain.asBuilder().setFullyQualifiedDomainName("AAA.BBB"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> domain.asBuilder().setFullyQualifiedDomainName("AAA.BBB")); + assertThat(thrown) + .hasMessageThat() + .contains("Domain name must be in puny-coded, lower-case form"); } @Test public void testFailure_utf8DomainName() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Domain name must be in puny-coded, lower-case form"); - domain.asBuilder().setFullyQualifiedDomainName("みんな.みんな"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> domain.asBuilder().setFullyQualifiedDomainName("みんな.みんな")); + assertThat(thrown) + .hasMessageThat() + .contains("Domain name must be in puny-coded, lower-case form"); } } diff --git a/javatests/google/registry/model/domain/GracePeriodTest.java b/javatests/google/registry/model/domain/GracePeriodTest.java index 8888c2e74..b527d35ec 100644 --- a/javatests/google/registry/model/domain/GracePeriodTest.java +++ b/javatests/google/registry/model/domain/GracePeriodTest.java @@ -15,6 +15,7 @@ package google.registry.model.domain; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.joda.time.DateTimeZone.UTC; import com.googlecode.objectify.Key; @@ -30,7 +31,6 @@ import org.joda.time.DateTime; 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; @@ -42,10 +42,6 @@ public class GracePeriodTest { public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() // Needed to be able to construct Keys. .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final DateTime now = DateTime.now(UTC); private BillingEvent.OneTime onetime; @@ -96,19 +92,24 @@ public class GracePeriodTest { @Test public void testFailure_forBillingEvent_autoRenew() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("autorenew"); - GracePeriod.forBillingEvent(GracePeriodStatus.AUTO_RENEW, onetime); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> GracePeriod.forBillingEvent(GracePeriodStatus.AUTO_RENEW, onetime)); + assertThat(thrown).hasMessageThat().contains("autorenew"); } @Test public void testFailure_createForRecurring_notAutoRenew() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("autorenew"); - GracePeriod.createForRecurring( - GracePeriodStatus.RENEW, - now.plusDays(1), - "TheRegistrar", - Key.create(Recurring.class, 12345)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + GracePeriod.createForRecurring( + GracePeriodStatus.RENEW, + now.plusDays(1), + "TheRegistrar", + Key.create(Recurring.class, 12345))); + assertThat(thrown).hasMessageThat().contains("autorenew"); } } diff --git a/javatests/google/registry/model/domain/LrpTokenEntityTest.java b/javatests/google/registry/model/domain/LrpTokenEntityTest.java index 925568eb3..ccdaf8432 100644 --- a/javatests/google/registry/model/domain/LrpTokenEntityTest.java +++ b/javatests/google/registry/model/domain/LrpTokenEntityTest.java @@ -26,9 +26,7 @@ import com.googlecode.objectify.Key; import google.registry.model.EntityTestCase; import google.registry.model.reporting.HistoryEntry; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link LrpTokenEntity}. */ public class LrpTokenEntityTest extends EntityTestCase { @@ -36,9 +34,6 @@ public class LrpTokenEntityTest extends EntityTestCase { LrpTokenEntity unredeemedToken; LrpTokenEntity redeemedToken; - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Before public void setUp() throws Exception { createTld("tld"); diff --git a/javatests/google/registry/model/host/HostResourceTest.java b/javatests/google/registry/model/host/HostResourceTest.java index 6b448cacf..6ddf02ba7 100644 --- a/javatests/google/registry/model/host/HostResourceTest.java +++ b/javatests/google/registry/model/host/HostResourceTest.java @@ -21,6 +21,7 @@ import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.newDomainResource; import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.HostResourceSubject.assertAboutHosts; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableSet; import com.google.common.net.InetAddresses; @@ -36,16 +37,10 @@ import google.registry.model.transfer.TransferStatus; import java.net.InetAddress; import org.joda.time.DateTime; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link HostResource}. */ public class HostResourceTest extends EntityTestCase { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - final DateTime day3 = clock.nowUtc(); final DateTime day2 = day3.minusDays(1); final DateTime day1 = day2.minusDays(1); @@ -163,16 +158,24 @@ public class HostResourceTest extends EntityTestCase { @Test public void testFailure_uppercaseHostName() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Host name must be in puny-coded, lower-case form"); - host.asBuilder().setFullyQualifiedHostName("AAA.BBB.CCC"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> host.asBuilder().setFullyQualifiedHostName("AAA.BBB.CCC")); + assertThat(thrown) + .hasMessageThat() + .contains("Host name must be in puny-coded, lower-case form"); } @Test public void testFailure_utf8HostName() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Host name must be in puny-coded, lower-case form"); - host.asBuilder().setFullyQualifiedHostName("みんな.みんな.みんな"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> host.asBuilder().setFullyQualifiedHostName("みんな.みんな.みんな")); + assertThat(thrown) + .hasMessageThat() + .contains("Host name must be in puny-coded, lower-case form"); } @Test diff --git a/javatests/google/registry/model/index/DomainApplicationIndexTest.java b/javatests/google/registry/model/index/DomainApplicationIndexTest.java index a190e6924..96f46deee 100644 --- a/javatests/google/registry/model/index/DomainApplicationIndexTest.java +++ b/javatests/google/registry/model/index/DomainApplicationIndexTest.java @@ -23,6 +23,7 @@ import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.newDomainApplication; import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistSimpleResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.joda.time.DateTimeZone.UTC; import com.google.common.collect.ImmutableList; @@ -32,16 +33,10 @@ import google.registry.model.EntityTestCase; import google.registry.model.domain.DomainApplication; import org.joda.time.DateTime; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link DomainApplicationIndex}. */ public class DomainApplicationIndexTest extends EntityTestCase { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Before public void init() throws Exception { createTld("com"); @@ -49,16 +44,20 @@ public class DomainApplicationIndexTest extends EntityTestCase { @Test public void testFailure_create_nullReferences() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Keys must not be null or empty."); - DomainApplicationIndex.createWithSpecifiedKeys("blah.com", null); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> DomainApplicationIndex.createWithSpecifiedKeys("blah.com", null)); + assertThat(thrown).hasMessageThat().contains("Keys must not be null or empty."); } @Test public void testFailure_create_emptyReferences() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Keys must not be null or empty."); - createWithSpecifiedKeys("blah.com", ImmutableSet.>of()); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> createWithSpecifiedKeys("blah.com", ImmutableSet.>of())); + assertThat(thrown).hasMessageThat().contains("Keys must not be null or empty."); } @Test diff --git a/javatests/google/registry/model/index/ForeignKeyIndexTest.java b/javatests/google/registry/model/index/ForeignKeyIndexTest.java index f338d5b22..b1abcaf6c 100644 --- a/javatests/google/registry/model/index/ForeignKeyIndexTest.java +++ b/javatests/google/registry/model/index/ForeignKeyIndexTest.java @@ -27,16 +27,11 @@ import google.registry.model.EntityTestCase; import google.registry.model.host.HostResource; import google.registry.model.index.ForeignKeyIndex.ForeignKeyHostIndex; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link ForeignKeyIndex}. */ public class ForeignKeyIndexTest extends EntityTestCase { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Before public void setUp() throws Exception { createTld("com"); diff --git a/javatests/google/registry/model/ofy/CommitLogBucketTest.java b/javatests/google/registry/model/ofy/CommitLogBucketTest.java index 01452512e..974e42361 100644 --- a/javatests/google/registry/model/ofy/CommitLogBucketTest.java +++ b/javatests/google/registry/model/ofy/CommitLogBucketTest.java @@ -19,6 +19,7 @@ import static google.registry.model.ofy.CommitLogBucket.getBucketKey; import static google.registry.model.ofy.CommitLogBucket.loadAllBuckets; import static google.registry.model.ofy.CommitLogBucket.loadBucket; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.DateTimeUtils.END_OF_TIME; import com.google.common.base.Suppliers; @@ -29,7 +30,6 @@ import google.registry.testing.InjectRule; 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; @@ -44,10 +44,6 @@ public class CommitLogBucketTest { @Rule public final InjectRule inject = new InjectRule(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - CommitLogBucket bucket; @Before @@ -69,16 +65,16 @@ public class CommitLogBucketTest { @Test public void test_getBucketKey_bucketNumberTooLow_throws() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("0 not in ["); - getBucketKey(0); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> getBucketKey(0)); + assertThat(thrown).hasMessageThat().contains("0 not in ["); } @Test public void test_getBucketKey_bucketNumberTooHigh_throws() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("11 not in ["); - getBucketKey(11); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> getBucketKey(11)); + assertThat(thrown).hasMessageThat().contains("11 not in ["); } @Test diff --git a/javatests/google/registry/model/ofy/CommitLogCheckpointTest.java b/javatests/google/registry/model/ofy/CommitLogCheckpointTest.java index b5073904d..6f93b46ef 100644 --- a/javatests/google/registry/model/ofy/CommitLogCheckpointTest.java +++ b/javatests/google/registry/model/ofy/CommitLogCheckpointTest.java @@ -15,6 +15,7 @@ package google.registry.model.ofy; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.DateTimeUtils.START_OF_TIME; import static org.joda.time.DateTimeZone.UTC; @@ -23,7 +24,6 @@ import google.registry.testing.AppEngineRule; import org.joda.time.DateTime; 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 +36,6 @@ public class CommitLogCheckpointTest { .withDatastore() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private static final DateTime T1 = START_OF_TIME; private static final DateTime T2 = START_OF_TIME.plusMillis(1); private static final DateTime T3 = START_OF_TIME.plusMillis(2); @@ -60,29 +57,43 @@ public class CommitLogCheckpointTest { @Test public void test_create_notEnoughBucketTimestamps_throws() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Bucket ids are incorrect"); - CommitLogCheckpoint.create(DateTime.now(UTC), ImmutableMap.of(1, T1, 2, T2)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> CommitLogCheckpoint.create(DateTime.now(UTC), ImmutableMap.of(1, T1, 2, T2))); + assertThat(thrown).hasMessageThat().contains("Bucket ids are incorrect"); } @Test public void test_create_tooManyBucketTimestamps_throws() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Bucket ids are incorrect"); - CommitLogCheckpoint.create(DateTime.now(UTC), ImmutableMap.of(1, T1, 2, T2, 3, T3, 4, T1)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + CommitLogCheckpoint.create( + DateTime.now(UTC), ImmutableMap.of(1, T1, 2, T2, 3, T3, 4, T1))); + assertThat(thrown).hasMessageThat().contains("Bucket ids are incorrect"); } @Test public void test_create_wrongBucketIds_throws() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Bucket ids are incorrect"); - CommitLogCheckpoint.create(DateTime.now(UTC), ImmutableMap.of(0, T1, 1, T2, 2, T3)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + CommitLogCheckpoint.create( + DateTime.now(UTC), ImmutableMap.of(0, T1, 1, T2, 2, T3))); + assertThat(thrown).hasMessageThat().contains("Bucket ids are incorrect"); } @Test public void test_create_wrongBucketIdOrder_throws() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Bucket ids are incorrect"); - CommitLogCheckpoint.create(DateTime.now(UTC), ImmutableMap.of(2, T2, 1, T1, 3, T3)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + CommitLogCheckpoint.create( + DateTime.now(UTC), ImmutableMap.of(2, T2, 1, T1, 3, T3))); + assertThat(thrown).hasMessageThat().contains("Bucket ids are incorrect"); } } diff --git a/javatests/google/registry/model/ofy/OfyCommitLogTest.java b/javatests/google/registry/model/ofy/OfyCommitLogTest.java index ba4600ca6..261794935 100644 --- a/javatests/google/registry/model/ofy/OfyCommitLogTest.java +++ b/javatests/google/registry/model/ofy/OfyCommitLogTest.java @@ -20,6 +20,7 @@ import static com.googlecode.objectify.ObjectifyService.register; import static google.registry.model.common.EntityGroupRoot.getCrossTldKey; import static google.registry.model.ofy.CommitLogBucket.getBucketKey; import static google.registry.model.ofy.ObjectifyService.ofy; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableSet; import com.googlecode.objectify.Key; @@ -37,7 +38,6 @@ import org.joda.time.DateTime; 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; @@ -50,9 +50,6 @@ public class OfyCommitLogTest { .withDatastore() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -163,74 +160,91 @@ public class OfyCommitLogTest { public void testTransactNew_deleteNotBackedUpKind_throws() throws Exception { final CommitLogManifest backupsArentAllowedOnMe = CommitLogManifest.create(getBucketKey(1), clock.nowUtc(), ImmutableSet.>of()); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Can't save/delete a @NotBackedUp"); - ofy().transactNew(() -> ofy().delete().entity(backupsArentAllowedOnMe)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> ofy().transactNew(() -> ofy().delete().entity(backupsArentAllowedOnMe))); + assertThat(thrown).hasMessageThat().contains("Can't save/delete a @NotBackedUp"); } @Test public void testTransactNew_saveNotBackedUpKind_throws() throws Exception { final CommitLogManifest backupsArentAllowedOnMe = CommitLogManifest.create(getBucketKey(1), clock.nowUtc(), ImmutableSet.>of()); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Can't save/delete a @NotBackedUp"); - ofy().transactNew(() -> ofy().save().entity(backupsArentAllowedOnMe)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> ofy().transactNew(() -> ofy().save().entity(backupsArentAllowedOnMe))); + assertThat(thrown).hasMessageThat().contains("Can't save/delete a @NotBackedUp"); } @Test public void testTransactNew_deleteVirtualEntityKey_throws() throws Exception { final Key virtualEntityKey = TestVirtualObject.createKey("virtual"); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Can't save/delete a @VirtualEntity"); - ofy().transactNew(() -> ofy().delete().key(virtualEntityKey)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> ofy().transactNew(() -> ofy().delete().key(virtualEntityKey))); + assertThat(thrown).hasMessageThat().contains("Can't save/delete a @VirtualEntity"); } @Test public void testTransactNew_saveVirtualEntity_throws() throws Exception { final TestVirtualObject virtualEntity = TestVirtualObject.create("virtual"); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Can't save/delete a @VirtualEntity"); - ofy().transactNew(() -> ofy().save().entity(virtualEntity)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> ofy().transactNew(() -> ofy().save().entity(virtualEntity))); + assertThat(thrown).hasMessageThat().contains("Can't save/delete a @VirtualEntity"); } @Test public void test_deleteWithoutBackup_withVirtualEntityKey_throws() throws Exception { final Key virtualEntityKey = TestVirtualObject.createKey("virtual"); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Can't save/delete a @VirtualEntity"); - ofy().deleteWithoutBackup().key(virtualEntityKey); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> ofy().deleteWithoutBackup().key(virtualEntityKey)); + assertThat(thrown).hasMessageThat().contains("Can't save/delete a @VirtualEntity"); } @Test public void test_saveWithoutBackup_withVirtualEntity_throws() throws Exception { final TestVirtualObject virtualEntity = TestVirtualObject.create("virtual"); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Can't save/delete a @VirtualEntity"); - ofy().saveWithoutBackup().entity(virtualEntity); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> ofy().saveWithoutBackup().entity(virtualEntity)); + assertThat(thrown).hasMessageThat().contains("Can't save/delete a @VirtualEntity"); } @Test public void testTransact_twoSavesOnSameKey_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Multiple entries with same key"); - ofy() - .transact( - () -> { - ofy().save().entity(Root.create(1, getCrossTldKey())); - ofy().save().entity(Root.create(1, getCrossTldKey())); - }); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + ofy() + .transact( + () -> { + ofy().save().entity(Root.create(1, getCrossTldKey())); + ofy().save().entity(Root.create(1, getCrossTldKey())); + })); + assertThat(thrown).hasMessageThat().contains("Multiple entries with same key"); } @Test public void testTransact_saveAndDeleteSameKey_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Multiple entries with same key"); - ofy() - .transact( - () -> { - ofy().save().entity(Root.create(1, getCrossTldKey())); - ofy().delete().entity(Root.create(1, getCrossTldKey())); - }); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + ofy() + .transact( + () -> { + ofy().save().entity(Root.create(1, getCrossTldKey())); + ofy().delete().entity(Root.create(1, getCrossTldKey())); + })); + assertThat(thrown).hasMessageThat().contains("Multiple entries with same key"); } @Test diff --git a/javatests/google/registry/model/ofy/OfyFilterTest.java b/javatests/google/registry/model/ofy/OfyFilterTest.java index f678fc912..165a8f628 100644 --- a/javatests/google/registry/model/ofy/OfyFilterTest.java +++ b/javatests/google/registry/model/ofy/OfyFilterTest.java @@ -30,9 +30,7 @@ import com.googlecode.objectify.annotation.Id; import google.registry.model.contact.ContactResource; import org.junit.After; 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; @@ -63,9 +61,6 @@ public class OfyFilterTest { helper.tearDown(); } - @Rule - public final ExpectedException thrown = ExpectedException.none(); - /** * Key.create looks up kind metadata for the class of the object it is given. If this happens * before the first reference to ObjectifyService, which statically triggers type registrations, diff --git a/javatests/google/registry/model/ofy/OfyTest.java b/javatests/google/registry/model/ofy/OfyTest.java index b2301cca5..1b6b295f6 100644 --- a/javatests/google/registry/model/ofy/OfyTest.java +++ b/javatests/google/registry/model/ofy/OfyTest.java @@ -23,6 +23,8 @@ import static google.registry.model.ofy.Ofy.getBaseEntityClassFromEntityOrKey; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.newContactResource; import static google.registry.testing.DatastoreHelper.persistActiveContact; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME; import static java.nio.charset.StandardCharsets.UTF_8; @@ -55,7 +57,6 @@ import org.joda.time.DateTime; 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; @@ -67,10 +68,6 @@ public class OfyTest { public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - /** An entity to use in save and delete tests. */ private HistoryEntry someObject; @@ -92,13 +89,15 @@ public class OfyTest { .getUpdateAutoTimestamp().getTimestamp(); // Set the clock in Ofy to the same time as the backup group root's save time. Ofy ofy = new Ofy(new FakeClock(groupTimestamp)); - thrown.expect(TimestampInversionException.class); - thrown.expectMessage(String.format( - "Timestamp inversion between transaction time (%s) and entities rooted under:\n" - + "{Key(ContactResource(\"2-ROID\"))=%s}", - groupTimestamp, - groupTimestamp)); - ofy.transact(work); + TimestampInversionException thrown = + expectThrows(TimestampInversionException.class, () -> ofy.transact(work)); + assertThat(thrown) + .hasMessageThat() + .contains( + String.format( + "Timestamp inversion between transaction time (%s) and entities rooted under:\n" + + "{Key(ContactResource(\"2-ROID\"))=%s}", + groupTimestamp, groupTimestamp)); } @Test @@ -121,60 +120,89 @@ public class OfyTest { @Test public void testSavingKeyTwice() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Multiple entries with same key"); - ofy().transact(new VoidWork() { - @Override - public void vrun() { - ofy().save().entity(someObject); - ofy().save().entity(someObject); - }}); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + ofy().save().entity(someObject); + ofy().save().entity(someObject); + } + })); + assertThat(thrown).hasMessageThat().contains("Multiple entries with same key"); } @Test public void testDeletingKeyTwice() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Multiple entries with same key"); - ofy().transact(new VoidWork() { - @Override - public void vrun() { - ofy().delete().entity(someObject); - ofy().delete().entity(someObject); - }}); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + ofy().delete().entity(someObject); + ofy().delete().entity(someObject); + } + })); + assertThat(thrown).hasMessageThat().contains("Multiple entries with same key"); } @Test public void testSaveDeleteKey() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Multiple entries with same key"); - ofy().transact(new VoidWork() { - @Override - public void vrun() { - ofy().save().entity(someObject); - ofy().delete().entity(someObject); - }}); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + ofy().save().entity(someObject); + ofy().delete().entity(someObject); + } + })); + assertThat(thrown).hasMessageThat().contains("Multiple entries with same key"); } @Test public void testDeleteSaveKey() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Multiple entries with same key"); - ofy().transact(new VoidWork() { - @Override - public void vrun() { - ofy().delete().entity(someObject); - ofy().save().entity(someObject); - }}); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + ofy().delete().entity(someObject); + ofy().save().entity(someObject); + } + })); + assertThat(thrown).hasMessageThat().contains("Multiple entries with same key"); } @Test public void testSavingKeyTwiceInOneCall() { - thrown.expect(IllegalArgumentException.class); - ofy().transact(new VoidWork() { - @Override - public void vrun() { - ofy().save().entities(someObject, someObject); - }}); + assertThrows( + IllegalArgumentException.class, + () -> + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + ofy().save().entities(someObject, someObject); + } + })); } /** Simple entity class with lifecycle callbacks. */ @@ -375,17 +403,24 @@ public class OfyTest { @Test public void test_getBaseEntityClassFromEntityOrKey_unregisteredEntity() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("SystemClock"); - getBaseEntityClassFromEntityOrKey(new SystemClock()); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> getBaseEntityClassFromEntityOrKey(new SystemClock())); + assertThat(thrown).hasMessageThat().contains("SystemClock"); } @Test public void test_getBaseEntityClassFromEntityOrKey_unregisteredEntityKey() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("UnknownKind"); - getBaseEntityClassFromEntityOrKey(Key.create( - com.google.appengine.api.datastore.KeyFactory.createKey("UnknownKind", 1))); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + getBaseEntityClassFromEntityOrKey( + Key.create( + com.google.appengine.api.datastore.KeyFactory.createKey( + "UnknownKind", 1)))); + assertThat(thrown).hasMessageThat().contains("UnknownKind"); } @Test diff --git a/javatests/google/registry/model/poll/PollMessageExternalKeyConverterTest.java b/javatests/google/registry/model/poll/PollMessageExternalKeyConverterTest.java index 5f804a92d..2c07c755f 100644 --- a/javatests/google/registry/model/poll/PollMessageExternalKeyConverterTest.java +++ b/javatests/google/registry/model/poll/PollMessageExternalKeyConverterTest.java @@ -38,7 +38,6 @@ import org.joda.time.DateTime; 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; @@ -54,9 +53,6 @@ public class PollMessageExternalKeyConverterTest { @Rule public InjectRule inject = new InjectRule(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - HistoryEntry historyEntry; FakeClock clock = new FakeClock(DateTime.parse("2007-07-07T01:01:01Z")); diff --git a/javatests/google/registry/model/rde/RdeNamingUtilsTest.java b/javatests/google/registry/model/rde/RdeNamingUtilsTest.java index 2b885d67e..84c749a85 100644 --- a/javatests/google/registry/model/rde/RdeNamingUtilsTest.java +++ b/javatests/google/registry/model/rde/RdeNamingUtilsTest.java @@ -19,21 +19,16 @@ import static google.registry.model.rde.RdeMode.FULL; import static google.registry.model.rde.RdeMode.THIN; import static google.registry.model.rde.RdeNamingUtils.makePartialName; import static google.registry.model.rde.RdeNamingUtils.makeRydeFilename; +import static google.registry.testing.JUnitBackports.assertThrows; import org.joda.time.DateTime; -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 RdeNamingUtils}. */ @RunWith(JUnit4.class) public class RdeNamingUtilsTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testMakeRydeFilename_rdeDeposit() throws Exception { assertThat(makeRydeFilename("numbness", DateTime.parse("1984-12-18TZ"), FULL, 1, 0)) @@ -54,8 +49,9 @@ public class RdeNamingUtilsTest { @Test public void testMakeRydeFilename_timestampNotAtTheWitchingHour_throwsIae() throws Exception { - thrown.expect(IllegalArgumentException.class); - makeRydeFilename("wretched", DateTime.parse("2000-12-18T04:20Z"), THIN, 1, 0); + assertThrows( + IllegalArgumentException.class, + () -> makeRydeFilename("wretched", DateTime.parse("2000-12-18T04:20Z"), THIN, 1, 0)); } @Test diff --git a/javatests/google/registry/model/rde/RdeRevisionTest.java b/javatests/google/registry/model/rde/RdeRevisionTest.java index dec1a2778..9a71c37ee 100644 --- a/javatests/google/registry/model/rde/RdeRevisionTest.java +++ b/javatests/google/registry/model/rde/RdeRevisionTest.java @@ -19,6 +19,7 @@ import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.rde.RdeMode.FULL; import static google.registry.model.rde.RdeRevision.getNextRevision; import static google.registry.model.rde.RdeRevision.saveRevision; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.base.VerifyException; import com.googlecode.objectify.VoidWork; @@ -26,7 +27,6 @@ import google.registry.testing.AppEngineRule; import org.joda.time.DateTime; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -36,10 +36,6 @@ public class RdeRevisionTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testGetNextRevision_objectDoesntExist_returnsZero() throws Exception { assertThat(getNextRevision("torment", DateTime.parse("1984-12-18TZ"), FULL)) @@ -70,25 +66,37 @@ public class RdeRevisionTest { @Test public void testSaveRevision_objectDoesntExist_newRevisionIsOne_throwsVe() throws Exception { - thrown.expect(VerifyException.class); - thrown.expectMessage("object missing"); - ofy().transact(new VoidWork() { - @Override - public void vrun() { - saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 1); - }}); + VerifyException thrown = + expectThrows( + VerifyException.class, + () -> + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 1); + } + })); + assertThat(thrown).hasMessageThat().contains("object missing"); } @Test public void testSaveRevision_objectExistsAtZero_newRevisionIsZero_throwsVe() throws Exception { save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); - thrown.expect(VerifyException.class); - thrown.expectMessage("object already created"); - ofy().transact(new VoidWork() { - @Override - public void vrun() { - saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); - }}); + VerifyException thrown = + expectThrows( + VerifyException.class, + () -> + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); + } + })); + assertThat(thrown).hasMessageThat().contains("object already created"); } @Test @@ -110,31 +118,45 @@ public class RdeRevisionTest { @Test public void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() throws Exception { save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0); - thrown.expect(VerifyException.class); - thrown.expectMessage("should be at 1 "); - ofy().transact(new VoidWork() { - @Override - public void vrun() { - saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 2); - }}); + VerifyException thrown = + expectThrows( + VerifyException.class, + () -> + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 2); + } + })); + assertThat(thrown).hasMessageThat().contains("should be at 1 "); } @Test public void testSaveRevision_negativeRevision_throwsIae() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Negative revision"); - ofy().transact(new VoidWork() { - @Override - public void vrun() { - saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, -1); - }}); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + ofy() + .transact( + new VoidWork() { + @Override + public void vrun() { + saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, -1); + } + })); + assertThat(thrown).hasMessageThat().contains("Negative revision"); } @Test public void testSaveRevision_callerNotInTransaction_throwsIse() throws Exception { - thrown.expect(IllegalStateException.class); - thrown.expectMessage("transaction"); - saveRevision("frenzy", DateTime.parse("1984-12-18TZ"), FULL, 1); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> saveRevision("frenzy", DateTime.parse("1984-12-18TZ"), FULL, 1)); + assertThat(thrown).hasMessageThat().contains("transaction"); } public static void save(String tld, DateTime date, RdeMode mode, int revision) { diff --git a/javatests/google/registry/model/registrar/RegistrarTest.java b/javatests/google/registry/model/registrar/RegistrarTest.java index 24f37eea6..4be0a3ad7 100644 --- a/javatests/google/registry/model/registrar/RegistrarTest.java +++ b/javatests/google/registry/model/registrar/RegistrarTest.java @@ -26,6 +26,8 @@ import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistSimpleResource; import static google.registry.testing.DatastoreHelper.persistSimpleResources; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -40,16 +42,10 @@ import google.registry.model.registrar.Registrar.Type; import google.registry.util.CidrAddressBlock; import org.joda.money.CurrencyUnit; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link Registrar}. */ public class RegistrarTest extends EntityTestCase { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - private Registrar registrar; private RegistrarContact abuseAdminContact; @@ -143,23 +139,27 @@ public class RegistrarTest extends EntityTestCase { @Test public void testFailure_passwordNull() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Password must be 6-16 characters long."); - new Registrar.Builder().setPassword(null); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> new Registrar.Builder().setPassword(null)); + assertThat(thrown).hasMessageThat().contains("Password must be 6-16 characters long."); } @Test public void testFailure_passwordTooShort() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Password must be 6-16 characters long."); - new Registrar.Builder().setPassword("abcde"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> new Registrar.Builder().setPassword("abcde")); + assertThat(thrown).hasMessageThat().contains("Password must be 6-16 characters long."); } @Test public void testFailure_passwordTooLong() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Password must be 6-16 characters long."); - new Registrar.Builder().setPassword("abcdefghijklmnopq"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> new Registrar.Builder().setPassword("abcdefghijklmnopq")); + assertThat(thrown).hasMessageThat().contains("Password must be 6-16 characters long."); } @Test @@ -172,14 +172,14 @@ public class RegistrarTest extends EntityTestCase { @Test public void testFailure_clientId_tooShort() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setClientId("ab"); + assertThrows(IllegalArgumentException.class, () -> new Registrar.Builder().setClientId("ab")); } @Test public void testFailure_clientId_tooLong() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setClientId("abcdefghijklmnopq"); + assertThrows( + IllegalArgumentException.class, + () -> new Registrar.Builder().setClientId("abcdefghijklmnopq")); } @Test @@ -318,87 +318,103 @@ public class RegistrarTest extends EntityTestCase { @Test public void testFailure_missingRegistrarType() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Registrar type cannot be null"); - new Registrar.Builder().setRegistrarName("blah").build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> new Registrar.Builder().setRegistrarName("blah").build()); + assertThat(thrown).hasMessageThat().contains("Registrar type cannot be null"); } @Test public void testFailure_missingRegistrarName() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Registrar name cannot be null"); - new Registrar.Builder().setClientId("blahid").setType(Registrar.Type.TEST).build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + new Registrar.Builder().setClientId("blahid").setType(Registrar.Type.TEST).build()); + assertThat(thrown).hasMessageThat().contains("Registrar name cannot be null"); } @Test public void testFailure_missingAddress() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Must specify at least one of localized or internationalized address"); - new Registrar.Builder() - .setClientId("blahid") - .setType(Registrar.Type.TEST) - .setRegistrarName("Blah Co") - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + new Registrar.Builder() + .setClientId("blahid") + .setType(Registrar.Type.TEST) + .setRegistrarName("Blah Co") + .build()); + assertThat(thrown) + .hasMessageThat() + .contains("Must specify at least one of localized or internationalized address"); } @Test public void testFailure_badIanaIdForInternal() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setType(Type.INTERNAL).setIanaIdentifier(8L).build(); + assertThrows( + IllegalArgumentException.class, + () -> new Registrar.Builder().setType(Type.INTERNAL).setIanaIdentifier(8L).build()); } @Test public void testFailure_badIanaIdForPdt() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setType(Type.PDT).setIanaIdentifier(8L).build(); + assertThrows( + IllegalArgumentException.class, + () -> new Registrar.Builder().setType(Type.PDT).setIanaIdentifier(8L).build()); } @Test public void testFailure_badIanaIdForExternalMonitoring() throws Exception { - thrown.expect(IllegalArgumentException.class); - registrar.asBuilder().setType(Type.EXTERNAL_MONITORING).setIanaIdentifier(8L).build(); + assertThrows( + IllegalArgumentException.class, + () -> + registrar.asBuilder().setType(Type.EXTERNAL_MONITORING).setIanaIdentifier(8L).build()); } @Test public void testFailure_missingIanaIdForReal() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setType(Type.REAL).build(); + assertThrows( + IllegalArgumentException.class, () -> new Registrar.Builder().setType(Type.REAL).build()); } @Test public void testFailure_missingIanaIdForInternal() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setType(Type.INTERNAL).build(); + assertThrows( + IllegalArgumentException.class, + () -> new Registrar.Builder().setType(Type.INTERNAL).build()); } @Test public void testFailure_missingIanaIdForPdt() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setType(Type.PDT).build(); + assertThrows( + IllegalArgumentException.class, () -> new Registrar.Builder().setType(Type.PDT).build()); } @Test public void testFailure_missingIanaIdForExternalMonitoring() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setType(Type.EXTERNAL_MONITORING).build(); + assertThrows( + IllegalArgumentException.class, + () -> new Registrar.Builder().setType(Type.EXTERNAL_MONITORING).build()); } @Test public void testFailure_phonePasscodeTooShort() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setPhonePasscode("0123"); + assertThrows( + IllegalArgumentException.class, () -> new Registrar.Builder().setPhonePasscode("0123")); } @Test public void testFailure_phonePasscodeTooLong() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setPhonePasscode("012345"); + assertThrows( + IllegalArgumentException.class, () -> new Registrar.Builder().setPhonePasscode("012345")); } @Test public void testFailure_phonePasscodeInvalidCharacters() throws Exception { - thrown.expect(IllegalArgumentException.class); - new Registrar.Builder().setPhonePasscode("code1"); + assertThrows( + IllegalArgumentException.class, () -> new Registrar.Builder().setPhonePasscode("code1")); } @Test @@ -420,29 +436,29 @@ public class RegistrarTest extends EntityTestCase { @Test public void testFailure_loadByClientId_clientIdIsNull() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("clientId must be specified"); - Registrar.loadByClientId(null); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> Registrar.loadByClientId(null)); + assertThat(thrown).hasMessageThat().contains("clientId must be specified"); } @Test public void testFailure_loadByClientId_clientIdIsEmpty() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("clientId must be specified"); - Registrar.loadByClientId(""); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> Registrar.loadByClientId("")); + assertThat(thrown).hasMessageThat().contains("clientId must be specified"); } @Test public void testFailure_loadByClientIdCached_clientIdIsNull() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("clientId must be specified"); - Registrar.loadByClientIdCached(null); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> Registrar.loadByClientIdCached(null)); + assertThat(thrown).hasMessageThat().contains("clientId must be specified"); } @Test public void testFailure_loadByClientIdCached_clientIdIsEmpty() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("clientId must be specified"); - Registrar.loadByClientIdCached(""); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> Registrar.loadByClientIdCached("")); + assertThat(thrown).hasMessageThat().contains("clientId must be specified"); } } diff --git a/javatests/google/registry/model/registry/RegistriesTest.java b/javatests/google/registry/model/registry/RegistriesTest.java index 6b6e1e51d..99dd6c2e1 100644 --- a/javatests/google/registry/model/registry/RegistriesTest.java +++ b/javatests/google/registry/model/registry/RegistriesTest.java @@ -17,12 +17,12 @@ package google.registry.model.registry; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static google.registry.testing.DatastoreHelper.createTlds; +import static google.registry.testing.JUnitBackports.assertThrows; import com.google.common.net.InternetDomainName; import google.registry.testing.AppEngineRule; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -32,10 +32,6 @@ public class RegistriesTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - private void initTestTlds() { createTlds("foo", "a.b.c"); // Test a multipart tld. } @@ -61,8 +57,7 @@ public class RegistriesTest { @Test public void testAssertTldExists_doesntExist() { initTestTlds(); - thrown.expect(IllegalArgumentException.class); - Registries.assertTldExists("baz"); + assertThrows(IllegalArgumentException.class, () -> Registries.assertTldExists("baz")); } @Test diff --git a/javatests/google/registry/model/registry/RegistryTest.java b/javatests/google/registry/model/registry/RegistryTest.java index d46adc85d..c461cc6ae 100644 --- a/javatests/google/registry/model/registry/RegistryTest.java +++ b/javatests/google/registry/model/registry/RegistryTest.java @@ -44,15 +44,10 @@ import java.math.BigDecimal; import org.joda.money.Money; import org.joda.time.DateTime; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; /** Unit tests for {@link Registry}. */ public class RegistryTest extends EntityTestCase { - - @Rule public final ExpectedException thrown = ExpectedException.none(); - Registry registry; @Before @@ -71,8 +66,7 @@ public class RegistryTest extends EntityTestCase { @Test public void testFailure_registryNotFound() throws Exception { createTld("foo"); - thrown.expect(RegistryNotFoundException.class); - Registry.get("baz"); + assertThrows(RegistryNotFoundException.class, () -> Registry.get("baz")); } @Test @@ -202,11 +196,17 @@ public class RegistryTest extends EntityTestCase { ReservedList rl3 = persistReservedList( "tld-reserved057", "lol,RESERVED_FOR_ANCHOR_TENANT,another_conflict"); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "auth code conflicts for labels: [lol=[conflict1, conflict2, another_conflict]]"); - @SuppressWarnings("unused") - Registry unused = Registry.get("tld").asBuilder().setReservedLists(rl1, rl2, rl3).build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> { + @SuppressWarnings("unused") + Registry unused = + Registry.get("tld").asBuilder().setReservedLists(rl1, rl2, rl3).build(); + }); + assertThat(thrown) + .hasMessageThat() + .contains("auth code conflicts for labels: [lol=[conflict1, conflict2, another_conflict]]"); } @Test @@ -354,116 +354,167 @@ public class RegistryTest extends EntityTestCase { @Test public void testFailure_tldNeverSet() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("No registry TLD specified"); - new Registry.Builder().build(); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> new Registry.Builder().build()); + assertThat(thrown).hasMessageThat().contains("No registry TLD specified"); } @Test public void testFailure_setTldStr_null() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("TLD must not be null"); - new Registry.Builder().setTldStr(null); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> new Registry.Builder().setTldStr(null)); + assertThat(thrown).hasMessageThat().contains("TLD must not be null"); } @Test public void testFailure_setTldStr_invalidTld() { - thrown.expect(IllegalArgumentException.class); - thrown - .expectMessage("Cannot create registry for TLD that is not a valid, canonical domain name"); - new Registry.Builder().setTldStr(".tld").build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> new Registry.Builder().setTldStr(".tld").build()); + assertThat(thrown) + .hasMessageThat() + .contains("Cannot create registry for TLD that is not a valid, canonical domain name"); } @Test public void testFailure_setTldStr_nonCanonicalTld() { - thrown.expect(IllegalArgumentException.class); - thrown - .expectMessage("Cannot create registry for TLD that is not a valid, canonical domain name"); - new Registry.Builder().setTldStr("TLD").build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> new Registry.Builder().setTldStr("TLD").build()); + assertThat(thrown) + .hasMessageThat() + .contains("Cannot create registry for TLD that is not a valid, canonical domain name"); } @Test public void testFailure_tldStatesOutOfOrder() { - thrown.expect(IllegalArgumentException.class); - Registry.get("tld").asBuilder() - .setTldStateTransitions(ImmutableSortedMap.of( - clock.nowUtc(), TldState.SUNRUSH, clock.nowUtc().plusMonths(1), TldState.SUNRISE)) - .build(); + assertThrows( + IllegalArgumentException.class, + () -> + Registry.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of( + clock.nowUtc(), + TldState.SUNRUSH, + clock.nowUtc().plusMonths(1), + TldState.SUNRISE)) + .build()); } @Test public void testFailure_duplicateTldState() { - thrown.expect(IllegalArgumentException.class); - Registry.get("tld").asBuilder() - .setTldStateTransitions(ImmutableSortedMap.of( - clock.nowUtc(), TldState.SUNRUSH, clock.nowUtc().plusMonths(1), TldState.SUNRUSH)) - .build(); + assertThrows( + IllegalArgumentException.class, + () -> + Registry.get("tld") + .asBuilder() + .setTldStateTransitions( + ImmutableSortedMap.of( + clock.nowUtc(), + TldState.SUNRUSH, + clock.nowUtc().plusMonths(1), + TldState.SUNRUSH)) + .build()); } @Test public void testFailure_pricingEngineIsRequired() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("All registries must have a configured pricing engine"); - new Registry.Builder().setTldStr("invalid").build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> new Registry.Builder().setTldStr("invalid").build()); + assertThat(thrown) + .hasMessageThat() + .contains("All registries must have a configured pricing engine"); } @Test public void testFailure_negativeRenewBillingCostTransitionValue() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("billing cost cannot be negative"); - Registry.get("tld").asBuilder() - .setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(USD, -42))); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + Registry.get("tld") + .asBuilder() + .setRenewBillingCostTransitions( + ImmutableSortedMap.of(START_OF_TIME, Money.of(USD, -42)))); + assertThat(thrown).hasMessageThat().contains("billing cost cannot be negative"); } @Test public void testFailure_negativeCreateBillingCost() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("createBillingCost cannot be negative"); - Registry.get("tld").asBuilder().setCreateBillingCost(Money.of(USD, -42)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> Registry.get("tld").asBuilder().setCreateBillingCost(Money.of(USD, -42))); + assertThat(thrown).hasMessageThat().contains("createBillingCost cannot be negative"); } @Test public void testFailure_negativeRestoreBillingCost() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("restoreBillingCost cannot be negative"); - Registry.get("tld").asBuilder().setRestoreBillingCost(Money.of(USD, -42)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> Registry.get("tld").asBuilder().setRestoreBillingCost(Money.of(USD, -42))); + assertThat(thrown).hasMessageThat().contains("restoreBillingCost cannot be negative"); } @Test public void testFailure_negativeServerStatusChangeBillingCost() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("billing cost cannot be negative"); - Registry.get("tld").asBuilder().setServerStatusChangeBillingCost(Money.of(USD, -42)); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + Registry.get("tld") + .asBuilder() + .setServerStatusChangeBillingCost(Money.of(USD, -42))); + assertThat(thrown).hasMessageThat().contains("billing cost cannot be negative"); } @Test public void testFailure_renewBillingCostTransitionValue_wrongCurrency() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("cost must be in the registry's currency"); - Registry.get("tld").asBuilder() - .setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 42))) - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + Registry.get("tld") + .asBuilder() + .setRenewBillingCostTransitions( + ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 42))) + .build()); + assertThat(thrown).hasMessageThat().contains("cost must be in the registry's currency"); } @Test public void testFailure_createBillingCost_wrongCurrency() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("cost must be in the registry's currency"); - Registry.get("tld").asBuilder().setCreateBillingCost(Money.of(EUR, 42)).build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> Registry.get("tld").asBuilder().setCreateBillingCost(Money.of(EUR, 42)).build()); + assertThat(thrown).hasMessageThat().contains("cost must be in the registry's currency"); } @Test public void testFailure_restoreBillingCost_wrongCurrency() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("cost must be in the registry's currency"); - Registry.get("tld").asBuilder().setRestoreBillingCost(Money.of(EUR, 42)).build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> Registry.get("tld").asBuilder().setRestoreBillingCost(Money.of(EUR, 42)).build()); + assertThat(thrown).hasMessageThat().contains("cost must be in the registry's currency"); } @Test public void testFailure_serverStatusChangeBillingCost_wrongCurrency() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("cost must be in the registry's currency"); - Registry.get("tld").asBuilder().setServerStatusChangeBillingCost(Money.of(EUR, 42)).build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + Registry.get("tld") + .asBuilder() + .setServerStatusChangeBillingCost(Money.of(EUR, 42)) + .build()); + assertThat(thrown).hasMessageThat().contains("cost must be in the registry's currency"); } @Test @@ -493,11 +544,15 @@ public class RegistryTest extends EntityTestCase { @Test public void testFailure_eapFee_wrongCurrency() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("All EAP fees must be in the registry's currency"); - Registry.get("tld").asBuilder() - .setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(EUR))) - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + Registry.get("tld") + .asBuilder() + .setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(EUR))) + .build()); + assertThat(thrown).hasMessageThat().contains("All EAP fees must be in the registry's currency"); } @Test diff --git a/javatests/google/registry/model/registry/label/PremiumListTest.java b/javatests/google/registry/model/registry/label/PremiumListTest.java index f609868b5..d3607139b 100644 --- a/javatests/google/registry/model/registry/label/PremiumListTest.java +++ b/javatests/google/registry/model/registry/label/PremiumListTest.java @@ -21,6 +21,8 @@ import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistPremiumList; import static google.registry.testing.DatastoreHelper.persistReservedList; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableList; import google.registry.model.registry.Registry; @@ -29,7 +31,6 @@ import google.registry.testing.AppEngineRule; 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; @@ -37,7 +38,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class PremiumListTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); @Before @@ -56,14 +56,15 @@ public class PremiumListTest { @Test public void testSave_badSyntax() throws Exception { - thrown.expect(IllegalArgumentException.class); - persistPremiumList("gtld1", "lol,nonsense USD,e,e # yup"); + assertThrows( + IllegalArgumentException.class, + () -> persistPremiumList("gtld1", "lol,nonsense USD,e,e # yup")); } @Test public void testSave_invalidCurrencySymbol() throws Exception { - thrown.expect(IllegalArgumentException.class); - persistReservedList("gtld1", "lol,XBTC 200"); + assertThrows( + IllegalArgumentException.class, () -> persistReservedList("gtld1", "lol,XBTC 200")); } @Test @@ -80,13 +81,22 @@ public class PremiumListTest { @Test public void testParse_cannotIncludeDuplicateLabels() { - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "List 'tld' cannot contain duplicate labels. Dupes (with counts) were: [lol x 2]"); - PremiumList.get("tld") - .get() - .parse( - ImmutableList.of( - "lol,USD 100", "rofl,USD 90", "paper,USD 80", "wood,USD 70", "lol,USD 200")); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> + PremiumList.get("tld") + .get() + .parse( + ImmutableList.of( + "lol,USD 100", + "rofl,USD 90", + "paper,USD 80", + "wood,USD 70", + "lol,USD 200"))); + assertThat(thrown) + .hasMessageThat() + .contains( + "List 'tld' cannot contain duplicate labels. Dupes (with counts) were: [lol x 2]"); } } diff --git a/javatests/google/registry/model/registry/label/PremiumListUtilsTest.java b/javatests/google/registry/model/registry/label/PremiumListUtilsTest.java index 0b8be7d04..c057df860 100644 --- a/javatests/google/registry/model/registry/label/PremiumListUtilsTest.java +++ b/javatests/google/registry/model/registry/label/PremiumListUtilsTest.java @@ -34,6 +34,7 @@ import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.loadPremiumListEntries; import static google.registry.testing.DatastoreHelper.persistPremiumList; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.joda.time.Duration.standardMinutes; import com.google.common.collect.ImmutableList; @@ -52,7 +53,6 @@ import org.joda.money.Money; 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; @@ -60,7 +60,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class PremiumListUtilsTest { - @Rule public final ExpectedException thrown = ExpectedException.none(); @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); @Before @@ -112,9 +111,10 @@ public class PremiumListUtilsTest { public void testGetPremiumPrice_throwsExceptionWhenNonExistentPremiumListConfigured() throws Exception { deletePremiumList(PremiumList.get("tld").get()); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Could not load premium list 'tld'"); - getPremiumPrice("blah", Registry.get("tld")); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, () -> getPremiumPrice("blah", Registry.get("tld"))); + assertThat(thrown).hasMessageThat().contains("Could not load premium list 'tld'"); } @Test diff --git a/javatests/google/registry/model/registry/label/ReservedListTest.java b/javatests/google/registry/model/registry/label/ReservedListTest.java index f7e342a5b..ffd330fce 100644 --- a/javatests/google/registry/model/registry/label/ReservedListTest.java +++ b/javatests/google/registry/model/registry/label/ReservedListTest.java @@ -33,6 +33,8 @@ import static google.registry.monitoring.metrics.contrib.LongMetricSubject.asser import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistReservedList; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; @@ -49,7 +51,6 @@ import org.joda.time.DateTime; 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; @@ -60,9 +61,6 @@ public class ReservedListTest { @Rule public final InjectRule inject = new InjectRule(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() @@ -269,9 +267,13 @@ public class ReservedListTest { assertThat(matchesAnchorTenantReservation(InternetDomainName.from("lol.tld"), "foo")).isTrue(); assertThat(matchesAnchorTenantReservation(InternetDomainName.from("lol.tld"), "bar")).isFalse(); persistReservedList("reserved2", "lol,RESERVED_FOR_ANCHOR_TENANT,bar"); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("There are conflicting auth codes for domain: lol.tld"); - matchesAnchorTenantReservation(InternetDomainName.from("lol.tld"), "bar"); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> matchesAnchorTenantReservation(InternetDomainName.from("lol.tld"), "bar")); + assertThat(thrown) + .hasMessageThat() + .contains("There are conflicting auth codes for domain: lol.tld"); } @Test @@ -468,88 +470,120 @@ public class ReservedListTest { @Test public void testSave_badSyntax() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Could not parse line in reserved list"); - persistReservedList("tld", "lol,FULLY_BLOCKED,e,e # yup"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> persistReservedList("tld", "lol,FULLY_BLOCKED,e,e # yup")); + assertThat(thrown).hasMessageThat().contains("Could not parse line in reserved list"); } @Test public void testSave_badReservationType() throws Exception { - thrown.expect(IllegalArgumentException.class); - persistReservedList("tld", "lol,FULLY_BLOCKZ # yup"); + assertThrows( + IllegalArgumentException.class, () -> persistReservedList("tld", "lol,FULLY_BLOCKZ # yup")); } @Test public void testSave_additionalRestrictionWithIncompatibleReservationType() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Only anchor tenant and nameserver restricted reservations " - + "should have restrictions imposed"); - persistResource( - Registry.get("tld") - .asBuilder() - .setReservedLists( - ImmutableSet.of(persistReservedList("reserved1", "lol,FULLY_BLOCKED,foobar1"))) - .build()); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + persistResource( + Registry.get("tld") + .asBuilder() + .setReservedLists( + ImmutableSet.of( + persistReservedList("reserved1", "lol,FULLY_BLOCKED,foobar1"))) + .build())); + assertThat(thrown) + .hasMessageThat() + .contains( + "Only anchor tenant and nameserver restricted reservations " + + "should have restrictions imposed"); } @Test public void testSave_badNameservers_invalidSyntax() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Not a valid domain name: 'ns@.domain.tld'"); - persistReservedList( - "reserved1", - "lol,NAMESERVER_RESTRICTED,ns1.domain.tld:ns2.domain.tld", - "lol1,NAMESERVER_RESTRICTED,ns1.domain.tld:ns@.domain.tld"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + persistReservedList( + "reserved1", + "lol,NAMESERVER_RESTRICTED,ns1.domain.tld:ns2.domain.tld", + "lol1,NAMESERVER_RESTRICTED,ns1.domain.tld:ns@.domain.tld")); + assertThat(thrown).hasMessageThat().contains("Not a valid domain name: 'ns@.domain.tld'"); } @Test public void testSave_badNameservers_tooFewPartsForHostname() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("domain.tld is not a valid nameserver hostname"); - persistReservedList( - "reserved1", - "lol,NAMESERVER_RESTRICTED,ns1.domain.tld:ns2.domain.tld", - "lol1,NAMESERVER_RESTRICTED,ns1.domain.tld:domain.tld"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + persistReservedList( + "reserved1", + "lol,NAMESERVER_RESTRICTED,ns1.domain.tld:ns2.domain.tld", + "lol1,NAMESERVER_RESTRICTED,ns1.domain.tld:domain.tld")); + assertThat(thrown).hasMessageThat().contains("domain.tld is not a valid nameserver hostname"); } @Test public void testSave_noPasswordWithAnchorTenantReservation() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Anchor tenant reservations must have an auth code configured"); - persistResource( - Registry.get("tld") - .asBuilder() - .setReservedLists( - ImmutableSet.of(persistReservedList("reserved1", "lol,RESERVED_FOR_ANCHOR_TENANT"))) - .build()); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + persistResource( + Registry.get("tld") + .asBuilder() + .setReservedLists( + ImmutableSet.of( + persistReservedList("reserved1", "lol,RESERVED_FOR_ANCHOR_TENANT"))) + .build())); + assertThat(thrown) + .hasMessageThat() + .contains("Anchor tenant reservations must have an auth code configured"); } @Test public void testSave_noNameserversWithNameserverRestrictedReservation() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "Nameserver restricted reservations must have at least one nameserver configured"); - persistResource( - Registry.get("tld") - .asBuilder() - .setReservedLists( - ImmutableSet.of(persistReservedList("reserved1", "lol,NAMESERVER_RESTRICTED"))) - .build()); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + persistResource( + Registry.get("tld") + .asBuilder() + .setReservedLists( + ImmutableSet.of( + persistReservedList("reserved1", "lol,NAMESERVER_RESTRICTED"))) + .build())); + assertThat(thrown) + .hasMessageThat() + .contains( + "Nameserver restricted reservations must have at least one nameserver configured"); } @Test public void testParse_cannotIncludeDuplicateLabels() { ReservedList rl = new ReservedList.Builder().setName("blah").build(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage( - "List 'blah' cannot contain duplicate labels. Dupes (with counts) were: [lol x 2]"); - rl.parse( - ImmutableList.of( - "lol,FULLY_BLOCKED", - "rofl,FULLY_BLOCKED", - "paper,FULLY_BLOCKED", - "wood,FULLY_BLOCKED", - "lol,FULLY_BLOCKED")); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> + rl.parse( + ImmutableList.of( + "lol,FULLY_BLOCKED", + "rofl,FULLY_BLOCKED", + "paper,FULLY_BLOCKED", + "wood,FULLY_BLOCKED", + "lol,FULLY_BLOCKED"))); + assertThat(thrown) + .hasMessageThat() + .contains( + "List 'blah' cannot contain duplicate labels. Dupes (with counts) were: [lol x 2]"); } /** Gets the name of a reserved list. */ diff --git a/javatests/google/registry/model/server/KmsSecretRevisionTest.java b/javatests/google/registry/model/server/KmsSecretRevisionTest.java index b0cab7adc..d3c9fa1d6 100644 --- a/javatests/google/registry/model/server/KmsSecretRevisionTest.java +++ b/javatests/google/registry/model/server/KmsSecretRevisionTest.java @@ -17,13 +17,13 @@ package google.registry.model.server; import static com.google.common.truth.Truth.assertThat; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.base.Strings; import google.registry.testing.AppEngineRule; 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 +31,6 @@ import org.junit.runners.JUnit4; public class KmsSecretRevisionTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); - - @Rule public final ExpectedException thrown = ExpectedException.none(); - private KmsSecretRevision secretRevision; @Before @@ -49,15 +46,18 @@ public class KmsSecretRevisionTest { @Test public void test_setEncryptedValue_tooLong_throwsException() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Secret is greater than 67108864 bytes"); - secretRevision = - persistResource( - new KmsSecretRevision.Builder() - .setKmsCryptoKeyVersionName("foo") - .setParent("bar") - .setEncryptedValue(Strings.repeat("a", 64 * 1024 * 1024 + 1)) - .build()); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + secretRevision = + persistResource( + new KmsSecretRevision.Builder() + .setKmsCryptoKeyVersionName("foo") + .setParent("bar") + .setEncryptedValue(Strings.repeat("a", 64 * 1024 * 1024 + 1)) + .build())); + assertThat(thrown).hasMessageThat().contains("Secret is greater than 67108864 bytes"); } @Test diff --git a/javatests/google/registry/model/server/LockTest.java b/javatests/google/registry/model/server/LockTest.java index 4f0273342..860c42d88 100644 --- a/javatests/google/registry/model/server/LockTest.java +++ b/javatests/google/registry/model/server/LockTest.java @@ -14,11 +14,13 @@ package google.registry.model.server; +import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static google.registry.model.server.Lock.LockState.FREE; import static google.registry.model.server.Lock.LockState.IN_USE; import static google.registry.model.server.Lock.LockState.OWNER_DIED; import static google.registry.model.server.Lock.LockState.TIMED_OUT; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -35,7 +37,6 @@ import org.joda.time.Duration; 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; @@ -56,10 +57,6 @@ public class LockTest { @Rule public final InjectRule inject = new InjectRule(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private Optional acquire(String tld, Duration leaseLength, LockState expectedLockState) { Lock.lockMetrics = mock(LockMetrics.class); Optional lock = Lock.acquire(RESOURCE_NAME, tld, leaseLength, requestStatusChecker); @@ -138,8 +135,10 @@ public class LockTest { @Test public void testFailure_emptyResourceName() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("resourceName cannot be null or empty"); - Lock.acquire("", "", TWO_MILLIS, requestStatusChecker); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> Lock.acquire("", "", TWO_MILLIS, requestStatusChecker)); + assertThat(thrown).hasMessageThat().contains("resourceName cannot be null or empty"); } } diff --git a/javatests/google/registry/model/smd/SignedMarkRevocationListTest.java b/javatests/google/registry/model/smd/SignedMarkRevocationListTest.java index db136d33a..513565896 100644 --- a/javatests/google/registry/model/smd/SignedMarkRevocationListTest.java +++ b/javatests/google/registry/model/smd/SignedMarkRevocationListTest.java @@ -17,6 +17,7 @@ package google.registry.model.smd; import static com.google.common.truth.Truth.assertThat; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.model.smd.SignedMarkRevocationList.SHARD_SIZE; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.util.DateTimeUtils.START_OF_TIME; import static org.joda.time.Duration.standardDays; @@ -26,7 +27,6 @@ import google.registry.testing.FakeClock; import org.joda.time.DateTime; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -38,25 +38,24 @@ public class SignedMarkRevocationListTest { public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final FakeClock clock = new FakeClock(DateTime.parse("2013-01-01T00:00:00Z")); @Test public void testUnshardedSaveFails() throws Exception { - thrown.expect(SignedMarkRevocationList.UnshardedSaveException.class); // Our @Entity's @OnSave method will notice that this shouldn't be saved. - ofy() - .transact( - () -> { - SignedMarkRevocationList smdrl = - SignedMarkRevocationList.create( - ofy().getTransactionTime(), ImmutableMap.of("a", ofy().getTransactionTime())); - smdrl.id = 1; // Without an id this won't save anyways. - ofy().saveWithoutBackup().entity(smdrl).now(); - }); + assertThrows( + SignedMarkRevocationList.UnshardedSaveException.class, + () -> + ofy() + .transact( + () -> { + SignedMarkRevocationList smdrl = + SignedMarkRevocationList.create( + ofy().getTransactionTime(), + ImmutableMap.of("a", ofy().getTransactionTime())); + smdrl.id = 1; // Without an id this won't save anyways. + ofy().saveWithoutBackup().entity(smdrl).now(); + })); } @Test @@ -112,9 +111,11 @@ public class SignedMarkRevocationListTest { @Test public void test_isSmdRevoked_null() throws Exception { - thrown.expect(NullPointerException.class); - SignedMarkRevocationList.create(START_OF_TIME, ImmutableMap.of()) - .isSmdRevoked(null, clock.nowUtc()); + assertThrows( + NullPointerException.class, + () -> + SignedMarkRevocationList.create(START_OF_TIME, ImmutableMap.of()) + .isSmdRevoked(null, clock.nowUtc())); } @Test diff --git a/javatests/google/registry/model/tmch/ClaimsListShardTest.java b/javatests/google/registry/model/tmch/ClaimsListShardTest.java index a50fb3df6..ef7e76b6b 100644 --- a/javatests/google/registry/model/tmch/ClaimsListShardTest.java +++ b/javatests/google/registry/model/tmch/ClaimsListShardTest.java @@ -16,6 +16,7 @@ package google.registry.model.tmch; import static com.google.common.truth.Truth.assertThat; import static google.registry.model.ofy.ObjectifyService.ofy; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.util.DateTimeUtils.START_OF_TIME; import static org.joda.time.DateTimeZone.UTC; @@ -32,7 +33,6 @@ import org.joda.time.DateTime; 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; @@ -45,9 +45,6 @@ public class ClaimsListShardTest { .withDatastore() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -58,16 +55,19 @@ public class ClaimsListShardTest { @Test public void test_unshardedSaveFails() throws Exception { - thrown.expect(UnshardedSaveException.class); - ofy() - .transact( - () -> { - ClaimsListShard claimsList = - ClaimsListShard.create(ofy().getTransactionTime(), ImmutableMap.of("a", "b")); - claimsList.id = 1; // Without an id this won't save anyways. - claimsList.parent = ClaimsListRevision.createKey(); - ofy().saveWithoutBackup().entity(claimsList).now(); - }); + assertThrows( + UnshardedSaveException.class, + () -> + ofy() + .transact( + () -> { + ClaimsListShard claimsList = + ClaimsListShard.create( + ofy().getTransactionTime(), ImmutableMap.of("a", "b")); + claimsList.id = 1; // Without an id this won't save anyways. + claimsList.parent = ClaimsListRevision.createKey(); + ofy().saveWithoutBackup().entity(claimsList).now(); + })); } @Test diff --git a/javatests/google/registry/model/translators/CommitLogRevisionsTranslatorFactoryTest.java b/javatests/google/registry/model/translators/CommitLogRevisionsTranslatorFactoryTest.java index f7467abbd..1e11ad24b 100644 --- a/javatests/google/registry/model/translators/CommitLogRevisionsTranslatorFactoryTest.java +++ b/javatests/google/registry/model/translators/CommitLogRevisionsTranslatorFactoryTest.java @@ -35,7 +35,6 @@ import org.joda.time.DateTime; 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; @@ -58,9 +57,6 @@ public class CommitLogRevisionsTranslatorFactoryTest { @Rule public final InjectRule inject = new InjectRule(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final FakeClock clock = new FakeClock(START_TIME); @Before diff --git a/javatests/google/registry/pricing/PricingEngineProxyTest.java b/javatests/google/registry/pricing/PricingEngineProxyTest.java index 0258e832a..3ceae3292 100644 --- a/javatests/google/registry/pricing/PricingEngineProxyTest.java +++ b/javatests/google/registry/pricing/PricingEngineProxyTest.java @@ -21,6 +21,7 @@ import static google.registry.pricing.PricingEngineProxy.isDomainPremium; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistPremiumList; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.DateTimeUtils.START_OF_TIME; import static org.joda.money.CurrencyUnit.USD; @@ -35,17 +36,12 @@ import org.joda.time.DateTime; 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; /** Tests for {@link PricingEngineProxy}. */ @RunWith(JUnit4.class) public class PricingEngineProxyTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() @@ -148,8 +144,12 @@ public class PricingEngineProxyTest { .asBuilder() .setPremiumPricingEngine("fake") .build()); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Could not load pricing engine fake for TLD example"); - getDomainCreateCost("bad.example", clock.nowUtc(), 1); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> getDomainCreateCost("bad.example", clock.nowUtc(), 1)); + assertThat(thrown) + .hasMessageThat() + .contains("Could not load pricing engine fake for TLD example"); } } diff --git a/javatests/google/registry/rdap/RdapSearchPatternTest.java b/javatests/google/registry/rdap/RdapSearchPatternTest.java index 1d94dd967..b34c857c0 100644 --- a/javatests/google/registry/rdap/RdapSearchPatternTest.java +++ b/javatests/google/registry/rdap/RdapSearchPatternTest.java @@ -15,11 +15,10 @@ package google.registry.rdap; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import google.registry.request.HttpException.UnprocessableEntityException; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -27,9 +26,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class RdapSearchPatternTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testNoWildcards_ok() throws Exception { RdapSearchPattern rdapSearchPattern = RdapSearchPattern.create("example.lol", true); @@ -56,20 +52,19 @@ public class RdapSearchPatternTest { @Test public void testMultipleWildcards_unprocessable() throws Exception { - thrown.expect(UnprocessableEntityException.class); - RdapSearchPattern.create("ex*am*.lol", true); + assertThrows( + UnprocessableEntityException.class, () -> RdapSearchPattern.create("ex*am*.lol", true)); } @Test public void testWildcardNotAtEnd_unprocessable() throws Exception { - thrown.expect(UnprocessableEntityException.class); - RdapSearchPattern.create("ex*am", true); + assertThrows(UnprocessableEntityException.class, () -> RdapSearchPattern.create("ex*am", true)); } @Test public void testWildcardNotAtEndWithTld_unprocessable() throws Exception { - thrown.expect(UnprocessableEntityException.class); - RdapSearchPattern.create("ex*am.lol", true); + assertThrows( + UnprocessableEntityException.class, () -> RdapSearchPattern.create("ex*am.lol", true)); } @Test @@ -82,14 +77,14 @@ public class RdapSearchPatternTest { @Test public void testZeroLengthSuffix_unprocessable() throws Exception { - thrown.expect(UnprocessableEntityException.class); - RdapSearchPattern.create("exam*.", true); + assertThrows( + UnprocessableEntityException.class, () -> RdapSearchPattern.create("exam*.", true)); } @Test public void testDisallowedSuffix_unprocessable() throws Exception { - thrown.expect(UnprocessableEntityException.class); - RdapSearchPattern.create("exam*.lol", false); + assertThrows( + UnprocessableEntityException.class, () -> RdapSearchPattern.create("exam*.lol", false)); } @Test diff --git a/javatests/google/registry/rde/EscrowTaskRunnerTest.java b/javatests/google/registry/rde/EscrowTaskRunnerTest.java index 6e73f078e..ce02b5a08 100644 --- a/javatests/google/registry/rde/EscrowTaskRunnerTest.java +++ b/javatests/google/registry/rde/EscrowTaskRunnerTest.java @@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat; import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.joda.time.Duration.standardDays; import static org.joda.time.Duration.standardSeconds; import static org.mockito.Mockito.mock; @@ -37,7 +38,6 @@ import org.joda.time.DateTimeZone; 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; @@ -45,9 +45,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class EscrowTaskRunnerTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() @@ -99,10 +96,13 @@ public class EscrowTaskRunnerTest { clock.setTo(DateTime.parse("2006-06-06T00:30:00Z")); persistResource( Cursor.create(CursorType.RDE_STAGING, DateTime.parse("2006-06-07TZ"), registry)); - thrown.expect(NoContentException.class); - thrown.expectMessage("Already completed"); - runner.lockRunAndRollForward( - task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1)); + NoContentException thrown = + expectThrows( + NoContentException.class, + () -> + runner.lockRunAndRollForward( + task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1))); + assertThat(thrown).hasMessageThat().contains("Already completed"); } @Test @@ -111,10 +111,14 @@ public class EscrowTaskRunnerTest { clock.setTo(DateTime.parse("2006-06-06T00:30:00Z")); persistResource( Cursor.create(CursorType.RDE_STAGING, DateTime.parse("2006-06-06TZ"), registry)); - thrown.expect(ServiceUnavailableException.class); - thrown.expectMessage("Lock in use: " + lockName + " for TLD: lol"); - runner.lockHandler = new FakeLockHandler(false); - runner.lockRunAndRollForward( - task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1)); + ServiceUnavailableException thrown = + expectThrows( + ServiceUnavailableException.class, + () -> { + runner.lockHandler = new FakeLockHandler(false); + runner.lockRunAndRollForward( + task, registry, standardSeconds(30), CursorType.RDE_STAGING, standardDays(1)); + }); + assertThat(thrown).hasMessageThat().contains("Lock in use: " + lockName + " for TLD: lol"); } } diff --git a/javatests/google/registry/rde/GhostrydeTest.java b/javatests/google/registry/rde/GhostrydeTest.java index d18ba5505..642faf85c 100644 --- a/javatests/google/registry/rde/GhostrydeTest.java +++ b/javatests/google/registry/rde/GhostrydeTest.java @@ -17,6 +17,8 @@ package google.registry.rde; import static com.google.common.base.Strings.repeat; import static com.google.common.truth.Truth.assertThat; import static google.registry.keyring.api.PgpHelper.KeyRequirement.ENCRYPT; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; @@ -42,7 +44,6 @@ import org.junit.Test; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; /** Unit tests for {@link Ghostryde}. */ @@ -50,9 +51,6 @@ import org.junit.runner.RunWith; @SuppressWarnings("resource") public class GhostrydeTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @@ -194,11 +192,15 @@ public class GhostrydeTest { korruption(ciphertext, ciphertext.length / 2); ByteArrayInputStream bsIn = new ByteArrayInputStream(ciphertext); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("tampering"); - try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) { - ByteStreams.copy(decryptor, ByteStreams.nullOutputStream()); - } + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> { + try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) { + ByteStreams.copy(decryptor, ByteStreams.nullOutputStream()); + } + }); + assertThat(thrown).hasMessageThat().contains("tampering"); } @Theory @@ -223,10 +225,13 @@ public class GhostrydeTest { korruption(ciphertext, ciphertext.length / 2); ByteArrayInputStream bsIn = new ByteArrayInputStream(ciphertext); - thrown.expect(PGPException.class); - try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) { - ByteStreams.copy(decryptor, ByteStreams.nullOutputStream()); - } + assertThrows( + PGPException.class, + () -> { + try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) { + ByteStreams.copy(decryptor, ByteStreams.nullOutputStream()); + } + }); } @Test @@ -248,12 +253,17 @@ public class GhostrydeTest { } ByteArrayInputStream bsIn = new ByteArrayInputStream(bsOut.toByteArray()); - thrown.expect(PGPException.class); - thrown.expectMessage( - "Message was encrypted for keyid a59c132f3589a1d5 but ours is c9598c84ec70b9fd"); - try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) { - ByteStreams.copy(decryptor, ByteStreams.nullOutputStream()); - } + PGPException thrown = + expectThrows( + PGPException.class, + () -> { + try (Ghostryde.Decryptor decryptor = ghost.openDecryptor(bsIn, privateKey)) { + ByteStreams.copy(decryptor, ByteStreams.nullOutputStream()); + } + }); + assertThat(thrown) + .hasMessageThat() + .contains("Message was encrypted for keyid a59c132f3589a1d5 but ours is c9598c84ec70b9fd"); } @Test diff --git a/javatests/google/registry/rde/HostResourceToXjcConverterTest.java b/javatests/google/registry/rde/HostResourceToXjcConverterTest.java index e0926a291..729a0573c 100644 --- a/javatests/google/registry/rde/HostResourceToXjcConverterTest.java +++ b/javatests/google/registry/rde/HostResourceToXjcConverterTest.java @@ -17,6 +17,7 @@ package google.registry.rde; import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.newDomainResource; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.xjc.XjcXmlTransformer.marshalStrict; import static java.nio.charset.StandardCharsets.UTF_8; @@ -36,7 +37,6 @@ import org.joda.time.DateTime; 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; @@ -54,9 +54,6 @@ public class HostResourceToXjcConverterTest { .withDatastore() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Before public void init() { createTld("foobar"); @@ -192,20 +189,22 @@ public class HostResourceToXjcConverterTest { @Test public void testHostStatusValueIsInvalid() throws Exception { - thrown.expect(IllegalArgumentException.class); - HostResourceToXjcConverter.convertExternalHost( - new HostResource.Builder() - .setCreationClientId("LawyerCat") - .setCreationTimeForTest(DateTime.parse("1900-01-01T00:00:00Z")) - .setPersistedCurrentSponsorClientId("BusinessCat") - .setFullyQualifiedHostName("ns1.love.lol") - .setInetAddresses(ImmutableSet.of(InetAddresses.forString("cafe::abba"))) - .setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z")) - .setLastEppUpdateClientId("CeilingCat") - .setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z")) - .setRepoId("2-LOL") - .setStatusValues(ImmutableSet.of(StatusValue.SERVER_HOLD)) // <-- OOPS - .build()); + assertThrows( + IllegalArgumentException.class, + () -> + HostResourceToXjcConverter.convertExternalHost( + new HostResource.Builder() + .setCreationClientId("LawyerCat") + .setCreationTimeForTest(DateTime.parse("1900-01-01T00:00:00Z")) + .setPersistedCurrentSponsorClientId("BusinessCat") + .setFullyQualifiedHostName("ns1.love.lol") + .setInetAddresses(ImmutableSet.of(InetAddresses.forString("cafe::abba"))) + .setLastTransferTime(DateTime.parse("1910-01-01T00:00:00Z")) + .setLastEppUpdateClientId("CeilingCat") + .setLastEppUpdateTime(DateTime.parse("1920-01-01T00:00:00Z")) + .setRepoId("2-LOL") + .setStatusValues(ImmutableSet.of(StatusValue.SERVER_HOLD)) // <-- OOPS + .build())); } @Test diff --git a/javatests/google/registry/rde/RdeReportActionTest.java b/javatests/google/registry/rde/RdeReportActionTest.java index 816a36e54..e45b5ed7e 100644 --- a/javatests/google/registry/rde/RdeReportActionTest.java +++ b/javatests/google/registry/rde/RdeReportActionTest.java @@ -21,6 +21,8 @@ import static google.registry.model.ofy.ObjectifyService.ofy; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.GcsTestingUtils.writeGcsFile; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_OK; import static org.joda.time.DateTimeZone.UTC; @@ -65,7 +67,6 @@ import org.joda.time.DateTime; 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; import org.mockito.ArgumentCaptor; @@ -77,10 +78,6 @@ public class RdeReportActionTest { private static final ByteSource REPORT_XML = RdeTestData.loadBytes("report.xml"); private static final ByteSource IIRDEA_BAD_XML = RdeTestData.loadBytes("iirdea_bad.xml"); private static final ByteSource IIRDEA_GOOD_XML = RdeTestData.loadBytes("iirdea_good.xml"); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); @@ -175,17 +172,19 @@ public class RdeReportActionTest { when(httpResponse.getResponseCode()).thenReturn(SC_BAD_REQUEST); when(httpResponse.getContent()).thenReturn(IIRDEA_BAD_XML.read()); when(urlFetchService.fetch(request.capture())).thenReturn(httpResponse); - thrown.expect(InternalServerErrorException.class); - thrown.expectMessage("The structure of the report is invalid."); - createAction().runWithLock(loadRdeReportCursor()); + InternalServerErrorException thrown = + expectThrows( + InternalServerErrorException.class, + () -> createAction().runWithLock(loadRdeReportCursor())); + assertThat(thrown).hasMessageThat().contains("The structure of the report is invalid."); } @Test public void testRunWithLock_fetchFailed_throwsRuntimeException() throws Exception { class ExpectedThrownException extends RuntimeException {} when(urlFetchService.fetch(any(HTTPRequest.class))).thenThrow(new ExpectedThrownException()); - thrown.expect(ExpectedThrownException.class); - createAction().runWithLock(loadRdeReportCursor()); + assertThrows( + ExpectedThrownException.class, () -> createAction().runWithLock(loadRdeReportCursor())); } @Test diff --git a/javatests/google/registry/rde/RdeStagingActionTest.java b/javatests/google/registry/rde/RdeStagingActionTest.java index 35ba811e7..d03a03dfb 100644 --- a/javatests/google/registry/rde/RdeStagingActionTest.java +++ b/javatests/google/registry/rde/RdeStagingActionTest.java @@ -26,6 +26,7 @@ import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResourceWithCommitLog; import static google.registry.testing.GcsTestingUtils.readGcsFile; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.TaskQueueHelper.assertAtLeastOneTaskIsEnqueued; import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; @@ -92,7 +93,6 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -108,9 +108,6 @@ public class RdeStagingActionTest extends MapreduceTestCase { @Rule public final InjectRule inject = new InjectRule(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final FakeClock clock = new FakeClock(); private final FakeResponse response = new FakeResponse(); private final GcsService gcsService = GcsServiceFactory.createGcsService(); @@ -162,8 +159,7 @@ public class RdeStagingActionTest extends MapreduceTestCase { createTldWithEscrowEnabled("lol"); clock.setTo(DateTime.parse("2000-01-01TZ")); action.modeStrings = ImmutableSet.of("full"); - thrown.expect(BadRequestException.class); - action.run(); + assertThrows(BadRequestException.class, () -> action.run()); } @Test @@ -171,8 +167,7 @@ public class RdeStagingActionTest extends MapreduceTestCase { createTldWithEscrowEnabled("lol"); clock.setTo(DateTime.parse("2000-01-01TZ")); action.tlds = ImmutableSet.of("tld"); - thrown.expect(BadRequestException.class); - action.run(); + assertThrows(BadRequestException.class, () -> action.run()); } @Test @@ -180,8 +175,7 @@ public class RdeStagingActionTest extends MapreduceTestCase { createTldWithEscrowEnabled("lol"); clock.setTo(DateTime.parse("2000-01-01TZ")); action.watermarks = ImmutableSet.of(clock.nowUtc()); - thrown.expect(BadRequestException.class); - action.run(); + assertThrows(BadRequestException.class, () -> action.run()); } @Test @@ -189,8 +183,7 @@ public class RdeStagingActionTest extends MapreduceTestCase { createTldWithEscrowEnabled("lol"); clock.setTo(DateTime.parse("2000-01-01TZ")); action.revision = Optional.of(42); - thrown.expect(BadRequestException.class); - action.run(); + assertThrows(BadRequestException.class, () -> action.run()); } @Test @@ -248,8 +241,7 @@ public class RdeStagingActionTest extends MapreduceTestCase { action.modeStrings = ImmutableSet.of(); action.tlds = ImmutableSet.of("lol"); action.watermarks = ImmutableSet.of(clock.nowUtc()); - thrown.expect(BadRequestException.class); - action.run(); + assertThrows(BadRequestException.class, () -> action.run()); } @Test @@ -261,8 +253,7 @@ public class RdeStagingActionTest extends MapreduceTestCase { action.modeStrings = ImmutableSet.of("full", "thing"); action.tlds = ImmutableSet.of("lol"); action.watermarks = ImmutableSet.of(clock.nowUtc()); - thrown.expect(BadRequestException.class); - action.run(); + assertThrows(BadRequestException.class, () -> action.run()); } @Test @@ -274,8 +265,7 @@ public class RdeStagingActionTest extends MapreduceTestCase { action.modeStrings = ImmutableSet.of("full"); action.tlds = ImmutableSet.of(); action.watermarks = ImmutableSet.of(clock.nowUtc()); - thrown.expect(BadRequestException.class); - action.run(); + assertThrows(BadRequestException.class, () -> action.run()); } @Test @@ -287,8 +277,7 @@ public class RdeStagingActionTest extends MapreduceTestCase { action.modeStrings = ImmutableSet.of("full"); action.tlds = ImmutableSet.of("lol"); action.watermarks = ImmutableSet.of(); - thrown.expect(BadRequestException.class); - action.run(); + assertThrows(BadRequestException.class, () -> action.run()); } @Test @@ -300,8 +289,7 @@ public class RdeStagingActionTest extends MapreduceTestCase { action.modeStrings = ImmutableSet.of("full"); action.tlds = ImmutableSet.of("lol"); action.watermarks = ImmutableSet.of(DateTime.parse("2001-01-01T01:36:45Z")); - thrown.expect(BadRequestException.class); - action.run(); + assertThrows(BadRequestException.class, () -> action.run()); } @Test @@ -314,8 +302,7 @@ public class RdeStagingActionTest extends MapreduceTestCase { action.tlds = ImmutableSet.of("lol"); action.watermarks = ImmutableSet.of(DateTime.parse("2001-01-01T00:00:00Z")); action.revision = Optional.of(-1); - thrown.expect(BadRequestException.class); - action.run(); + assertThrows(BadRequestException.class, () -> action.run()); } @Test diff --git a/javatests/google/registry/rde/RdeUploadActionTest.java b/javatests/google/registry/rde/RdeUploadActionTest.java index 790bb451d..16d23ce5c 100644 --- a/javatests/google/registry/rde/RdeUploadActionTest.java +++ b/javatests/google/registry/rde/RdeUploadActionTest.java @@ -24,6 +24,7 @@ import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistSimpleResource; import static google.registry.testing.GcsTestingUtils.readGcsFile; import static google.registry.testing.GcsTestingUtils.writeGcsFile; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.SystemInfo.hasCommand; import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; @@ -86,7 +87,6 @@ import org.joda.time.DateTime; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -113,10 +113,6 @@ public class RdeUploadActionTest { new GcsFilename("bucket", "tld_2010-10-17_full_S1_R1.xml.length"); private static final GcsFilename REPORT_R1_FILE = new GcsFilename("bucket", "tld_2010-10-17_full_S1_R1-report.xml.ghostryde"); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final SftpServerRule sftpd = new SftpServerRule(); @@ -312,9 +308,9 @@ public class RdeUploadActionTest { Cursor.create(CursorType.RDE_STAGING, stagingCursor, Registry.get("tld"))); RdeUploadAction action = createAction(uploadUrl); action.lazyJsch = Lazies.of(createThrowingJSchSpy(action.lazyJsch.get(), 3)); - thrown.expect(RuntimeException.class); - thrown.expectMessage("The crow flies in square circles."); - action.runWithLock(uploadCursor); + RuntimeException thrown = + expectThrows(RuntimeException.class, () -> action.runWithLock(uploadCursor)); + assertThat(thrown).hasMessageThat().contains("The crow flies in square circles."); } @Test @@ -387,9 +383,10 @@ public class RdeUploadActionTest { DateTime uploadCursor = DateTime.parse("2010-10-17TZ"); persistResource( Cursor.create(CursorType.RDE_STAGING, stagingCursor, Registry.get("tld"))); - thrown.expect(ServiceUnavailableException.class); - thrown.expectMessage("Waiting for RdeStagingAction to complete"); - createAction(null).runWithLock(uploadCursor); + ServiceUnavailableException thrown = + expectThrows( + ServiceUnavailableException.class, () -> createAction(null).runWithLock(uploadCursor)); + assertThat(thrown).hasMessageThat().contains("Waiting for RdeStagingAction to complete"); } private String slurp(InputStream is) throws FileNotFoundException, IOException { diff --git a/javatests/google/registry/reporting/IcannHttpReporterTest.java b/javatests/google/registry/reporting/IcannHttpReporterTest.java index a18e47d90..1166354df 100644 --- a/javatests/google/registry/reporting/IcannHttpReporterTest.java +++ b/javatests/google/registry/reporting/IcannHttpReporterTest.java @@ -18,6 +18,7 @@ import static com.google.common.net.MediaType.CSV_UTF_8; import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8; import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatastoreHelper.createTld; +import static google.registry.testing.JUnitBackports.expectThrows; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.api.client.http.LowLevelHttpRequest; @@ -35,7 +36,6 @@ import java.util.Map; 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; @@ -50,9 +50,6 @@ public class IcannHttpReporterTest { private static final byte[] FAKE_PAYLOAD = "test,csv\n1,2".getBytes(UTF_8); private MockLowLevelHttpRequest mockRequest; - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public AppEngineRule appEngineRule = new AppEngineRule.Builder().withDatastore().build(); private MockHttpTransport createMockTransport (final ByteSource iirdeaResponse) { @@ -127,36 +124,60 @@ public class IcannHttpReporterTest { @Test public void testFail_invalidFilename_nonSixDigitYearMonth() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "Expected file format: tld-reportType-yyyyMM.csv, got test-transactions-20176.csv instead"); - IcannHttpReporter reporter = createReporter(); - reporter.send(FAKE_PAYLOAD, "test-transactions-20176.csv"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> { + IcannHttpReporter reporter = createReporter(); + reporter.send(FAKE_PAYLOAD, "test-transactions-20176.csv"); + }); + assertThat(thrown) + .hasMessageThat() + .contains( + "Expected file format: tld-reportType-yyyyMM.csv, " + + "got test-transactions-20176.csv instead"); } @Test public void testFail_invalidFilename_notActivityOrTransactions() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "Expected file format: tld-reportType-yyyyMM.csv, got test-invalid-201706.csv instead"); - IcannHttpReporter reporter = createReporter(); - reporter.send(FAKE_PAYLOAD, "test-invalid-201706.csv"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> { + IcannHttpReporter reporter = createReporter(); + reporter.send(FAKE_PAYLOAD, "test-invalid-201706.csv"); + }); + assertThat(thrown) + .hasMessageThat() + .contains( + "Expected file format: tld-reportType-yyyyMM.csv, got test-invalid-201706.csv instead"); } @Test public void testFail_invalidFilename_invalidTldName() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "Expected file format: tld-reportType-yyyyMM.csv, got n!-n-activity-201706.csv instead"); - IcannHttpReporter reporter = createReporter(); - reporter.send(FAKE_PAYLOAD, "n!-n-activity-201706.csv"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> { + IcannHttpReporter reporter = createReporter(); + reporter.send(FAKE_PAYLOAD, "n!-n-activity-201706.csv"); + }); + assertThat(thrown) + .hasMessageThat() + .contains( + "Expected file format: tld-reportType-yyyyMM.csv, " + + "got n!-n-activity-201706.csv instead"); } @Test public void testFail_invalidFilename_tldDoesntExist() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("TLD hello does not exist"); - IcannHttpReporter reporter = createReporter(); - reporter.send(FAKE_PAYLOAD, "hello-activity-201706.csv"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> { + IcannHttpReporter reporter = createReporter(); + reporter.send(FAKE_PAYLOAD, "hello-activity-201706.csv"); + }); + assertThat(thrown).hasMessageThat().contains("TLD hello does not exist"); } } diff --git a/javatests/google/registry/reporting/IcannReportingModuleTest.java b/javatests/google/registry/reporting/IcannReportingModuleTest.java index 1050b8665..c1a78dc73 100644 --- a/javatests/google/registry/reporting/IcannReportingModuleTest.java +++ b/javatests/google/registry/reporting/IcannReportingModuleTest.java @@ -15,6 +15,7 @@ package google.registry.reporting; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -27,9 +28,7 @@ import javax.servlet.http.HttpServletRequest; import org.joda.time.DateTime; import org.joda.time.YearMonth; 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; @@ -39,9 +38,6 @@ public class IcannReportingModuleTest { HttpServletRequest req = mock(HttpServletRequest.class); Clock clock; - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Before public void setUp() { clock = new FakeClock(DateTime.parse("2017-07-01TZ")); @@ -56,9 +52,12 @@ public class IcannReportingModuleTest { @Test public void testInvalidYearMonthParameter_throwsException() { when(req.getParameter("yearMonth")).thenReturn("201705"); - thrown.expect(BadRequestException.class); - thrown.expectMessage("yearMonth must be in yyyy-MM format, got 201705 instead"); - IcannReportingModule.provideYearMonthOptional(req); + BadRequestException thrown = + expectThrows( + BadRequestException.class, () -> IcannReportingModule.provideYearMonthOptional(req)); + assertThat(thrown) + .hasMessageThat() + .contains("yearMonth must be in yyyy-MM format, got 201705 instead"); } @Test @@ -88,9 +87,14 @@ public class IcannReportingModuleTest { @Test public void testInvalidSubdir_throwsException() { - thrown.expect(BadRequestException.class); - thrown.expectMessage("subdir must not start or end with a \"/\", got /whoops instead."); - IcannReportingModule.provideSubdir(Optional.of("/whoops"), new YearMonth(2017, 6)); + BadRequestException thrown = + expectThrows( + BadRequestException.class, + () -> + IcannReportingModule.provideSubdir(Optional.of("/whoops"), new YearMonth(2017, 6))); + assertThat(thrown) + .hasMessageThat() + .contains("subdir must not start or end with a \"/\", got /whoops instead."); } @Test diff --git a/javatests/google/registry/request/JsonResponseTest.java b/javatests/google/registry/request/JsonResponseTest.java index 1f95d2487..b4988b9cd 100644 --- a/javatests/google/registry/request/JsonResponseTest.java +++ b/javatests/google/registry/request/JsonResponseTest.java @@ -21,9 +21,7 @@ import com.google.common.collect.ImmutableMap; import google.registry.testing.FakeResponse; import java.util.Map; import org.json.simple.JSONValue; -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 +29,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class JsonResponseTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - FakeResponse fakeResponse = new FakeResponse(); JsonResponse jsonResponse = new JsonResponse(fakeResponse); diff --git a/javatests/google/registry/request/RequestModuleTest.java b/javatests/google/registry/request/RequestModuleTest.java index cf99f0dad..69bdc30c2 100644 --- a/javatests/google/registry/request/RequestModuleTest.java +++ b/javatests/google/registry/request/RequestModuleTest.java @@ -16,23 +16,19 @@ package google.registry.request; import static com.google.common.truth.Truth.assertThat; import static google.registry.request.RequestModule.provideJsonPayload; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.net.MediaType; import google.registry.request.HttpException.BadRequestException; import google.registry.request.HttpException.UnsupportedMediaTypeException; -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 RequestModule}. */ @RunWith(JUnit4.class) public final class RequestModuleTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testProvideJsonPayload() throws Exception { assertThat(provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":\"v\"}")) @@ -47,27 +43,30 @@ public final class RequestModuleTest { @Test public void testProvideJsonPayload_malformedInput_throws500() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage("Malformed JSON"); - provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":"); + BadRequestException thrown = + expectThrows( + BadRequestException.class, () -> provideJsonPayload(MediaType.JSON_UTF_8, "{\"k\":")); + assertThat(thrown).hasMessageThat().contains("Malformed JSON"); } @Test public void testProvideJsonPayload_emptyInput_throws500() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage("Malformed JSON"); - provideJsonPayload(MediaType.JSON_UTF_8, ""); + BadRequestException thrown = + expectThrows(BadRequestException.class, () -> provideJsonPayload(MediaType.JSON_UTF_8, "")); + assertThat(thrown).hasMessageThat().contains("Malformed JSON"); } @Test public void testProvideJsonPayload_nonJsonContentType_throws415() throws Exception { - thrown.expect(UnsupportedMediaTypeException.class); - provideJsonPayload(MediaType.PLAIN_TEXT_UTF_8, "{}"); + assertThrows( + UnsupportedMediaTypeException.class, + () -> provideJsonPayload(MediaType.PLAIN_TEXT_UTF_8, "{}")); } @Test public void testProvideJsonPayload_contentTypeWithWeirdParam_throws415() throws Exception { - thrown.expect(UnsupportedMediaTypeException.class); - provideJsonPayload(MediaType.JSON_UTF_8.withParameter("omg", "handel"), "{}"); + assertThrows( + UnsupportedMediaTypeException.class, + () -> provideJsonPayload(MediaType.JSON_UTF_8.withParameter("omg", "handel"), "{}")); } } diff --git a/javatests/google/registry/request/RequestParametersTest.java b/javatests/google/registry/request/RequestParametersTest.java index 7f0f3403f..2c9395d0e 100644 --- a/javatests/google/registry/request/RequestParametersTest.java +++ b/javatests/google/registry/request/RequestParametersTest.java @@ -23,6 +23,7 @@ import static google.registry.request.RequestParameters.extractOptionalEnumParam import static google.registry.request.RequestParameters.extractOptionalParameter; import static google.registry.request.RequestParameters.extractRequiredDatetimeParameter; import static google.registry.request.RequestParameters.extractRequiredParameter; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -30,19 +31,13 @@ import com.google.common.collect.ImmutableMap; import google.registry.request.HttpException.BadRequestException; import javax.servlet.http.HttpServletRequest; import org.joda.time.DateTime; -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 RequestParameters}. */ @RunWith(JUnit4.class) public class RequestParametersTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final HttpServletRequest req = mock(HttpServletRequest.class); @Test @@ -53,17 +48,17 @@ public class RequestParametersTest { @Test public void testExtractRequiredParameter_notPresent_throwsBadRequest() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage("spin"); - extractRequiredParameter(req, "spin"); + BadRequestException thrown = + expectThrows(BadRequestException.class, () -> extractRequiredParameter(req, "spin")); + assertThat(thrown).hasMessageThat().contains("spin"); } @Test public void testExtractRequiredParameter_empty_throwsBadRequest() throws Exception { when(req.getParameter("spin")).thenReturn(""); - thrown.expect(BadRequestException.class); - thrown.expectMessage("spin"); - extractRequiredParameter(req, "spin"); + BadRequestException thrown = + expectThrows(BadRequestException.class, () -> extractRequiredParameter(req, "spin")); + assertThat(thrown).hasMessageThat().contains("spin"); } @Test @@ -146,9 +141,10 @@ public class RequestParametersTest { @Test public void testExtractEnumValue_nonExistentValue_throwsBadRequest() throws Exception { when(req.getParameter("spin")).thenReturn("sing"); - thrown.expect(BadRequestException.class); - thrown.expectMessage("spin"); - extractEnumParameter(req, Club.class, "spin"); + BadRequestException thrown = + expectThrows( + BadRequestException.class, () -> extractEnumParameter(req, Club.class, "spin")); + assertThat(thrown).hasMessageThat().contains("spin"); } @Test @@ -166,9 +162,10 @@ public class RequestParametersTest { @Test public void testOptionalExtractEnumValue_nonExistentValue_throwsBadRequest() throws Exception { when(req.getParameter("spin")).thenReturn("sing"); - thrown.expect(BadRequestException.class); - thrown.expectMessage("spin"); - extractOptionalEnumParameter(req, Club.class, "spin"); + BadRequestException thrown = + expectThrows( + BadRequestException.class, () -> extractOptionalEnumParameter(req, Club.class, "spin")); + assertThat(thrown).hasMessageThat().contains("spin"); } @Test @@ -181,9 +178,10 @@ public class RequestParametersTest { @Test public void testExtractRequiredDatetimeParameter_badValue_throwsBadRequest() throws Exception { when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock"); - thrown.expect(BadRequestException.class); - thrown.expectMessage("timeParam"); - extractRequiredDatetimeParameter(req, "timeParam"); + BadRequestException thrown = + expectThrows( + BadRequestException.class, () -> extractRequiredDatetimeParameter(req, "timeParam")); + assertThat(thrown).hasMessageThat().contains("timeParam"); } @Test @@ -196,9 +194,10 @@ public class RequestParametersTest { @Test public void testExtractOptionalDatetimeParameter_badValue_throwsBadRequest() throws Exception { when(req.getParameter("timeParam")).thenReturn("Tuesday at three o'clock"); - thrown.expect(BadRequestException.class); - thrown.expectMessage("timeParam"); - extractOptionalDatetimeParameter(req, "timeParam"); + BadRequestException thrown = + expectThrows( + BadRequestException.class, () -> extractOptionalDatetimeParameter(req, "timeParam")); + assertThat(thrown).hasMessageThat().contains("timeParam"); } @Test @@ -209,8 +208,9 @@ public class RequestParametersTest { @Test public void testExtractRequiredDatetimeParameter_noValue_throwsBadRequest() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage("timeParam"); - extractRequiredDatetimeParameter(req, "timeParam"); + BadRequestException thrown = + expectThrows( + BadRequestException.class, () -> extractRequiredDatetimeParameter(req, "timeParam")); + assertThat(thrown).hasMessageThat().contains("timeParam"); } } diff --git a/javatests/google/registry/request/ResponseImplTest.java b/javatests/google/registry/request/ResponseImplTest.java index e487ebc81..e120e4648 100644 --- a/javatests/google/registry/request/ResponseImplTest.java +++ b/javatests/google/registry/request/ResponseImplTest.java @@ -24,9 +24,7 @@ import static org.mockito.Mockito.when; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.http.HttpServletResponse; -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 +32,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class ResponseImplTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final HttpServletResponse rsp = mock(HttpServletResponse.class); @Test diff --git a/javatests/google/registry/request/RouterTest.java b/javatests/google/registry/request/RouterTest.java index e99848ea6..18d5306f7 100644 --- a/javatests/google/registry/request/RouterTest.java +++ b/javatests/google/registry/request/RouterTest.java @@ -17,13 +17,12 @@ package google.registry.request; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static google.registry.request.auth.Auth.AUTH_INTERNAL_ONLY; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.base.Function; import java.util.Optional; import java.util.concurrent.Callable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -31,18 +30,17 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class RouterTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - //////////////////////////////////////////////////////////////////////////////////////////////// public interface Empty {} @Test public void testRoute_noRoutes_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("No routes found for class: google.registry.request.RouterTest.Empty"); - Router.create(Empty.class); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> Router.create(Empty.class)); + assertThat(thrown) + .hasMessageThat() + .contains("No routes found for class: google.registry.request.RouterTest.Empty"); } //////////////////////////////////////////////////////////////////////////////////////////////// @@ -144,10 +142,13 @@ public final class RouterTest { @Test public void testRoute_methodsInComponentAreIgnored_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "No routes found for class: google.registry.request.RouterTest.WeirdMethodsComponent"); - Router.create(WeirdMethodsComponent.class); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> Router.create(WeirdMethodsComponent.class)); + assertThat(thrown) + .hasMessageThat() + .contains( + "No routes found for class: google.registry.request.RouterTest.WeirdMethodsComponent"); } //////////////////////////////////////////////////////////////////////////////////////////////// @@ -171,8 +172,8 @@ public final class RouterTest { @Test public void testCreate_twoTasksWithSameMethodAndPath_resultsInError() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Multiple entries with same key"); - Router.create(DuplicateComponent.class); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> Router.create(DuplicateComponent.class)); + assertThat(thrown).hasMessageThat().contains("Multiple entries with same key"); } } diff --git a/javatests/google/registry/request/auth/RequestAuthenticatorTest.java b/javatests/google/registry/request/auth/RequestAuthenticatorTest.java index cb41aa25b..f9a50b9a6 100644 --- a/javatests/google/registry/request/auth/RequestAuthenticatorTest.java +++ b/javatests/google/registry/request/auth/RequestAuthenticatorTest.java @@ -17,6 +17,7 @@ package google.registry.request.auth; import static com.google.common.net.HttpHeaders.AUTHORIZATION; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; @@ -38,7 +39,6 @@ import javax.servlet.http.HttpServletRequest; 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; @@ -48,10 +48,6 @@ public class RequestAuthenticatorTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder().build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private static final AuthSettings AUTH_NONE = AuthSettings.create( ImmutableList.of(AuthMethod.INTERNAL), AuthLevel.NONE, @@ -391,44 +387,55 @@ public class RequestAuthenticatorTest { @Test public void testCheckAuthConfig_NoMethods_failure() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Must specify at least one auth method"); - - RequestAuthenticator.checkAuthConfig(AUTH_NO_METHODS); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> RequestAuthenticator.checkAuthConfig(AUTH_NO_METHODS)); + assertThat(thrown).hasMessageThat().contains("Must specify at least one auth method"); } @Test public void testCheckAuthConfig_WrongMethodOrdering_failure() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown - .expectMessage("Auth methods must be unique and strictly in order - INTERNAL, API, LEGACY"); - - RequestAuthenticator.checkAuthConfig(AUTH_WRONG_METHOD_ORDERING); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> RequestAuthenticator.checkAuthConfig(AUTH_WRONG_METHOD_ORDERING)); + assertThat(thrown) + .hasMessageThat() + .contains("Auth methods must be unique and strictly in order - INTERNAL, API, LEGACY"); } @Test public void testCheckAuthConfig_DuplicateMethods_failure() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown - .expectMessage("Auth methods must be unique and strictly in order - INTERNAL, API, LEGACY"); - - RequestAuthenticator.checkAuthConfig(AUTH_DUPLICATE_METHODS); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> RequestAuthenticator.checkAuthConfig(AUTH_DUPLICATE_METHODS)); + assertThat(thrown) + .hasMessageThat() + .contains("Auth methods must be unique and strictly in order - INTERNAL, API, LEGACY"); } @Test public void testCheckAuthConfig_InternalWithUser_failure() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Actions with INTERNAL auth method may not require USER auth level"); - - RequestAuthenticator.checkAuthConfig(AUTH_INTERNAL_WITH_USER); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> RequestAuthenticator.checkAuthConfig(AUTH_INTERNAL_WITH_USER)); + assertThat(thrown) + .hasMessageThat() + .contains("Actions with INTERNAL auth method may not require USER auth level"); } @Test public void testCheckAuthConfig_WronglyIgnoringUser_failure() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "Actions with auth methods beyond INTERNAL must not specify the IGNORED user policy"); - - RequestAuthenticator.checkAuthConfig(AUTH_WRONGLY_IGNORING_USER); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> RequestAuthenticator.checkAuthConfig(AUTH_WRONGLY_IGNORING_USER)); + assertThat(thrown) + .hasMessageThat() + .contains( + "Actions with auth methods beyond INTERNAL must not specify the IGNORED user policy"); } } diff --git a/javatests/google/registry/request/lock/LockHandlerImplTest.java b/javatests/google/registry/request/lock/LockHandlerImplTest.java index b4799fb57..b99939fd5 100644 --- a/javatests/google/registry/request/lock/LockHandlerImplTest.java +++ b/javatests/google/registry/request/lock/LockHandlerImplTest.java @@ -29,7 +29,6 @@ import org.joda.time.Duration; 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; @@ -43,9 +42,6 @@ public final class LockHandlerImplTest { public final AppEngineRule appEngine = AppEngineRule.builder() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private static class CountingCallable implements Callable { int numCalled = 0; diff --git a/javatests/google/registry/storage/drive/DriveConnectionTest.java b/javatests/google/registry/storage/drive/DriveConnectionTest.java index ed902d457..353e0cdce 100644 --- a/javatests/google/registry/storage/drive/DriveConnectionTest.java +++ b/javatests/google/registry/storage/drive/DriveConnectionTest.java @@ -16,6 +16,7 @@ package google.registry.storage.drive; import static com.google.common.io.ByteStreams.toByteArray; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; @@ -37,9 +38,7 @@ import com.google.common.net.MediaType; import java.util.Arrays; import java.util.List; 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; import org.mockito.ArgumentMatcher; @@ -47,10 +46,6 @@ import org.mockito.ArgumentMatcher; /** Tests for {@link DriveConnection}.*/ @RunWith(JUnit4.class) public class DriveConnectionTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final Drive drive = mock(Drive.class); private final Files files = mock(Files.class); private final Children children = mock(Children.class); @@ -215,10 +210,17 @@ public class DriveConnectionTest { new ChildReference().setId("id2"))) .setNextPageToken(null); when(childrenList.execute()).thenReturn(childList); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Could not update file 'title' in Drive folder id 'driveFolderId' " - + "because multiple files with that name already exist."); - driveConnection.createOrUpdateFile("title", MediaType.WEBM_VIDEO, "driveFolderId", DATA); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> + driveConnection.createOrUpdateFile( + "title", MediaType.WEBM_VIDEO, "driveFolderId", DATA)); + assertThat(thrown) + .hasMessageThat() + .contains( + "Could not update file 'title' in Drive folder id 'driveFolderId' " + + "because multiple files with that name already exist."); } @Test diff --git a/javatests/google/registry/tldconfig/idn/IdnTableTest.java b/javatests/google/registry/tldconfig/idn/IdnTableTest.java index 9a48fca52..251fb8105 100644 --- a/javatests/google/registry/tldconfig/idn/IdnTableTest.java +++ b/javatests/google/registry/tldconfig/idn/IdnTableTest.java @@ -15,23 +15,18 @@ package google.registry.tldconfig.idn; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableList; import java.net.URI; import java.util.Optional; -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 IdnTable}. */ @RunWith(JUnit4.class) public class IdnTableTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testDigits() { ImmutableList of = ImmutableList.of( @@ -108,17 +103,21 @@ public class IdnTableTest { public void testMissingUrl_throwsNpe() { ImmutableList of = ImmutableList.of( "# Policy: https://love.example/policy.html"); - thrown.expect(NullPointerException.class); - thrown.expectMessage("sloth missing '# URL:"); - IdnTable.createFrom("sloth", of, Optional.empty()); + NullPointerException thrown = + expectThrows( + NullPointerException.class, + () -> IdnTable.createFrom("sloth", of, Optional.empty())); + assertThat(thrown).hasMessageThat().contains("sloth missing '# URL:"); } @Test public void testMissingPolicy_throwsNpe() { ImmutableList of = ImmutableList.of( "# URL: https://love.example/sloth.txt"); - thrown.expect(NullPointerException.class); - thrown.expectMessage("sloth missing '# Policy:"); - IdnTable.createFrom("sloth", of, Optional.empty()); + NullPointerException thrown = + expectThrows( + NullPointerException.class, + () -> IdnTable.createFrom("sloth", of, Optional.empty())); + assertThat(thrown).hasMessageThat().contains("sloth missing '# Policy:"); } } diff --git a/javatests/google/registry/tmch/LordnLogTest.java b/javatests/google/registry/tmch/LordnLogTest.java index df1766f90..f05ad178c 100644 --- a/javatests/google/registry/tmch/LordnLogTest.java +++ b/javatests/google/registry/tmch/LordnLogTest.java @@ -15,14 +15,13 @@ package google.registry.tmch; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import com.google.common.collect.ImmutableList; import google.registry.tmch.LordnLog.Result; import java.util.Map.Entry; import org.joda.time.DateTime; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -30,9 +29,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class LordnLogTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - public static final ImmutableList EXAMPLE_FROM_RFC = ImmutableList.of( "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z," @@ -89,29 +85,33 @@ public class LordnLogTest { @Test public void testFailure_noDnLineMismatch() throws Exception { - thrown.expect(IllegalArgumentException.class); - LordnLog.parse(ImmutableList.of( - "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,1", - "roid,result-code")); + assertThrows( + IllegalArgumentException.class, + () -> + LordnLog.parse( + ImmutableList.of( + "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,1", + "roid,result-code"))); } @Test public void testFailure_parseNull() throws Exception { - thrown.expect(NullPointerException.class); - LordnLog.parse(null); + assertThrows(NullPointerException.class, () -> LordnLog.parse(null)); } @Test public void testFailure_parseEmpty() throws Exception { - thrown.expect(Exception.class); - LordnLog.parse(ImmutableList.of()); + assertThrows(Exception.class, () -> LordnLog.parse(ImmutableList.of())); } @Test public void testFailure_parseMissingHeaderLine() throws Exception { - thrown.expect(Exception.class); - LordnLog.parse(ImmutableList.of( - "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,0")); + assertThrows( + Exception.class, + () -> + LordnLog.parse( + ImmutableList.of( + "1,2012-08-16T02:15:00.0Z,2012-08-16T00:00:00.0Z,lolcat,accepted,no-warnings,0"))); } @Test diff --git a/javatests/google/registry/tmch/LordnTaskTest.java b/javatests/google/registry/tmch/LordnTaskTest.java index 3c4ce60c7..8040d7e62 100644 --- a/javatests/google/registry/tmch/LordnTaskTest.java +++ b/javatests/google/registry/tmch/LordnTaskTest.java @@ -20,6 +20,8 @@ import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.persistActiveContact; import static google.registry.testing.DatastoreHelper.persistDomainAndEnqueueLordn; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; @@ -49,7 +51,6 @@ import org.joda.time.DateTime; 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; @@ -64,10 +65,6 @@ public class LordnTaskTest { .withDatastore() .withTaskQueue() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -97,8 +94,9 @@ public class LordnTaskTest { @Test public void test_convertTasksToCsv_throwsNpeOnNullTasks() throws Exception { - thrown.expect(NullPointerException.class); - LordnTask.convertTasksToCsv(null, clock.nowUtc(), "header"); + assertThrows( + NullPointerException.class, + () -> LordnTask.convertTasksToCsv(null, clock.nowUtc(), "header")); } private DomainResource.Builder newDomainBuilder(DateTime applicationTime) { @@ -166,19 +164,26 @@ public class LordnTaskTest { .setRepoId("9000-EXAMPLE") .setCreationClientId("nonexistentRegistrar") .build(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("No registrar found for client id: nonexistentRegistrar"); - persistDomainAndEnqueueLordn(domain); + IllegalStateException thrown = + expectThrows(IllegalStateException.class, () -> persistDomainAndEnqueueLordn(domain)); + assertThat(thrown) + .hasMessageThat() + .contains("No registrar found for client id: nonexistentRegistrar"); } @Test public void test_enqueueDomainResourceTask_throwsNpeOnNullDomain() throws Exception { - thrown.expect(NullPointerException.class); - ofy().transactNew(new VoidWork() { - @Override - public void vrun() { - LordnTask.enqueueDomainResourceTask(null); - }}); + assertThrows( + NullPointerException.class, + () -> + ofy() + .transactNew( + new VoidWork() { + @Override + public void vrun() { + LordnTask.enqueueDomainResourceTask(null); + } + })); } @SuppressWarnings("unchecked") @@ -198,9 +203,9 @@ public class LordnTaskTest { public void test_loadAllTasks_retryLogic_allFailures() throws Exception { Queue queue = mock(Queue.class); when(queue.leaseTasks(any(LeaseOptions.class))).thenThrow(TransientFailureException.class); - thrown.expect(RuntimeException.class); - thrown.expectMessage("Error leasing tasks"); - LordnTask.loadAllTasks(queue, "tld"); + RuntimeException thrown = + expectThrows(RuntimeException.class, () -> LordnTask.loadAllTasks(queue, "tld")); + assertThat(thrown).hasMessageThat().contains("Error leasing tasks"); } private static TaskHandle makeTaskHandle( diff --git a/javatests/google/registry/tmch/NordnUploadActionTest.java b/javatests/google/registry/tmch/NordnUploadActionTest.java index e91a82b13..11864230f 100644 --- a/javatests/google/registry/tmch/NordnUploadActionTest.java +++ b/javatests/google/registry/tmch/NordnUploadActionTest.java @@ -25,6 +25,8 @@ import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.newDomainResource; import static google.registry.testing.DatastoreHelper.persistDomainAndEnqueueLordn; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.util.UrlFetchUtils.getHeaderFirst; import static java.nio.charset.StandardCharsets.UTF_8; @@ -55,7 +57,6 @@ import org.joda.time.DateTime; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -86,10 +87,6 @@ public class NordnUploadActionTest { @Rule public final InjectRule inject = new InjectRule(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Mock private URLFetchService fetchService; @@ -202,17 +199,15 @@ public class NordnUploadActionTest { public void testFailure_nullRegistryUser() throws Exception { persistClaimsModeDomain(); persistResource(Registry.get("tld").asBuilder().setLordnUsername(null).build()); - thrown.expect(VerifyException.class); - thrown.expectMessage("lordnUsername is not set for tld."); - action.run(); + VerifyException thrown = expectThrows(VerifyException.class, () -> action.run()); + assertThat(thrown).hasMessageThat().contains("lordnUsername is not set for tld."); } @Test public void testFetchFailure() throws Exception { persistClaimsModeDomain(); when(httpResponse.getResponseCode()).thenReturn(SC_INTERNAL_SERVER_ERROR); - thrown.expect(UrlFetchException.class); - action.run(); + assertThrows(UrlFetchException.class, () -> action.run()); } private HTTPRequest getCapturedHttpRequest() throws Exception { diff --git a/javatests/google/registry/tmch/NordnVerifyActionTest.java b/javatests/google/registry/tmch/NordnVerifyActionTest.java index 31f5d441a..5ff637995 100644 --- a/javatests/google/registry/tmch/NordnVerifyActionTest.java +++ b/javatests/google/registry/tmch/NordnVerifyActionTest.java @@ -19,6 +19,8 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import static google.registry.testing.DatastoreHelper.createTld; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.UrlFetchUtils.getHeaderFirst; import static java.nio.charset.StandardCharsets.UTF_8; import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; @@ -40,7 +42,6 @@ import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -86,10 +87,6 @@ public class NordnVerifyActionTest { .withDatastore() .withTaskQueue() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Mock private URLFetchService fetchService; @@ -168,15 +165,13 @@ public class NordnVerifyActionTest { @Test public void failureVerifyUnauthorized() throws Exception { when(httpResponse.getResponseCode()).thenReturn(SC_UNAUTHORIZED); - thrown.expect(Exception.class); - action.run(); + assertThrows(Exception.class, () -> action.run()); } @Test public void failureVerifyNotReady() throws Exception { when(httpResponse.getResponseCode()).thenReturn(SC_NO_CONTENT); - thrown.expect(ConflictException.class); - thrown.expectMessage("Not ready"); - action.run(); + ConflictException thrown = expectThrows(ConflictException.class, () -> action.run()); + assertThat(thrown).hasMessageThat().contains("Not ready"); } } diff --git a/javatests/google/registry/tmch/SmdrlCsvParserTest.java b/javatests/google/registry/tmch/SmdrlCsvParserTest.java index e27c0c9b6..6b4bbb6fd 100644 --- a/javatests/google/registry/tmch/SmdrlCsvParserTest.java +++ b/javatests/google/registry/tmch/SmdrlCsvParserTest.java @@ -15,6 +15,7 @@ package google.registry.tmch; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import static java.nio.charset.StandardCharsets.US_ASCII; import static org.joda.time.Duration.millis; import static org.joda.time.Duration.standardDays; @@ -27,7 +28,6 @@ import google.registry.testing.FakeClock; import org.joda.time.DateTime; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -38,10 +38,6 @@ public class SmdrlCsvParserTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final FakeClock clock = new FakeClock(); private static final CharSource SMDRL_LATEST_CSV = @@ -110,31 +106,43 @@ public class SmdrlCsvParserTest { @Test public void testFail_badVersion() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("version"); - SmdrlCsvParser.parse(ImmutableList.of( - "666,2013-11-24T23:30:04.3Z", - "smd-id,insertion-datetime", - "0000001681375789102250-65535,2013-08-09T12:00:00.0Z")); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + SmdrlCsvParser.parse( + ImmutableList.of( + "666,2013-11-24T23:30:04.3Z", + "smd-id,insertion-datetime", + "0000001681375789102250-65535,2013-08-09T12:00:00.0Z"))); + assertThat(thrown).hasMessageThat().contains("version"); } @Test public void testFail_badHeader() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("header"); - SmdrlCsvParser.parse(ImmutableList.of( - "1,2013-11-24T23:30:04.3Z", - "lol,cat", - "0000001681375789102250-65535,2013-08-09T12:00:00.0Z")); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + SmdrlCsvParser.parse( + ImmutableList.of( + "1,2013-11-24T23:30:04.3Z", + "lol,cat", + "0000001681375789102250-65535,2013-08-09T12:00:00.0Z"))); + assertThat(thrown).hasMessageThat().contains("header"); } @Test public void testFail_tooManyColumns() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("elements"); - SmdrlCsvParser.parse(ImmutableList.of( - "1,2013-11-24T23:30:04.3Z", - "smd-id,insertion-datetime", - "0000001681375789102250-65535,haha,2013-08-09T12:00:00.0Z")); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + SmdrlCsvParser.parse( + ImmutableList.of( + "1,2013-11-24T23:30:04.3Z", + "smd-id,insertion-datetime", + "0000001681375789102250-65535,haha,2013-08-09T12:00:00.0Z"))); + assertThat(thrown).hasMessageThat().contains("elements"); } } diff --git a/javatests/google/registry/tmch/TmchActionTestCase.java b/javatests/google/registry/tmch/TmchActionTestCase.java index 5de75ae0e..081bd78e4 100644 --- a/javatests/google/registry/tmch/TmchActionTestCase.java +++ b/javatests/google/registry/tmch/TmchActionTestCase.java @@ -27,7 +27,6 @@ import google.registry.testing.FakeClock; import google.registry.testing.InjectRule; import org.junit.Before; import org.junit.Rule; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -50,9 +49,6 @@ public class TmchActionTestCase { @Rule public final BouncyCastleProviderRule bouncy = new BouncyCastleProviderRule(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); diff --git a/javatests/google/registry/tmch/TmchCertificateAuthorityTest.java b/javatests/google/registry/tmch/TmchCertificateAuthorityTest.java index c37107f29..09f62a101 100644 --- a/javatests/google/registry/tmch/TmchCertificateAuthorityTest.java +++ b/javatests/google/registry/tmch/TmchCertificateAuthorityTest.java @@ -34,7 +34,6 @@ import org.joda.time.DateTime; 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; @@ -49,10 +48,6 @@ public class TmchCertificateAuthorityTest { public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -113,8 +108,10 @@ public class TmchCertificateAuthorityTest { @Test public void testFailure_verifyRevoked() throws Exception { TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT); - thrown.expect(CertificateRevokedException.class); - thrown.expectMessage("revoked, reason: KEY_COMPROMISE"); - tmchCertificateAuthority.verify(loadCertificate(REVOKED_TEST_CERTIFICATE)); + CertificateRevokedException thrown = + expectThrows( + CertificateRevokedException.class, + () -> tmchCertificateAuthority.verify(loadCertificate(REVOKED_TEST_CERTIFICATE))); + assertThat(thrown).hasMessageThat().contains("revoked, reason: KEY_COMPROMISE"); } } diff --git a/javatests/google/registry/tmch/TmchXmlSignatureTest.java b/javatests/google/registry/tmch/TmchXmlSignatureTest.java index 4ec76676d..5863c353e 100644 --- a/javatests/google/registry/tmch/TmchXmlSignatureTest.java +++ b/javatests/google/registry/tmch/TmchXmlSignatureTest.java @@ -32,7 +32,6 @@ import org.joda.time.DateTime; 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; @@ -49,9 +48,6 @@ public class TmchXmlSignatureTest { .withDatastore() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -291,36 +287,31 @@ public class TmchXmlSignatureTest { @Test public void testInvalidInvalidsignatureCourtAgentFrenchActive() throws Exception { smdData = loadSmd("invalid/InvalidSignature-Court-Agent-French-Active.smd"); - thrown.expect(XMLSignatureException.class); - tmchXmlSignature.verify(smdData); + assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData)); } @Test public void testInvalidInvalidsignatureTrademarkAgentEnglishActive() throws Exception { smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-English-Active.smd"); - thrown.expect(XMLSignatureException.class); - tmchXmlSignature.verify(smdData); + assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData)); } @Test public void testInvalidInvalidsignatureTrademarkAgentRussianActive() throws Exception { smdData = loadSmd("invalid/InvalidSignature-Trademark-Agent-Russian-Active.smd"); - thrown.expect(XMLSignatureException.class); - tmchXmlSignature.verify(smdData); + assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData)); } @Test public void testInvalidInvalidsignatureTreatystatuteAgentChineseActive() throws Exception { smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-Chinese-Active.smd"); - thrown.expect(XMLSignatureException.class); - tmchXmlSignature.verify(smdData); + assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData)); } @Test public void testInvalidInvalidsignatureTreatystatuteAgentEnglishActive() throws Exception { smdData = loadSmd("invalid/InvalidSignature-TreatyStatute-Agent-English-Active.smd"); - thrown.expect(XMLSignatureException.class); - tmchXmlSignature.verify(smdData); + assertThrows(XMLSignatureException.class, () -> tmchXmlSignature.verify(smdData)); } @Test diff --git a/javatests/google/registry/tools/params/DateParameterTest.java b/javatests/google/registry/tools/params/DateParameterTest.java index b811a1939..682da9548 100644 --- a/javatests/google/registry/tools/params/DateParameterTest.java +++ b/javatests/google/registry/tools/params/DateParameterTest.java @@ -15,11 +15,10 @@ package google.registry.tools.params; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import org.joda.time.DateTime; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -27,9 +26,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DateParameterTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final DateParameter instance = new DateParameter(); @Test @@ -40,61 +36,52 @@ public class DateParameterTest { @Test public void testConvert_numeric_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("1234"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("1234")); } @Test public void testConvert_validDateAndTime_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("2014-01-01T01:02:03.004Z"); + assertThrows( + IllegalArgumentException.class, () -> instance.convert("2014-01-01T01:02:03.004Z")); } @Test public void testConvert_invalidDate_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("2014-13-33"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-13-33")); } @Test public void testConvert_null_throwsException() throws Exception { - thrown.expect(NullPointerException.class); - instance.convert(null); + assertThrows(NullPointerException.class, () -> instance.convert(null)); } @Test public void testConvert_empty_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert(""); + assertThrows(IllegalArgumentException.class, () -> instance.convert("")); } @Test public void testConvert_sillyString_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("foo"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("foo")); } @Test public void testConvert_partialDate_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("2014-01"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01")); } @Test public void testConvert_onlyTime_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("T01:02:03"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("T01:02:03")); } @Test public void testConvert_partialDateAndPartialTime_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("9T9"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("9T9")); } @Test public void testConvert_dateAndPartialTime_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("2014-01-01T01:02"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01-01T01:02")); } } diff --git a/javatests/google/registry/tools/params/DateTimeParameterTest.java b/javatests/google/registry/tools/params/DateTimeParameterTest.java index 2f68bdf3d..83b31510d 100644 --- a/javatests/google/registry/tools/params/DateTimeParameterTest.java +++ b/javatests/google/registry/tools/params/DateTimeParameterTest.java @@ -15,23 +15,19 @@ package google.registry.tools.params; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.joda.time.DateTimeZone.UTC; import com.beust.jcommander.ParameterException; import org.joda.time.DateTime; -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 DateTimeParameter}. */ @RunWith(JUnit4.class) public class DateTimeParameterTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final DateTimeParameter instance = new DateTimeParameter(); @Test @@ -60,69 +56,59 @@ public class DateTimeParameterTest { @Test public void testConvert_null_throwsException() throws Exception { - thrown.expect(NullPointerException.class); - instance.convert(null); + assertThrows(NullPointerException.class, () -> instance.convert(null)); } @Test public void testConvert_empty_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert(""); + assertThrows(IllegalArgumentException.class, () -> instance.convert("")); } @Test public void testConvert_sillyString_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("foo"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("foo")); } @Test public void testConvert_partialDate_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("2014-01"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01")); } @Test public void testConvert_onlyDate_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("2014-01-01"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01-01")); } @Test public void testConvert_partialTime_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("T01:02"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("T01:02")); } @Test public void testConvert_onlyTime_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("T01:02:03"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("T01:02:03")); } @Test public void testConvert_partialDateAndPartialTime_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("9T9"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("9T9")); } @Test public void testConvert_dateAndPartialTime_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("2014-01-01T01:02"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01-01T01:02")); } @Test public void testConvert_noTimeZone_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("2014-01-01T01:02:03"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("2014-01-01T01:02:03")); } @Test public void testValidate_sillyString_throwsParameterException() throws Exception { - thrown.expect(ParameterException.class); - thrown.expectMessage("--time=foo not an ISO"); - instance.validate("--time", "foo"); + ParameterException thrown = + expectThrows(ParameterException.class, () -> instance.validate("--time", "foo")); + assertThat(thrown).hasMessageThat().contains("--time=foo not an ISO"); } @Test diff --git a/javatests/google/registry/tools/params/DurationParameterTest.java b/javatests/google/registry/tools/params/DurationParameterTest.java index 3619378c9..0902e94ae 100644 --- a/javatests/google/registry/tools/params/DurationParameterTest.java +++ b/javatests/google/registry/tools/params/DurationParameterTest.java @@ -15,23 +15,19 @@ package google.registry.tools.params; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import com.beust.jcommander.ParameterException; import org.joda.time.Duration; import org.joda.time.Period; -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 DurationParameter}. */ @RunWith(JUnit4.class) public class DurationParameterTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final DurationParameter instance = new DurationParameter(); @Test @@ -51,50 +47,43 @@ public class DurationParameterTest { @Test public void testIsoMissingP_notAllowed() throws Exception { - thrown.expect(IllegalArgumentException.class); - Period.parse("T36H"); + assertThrows(IllegalArgumentException.class, () -> Period.parse("T36H")); } @Test public void testIsoMissingPT_notAllowed() throws Exception { - thrown.expect(IllegalArgumentException.class); - Period.parse("36H"); + assertThrows(IllegalArgumentException.class, () -> Period.parse("36H")); } @Test public void testConvert_isoMissingP_notAllowed() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("T36H"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("T36H")); } @Test public void testConvert_null_throws() throws Exception { - thrown.expect(NullPointerException.class); - instance.convert(null); + assertThrows(NullPointerException.class, () -> instance.convert(null)); } @Test public void testConvert_empty_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert(""); + assertThrows(IllegalArgumentException.class, () -> instance.convert("")); } @Test public void testConvert_numeric_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("1234"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("1234")); } @Test public void testConvert_sillyString_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("foo"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("foo")); } @Test public void testValidate_sillyString_throws() throws Exception { - thrown.expect(ParameterException.class); - thrown.expectMessage("--time=foo not an"); - instance.validate("--time", "foo"); + ParameterException thrown = + expectThrows(ParameterException.class, () -> instance.validate("--time", "foo")); + assertThat(thrown).hasMessageThat().contains("--time=foo not an"); } } diff --git a/javatests/google/registry/tools/params/EnumParameterTest.java b/javatests/google/registry/tools/params/EnumParameterTest.java index bc836aca4..91858e196 100644 --- a/javatests/google/registry/tools/params/EnumParameterTest.java +++ b/javatests/google/registry/tools/params/EnumParameterTest.java @@ -15,11 +15,10 @@ package google.registry.tools.params; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import google.registry.model.registry.Registry.TldState; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -27,9 +26,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class EnumParameterTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - // There's no additional functionality exposed by this (or any other) EnumParameter, but using // this in the test as EnumParameter is abstract. private final TldStateParameter instance = new TldStateParameter(); @@ -41,9 +37,11 @@ public class EnumParameterTest { @Test public void testFailure_badValue() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage( - "No enum constant google.registry.model.registry.Registry.TldState.GENERAL_SUNRUSH"); - instance.convert("GENERAL_SUNRUSH"); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> instance.convert("GENERAL_SUNRUSH")); + assertThat(thrown) + .hasMessageThat() + .contains( + "No enum constant google.registry.model.registry.Registry.TldState.GENERAL_SUNRUSH"); } } diff --git a/javatests/google/registry/tools/params/IntervalParameterTest.java b/javatests/google/registry/tools/params/IntervalParameterTest.java index ba76d7378..abf8263aa 100644 --- a/javatests/google/registry/tools/params/IntervalParameterTest.java +++ b/javatests/google/registry/tools/params/IntervalParameterTest.java @@ -15,23 +15,19 @@ package google.registry.tools.params; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import com.beust.jcommander.ParameterException; import org.joda.time.DateTime; import org.joda.time.Interval; -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 IntervalParameter}. */ @RunWith(JUnit4.class) public class IntervalParameterTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final IntervalParameter instance = new IntervalParameter(); @Test @@ -44,38 +40,35 @@ public class IntervalParameterTest { @Test public void testConvert_singleDate() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("2004-06-09T12:30:00Z"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("2004-06-09T12:30:00Z")); } @Test public void testConvert_backwardsInterval() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("2004-07-10T13:30:00Z/2004-06-09T12:30:00Z"); + assertThrows( + IllegalArgumentException.class, + () -> instance.convert("2004-07-10T13:30:00Z/2004-06-09T12:30:00Z")); } @Test public void testConvert_empty_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert(""); + assertThrows(IllegalArgumentException.class, () -> instance.convert("")); } @Test public void testConvert_null_throws() throws Exception { - thrown.expect(NullPointerException.class); - instance.convert(null); + assertThrows(NullPointerException.class, () -> instance.convert(null)); } @Test public void testConvert_sillyString_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("foo"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("foo")); } @Test public void testValidate_sillyString_throws() throws Exception { - thrown.expect(ParameterException.class); - thrown.expectMessage("--time=foo not an"); - instance.validate("--time", "foo"); + ParameterException thrown = + expectThrows(ParameterException.class, () -> instance.validate("--time", "foo")); + assertThat(thrown).hasMessageThat().contains("--time=foo not an"); } } diff --git a/javatests/google/registry/tools/params/KeyValueMapParameterTest.java b/javatests/google/registry/tools/params/KeyValueMapParameterTest.java index 605475b3f..470427e2e 100644 --- a/javatests/google/registry/tools/params/KeyValueMapParameterTest.java +++ b/javatests/google/registry/tools/params/KeyValueMapParameterTest.java @@ -15,6 +15,8 @@ package google.registry.tools.params; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.collect.ImmutableMap; import google.registry.tools.params.KeyValueMapParameter.CurrencyUnitToStringMap; @@ -22,19 +24,13 @@ import google.registry.tools.params.KeyValueMapParameter.StringToIntegerMap; import google.registry.tools.params.KeyValueMapParameter.StringToStringMap; import org.joda.money.CurrencyUnit; import org.joda.money.IllegalCurrencyException; -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 KeyValueMapParameter}. */ @RunWith(JUnit4.class) public class KeyValueMapParameterTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final StringToStringMap stringToStringInstance = new StringToStringMap(); private final StringToIntegerMap stringToIntegerInstance = new StringToIntegerMap(); private final CurrencyUnitToStringMap currencyUnitToStringMap = new CurrencyUnitToStringMap(); @@ -92,51 +88,51 @@ public class KeyValueMapParameterTest { @Test public void testFailure_convertStringToInteger_badType() throws Exception { - thrown.expect(NumberFormatException.class); - stringToIntegerInstance.convert("key=1,key2=foo"); + assertThrows( + NumberFormatException.class, () -> stringToIntegerInstance.convert("key=1,key2=foo")); } @Test public void testFailure_convertCurrencyUnitToString_badType() throws Exception { - thrown.expect(IllegalCurrencyException.class); - thrown.expectMessage("XYZ"); - currencyUnitToStringMap.convert("USD=123abc,XYZ=xyz789"); + IllegalCurrencyException thrown = + expectThrows( + IllegalCurrencyException.class, + () -> currencyUnitToStringMap.convert("USD=123abc,XYZ=xyz789")); + assertThat(thrown).hasMessageThat().contains("XYZ"); } @Test public void testFailure_convertStringToString_badSeparator() throws Exception { - thrown.expect(IllegalArgumentException.class); - stringToStringInstance.convert("key=foo&key2=bar"); + assertThrows( + IllegalArgumentException.class, () -> stringToStringInstance.convert("key=foo&key2=bar")); } @Test public void testFailure_convertStringToInteger_badSeparator() throws Exception { - thrown.expect(IllegalArgumentException.class); - stringToIntegerInstance.convert("key=1&key2=2"); + assertThrows( + IllegalArgumentException.class, () -> stringToIntegerInstance.convert("key=1&key2=2")); } @Test public void testFailure_convertCurrencyUnitToString_badSeparator() throws Exception { - thrown.expect(IllegalArgumentException.class); - currencyUnitToStringMap.convert("USD=123abc&JPY=xyz789"); + assertThrows( + IllegalArgumentException.class, + () -> currencyUnitToStringMap.convert("USD=123abc&JPY=xyz789")); } @Test public void testFailure_convertStringToString_badFormat() throws Exception { - thrown.expect(IllegalArgumentException.class); - stringToStringInstance.convert("foo"); + assertThrows(IllegalArgumentException.class, () -> stringToStringInstance.convert("foo")); } @Test public void testFailure_convertStringToInteger_badFormat() throws Exception { - thrown.expect(IllegalArgumentException.class); - stringToIntegerInstance.convert("foo"); + assertThrows(IllegalArgumentException.class, () -> stringToIntegerInstance.convert("foo")); } @Test public void testFailure_convertCurrencyUnitToString_badFormat() throws Exception { - thrown.expect(IllegalArgumentException.class); - currencyUnitToStringMap.convert("foo"); + assertThrows(IllegalArgumentException.class, () -> currencyUnitToStringMap.convert("foo")); } } diff --git a/javatests/google/registry/tools/params/MoneyParameterTest.java b/javatests/google/registry/tools/params/MoneyParameterTest.java index 354955267..f84829358 100644 --- a/javatests/google/registry/tools/params/MoneyParameterTest.java +++ b/javatests/google/registry/tools/params/MoneyParameterTest.java @@ -15,22 +15,18 @@ package google.registry.tools.params; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import com.beust.jcommander.ParameterException; import org.joda.money.Money; -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 MoneyParameter}. */ @RunWith(JUnit4.class) public class MoneyParameterTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final MoneyParameter instance = new MoneyParameter(); @Test @@ -55,33 +51,29 @@ public class MoneyParameterTest { @Test public void testConvert_badCurrency_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("FOO 1337"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("FOO 1337")); } @Test public void testConvert_null_throws() throws Exception { - thrown.expect(NullPointerException.class); - instance.convert(null); + assertThrows(NullPointerException.class, () -> instance.convert(null)); } @Test public void testConvert_empty_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert(""); + assertThrows(IllegalArgumentException.class, () -> instance.convert("")); } @Test public void testConvert_sillyString_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("foo"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("foo")); } @Test public void testValidate_sillyString_throws() throws Exception { - thrown.expect(ParameterException.class); - thrown.expectMessage("--money=foo not valid"); - instance.validate("--money", "foo"); + ParameterException thrown = + expectThrows(ParameterException.class, () -> instance.validate("--money", "foo")); + assertThat(thrown).hasMessageThat().contains("--money=foo not valid"); } @Test diff --git a/javatests/google/registry/tools/params/PathParameterTest.java b/javatests/google/registry/tools/params/PathParameterTest.java index d391130a9..71cb5956a 100644 --- a/javatests/google/registry/tools/params/PathParameterTest.java +++ b/javatests/google/registry/tools/params/PathParameterTest.java @@ -15,6 +15,8 @@ package google.registry.tools.params; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; @@ -31,7 +33,6 @@ import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermissions; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -39,10 +40,6 @@ import org.junit.runners.JUnit4; /** Unit tests for {@link PathParameter}. */ @RunWith(JUnit4.class) public class PathParameterTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final TemporaryFolder folder = new TemporaryFolder(); @@ -57,14 +54,12 @@ public class PathParameterTest { @Test public void testConvert_null_throws() throws Exception { - thrown.expect(NullPointerException.class); - vanilla.convert(null); + assertThrows(NullPointerException.class, () -> vanilla.convert(null)); } @Test public void testConvert_empty_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - vanilla.convert(""); + assertThrows(IllegalArgumentException.class, () -> vanilla.convert("")); } @Test @@ -86,8 +81,7 @@ public class PathParameterTest { @Test public void testConvert_uriNotProvided() throws Exception { - thrown.expect(FileSystemNotFoundException.class); - vanilla.convert("bog://bucket/lolcat"); + assertThrows(FileSystemNotFoundException.class, () -> vanilla.convert("bog://bucket/lolcat")); } // =========================== Test InputFile Validate ======================================== @@ -101,25 +95,29 @@ public class PathParameterTest { @Test public void testInputFileValidate_missingFile_throws() throws Exception { - thrown.expect(ParameterException.class); - thrown.expectMessage("not found"); - inputFile.validate("input", new File(folder.getRoot(), "foo").toString()); + ParameterException thrown = + expectThrows( + ParameterException.class, + () -> inputFile.validate("input", new File(folder.getRoot(), "foo").toString())); + assertThat(thrown).hasMessageThat().contains("not found"); } @Test public void testInputFileValidate_directory_throws() throws Exception { - thrown.expect(ParameterException.class); - thrown.expectMessage("is a directory"); - inputFile.validate("input", folder.getRoot().toString()); + ParameterException thrown = + expectThrows( + ParameterException.class, + () -> inputFile.validate("input", folder.getRoot().toString())); + assertThat(thrown).hasMessageThat().contains("is a directory"); } @Test public void testInputFileValidate_unreadableFile_throws() throws Exception { Path file = Paths.get(folder.newFile().toString()); Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("-w-------")); - thrown.expect(ParameterException.class); - thrown.expectMessage("not readable"); - inputFile.validate("input", file.toString()); + ParameterException thrown = + expectThrows(ParameterException.class, () -> inputFile.validate("input", file.toString())); + assertThat(thrown).hasMessageThat().contains("not readable"); } // =========================== Test OutputFile Validate ======================================== @@ -144,33 +142,35 @@ public class PathParameterTest { @Test public void testOutputFileValidate_directory_throws() throws Exception { - thrown.expect(ParameterException.class); - thrown.expectMessage("is a directory"); - outputFile.validate("input", folder.getRoot().toString()); + ParameterException thrown = + expectThrows( + ParameterException.class, + () -> outputFile.validate("input", folder.getRoot().toString())); + assertThat(thrown).hasMessageThat().contains("is a directory"); } @Test public void testOutputFileValidate_notWritable_throws() throws Exception { Path file = Paths.get(folder.newFile().toString()); Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("r--------")); - thrown.expect(ParameterException.class); - thrown.expectMessage("not writable"); - outputFile.validate("input", file.toString()); + ParameterException thrown = + expectThrows(ParameterException.class, () -> outputFile.validate("input", file.toString())); + assertThat(thrown).hasMessageThat().contains("not writable"); } @Test public void testOutputFileValidate_parentDirMissing_throws() throws Exception { Path file = Paths.get(folder.getRoot().toString(), "MISSINGNO", "foo.txt"); - thrown.expect(ParameterException.class); - thrown.expectMessage("parent dir doesn't exist"); - outputFile.validate("input", file.toString()); + ParameterException thrown = + expectThrows(ParameterException.class, () -> outputFile.validate("input", file.toString())); + assertThat(thrown).hasMessageThat().contains("parent dir doesn't exist"); } @Test public void testOutputFileValidate_parentDirIsFile_throws() throws Exception { Path file = Paths.get(folder.newFile().toString(), "foo.txt"); - thrown.expect(ParameterException.class); - thrown.expectMessage("parent is non-directory"); - outputFile.validate("input", file.toString()); + ParameterException thrown = + expectThrows(ParameterException.class, () -> outputFile.validate("input", file.toString())); + assertThat(thrown).hasMessageThat().contains("parent is non-directory"); } } diff --git a/javatests/google/registry/tools/params/PhoneNumberParameterTest.java b/javatests/google/registry/tools/params/PhoneNumberParameterTest.java index bfc225fc9..f92a77412 100644 --- a/javatests/google/registry/tools/params/PhoneNumberParameterTest.java +++ b/javatests/google/registry/tools/params/PhoneNumberParameterTest.java @@ -15,20 +15,15 @@ package google.registry.tools.params; import static com.google.common.truth.Truth8.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; -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 PhoneNumberParameter}. */ @RunWith(JUnit4.class) public class PhoneNumberParameterTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final OptionalPhoneNumberParameter instance = new OptionalPhoneNumberParameter(); @Test @@ -38,8 +33,7 @@ public class PhoneNumberParameterTest { @Test public void testConvert_sillyString_throws() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("foo"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("foo")); } @Test diff --git a/javatests/google/registry/tools/params/YearMonthParameterTest.java b/javatests/google/registry/tools/params/YearMonthParameterTest.java index 72ad3df9f..dc298dcad 100644 --- a/javatests/google/registry/tools/params/YearMonthParameterTest.java +++ b/javatests/google/registry/tools/params/YearMonthParameterTest.java @@ -15,22 +15,18 @@ package google.registry.tools.params; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import com.beust.jcommander.ParameterException; import org.joda.time.YearMonth; -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 YearMonthParameter}. */ @RunWith(JUnit4.class) public class YearMonthParameterTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final YearMonthParameter instance = new YearMonthParameter(); @Test @@ -40,39 +36,34 @@ public class YearMonthParameterTest { @Test public void testConvert_null_throwsException() throws Exception { - thrown.expect(NullPointerException.class); - instance.convert(null); + assertThrows(NullPointerException.class, () -> instance.convert(null)); } @Test public void testConvert_empty_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert(""); + assertThrows(IllegalArgumentException.class, () -> instance.convert("")); } @Test public void testConvert_sillyString_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("foo"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("foo")); } @Test public void testConvert_wrongOrder() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("12-1984"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("12-1984")); } @Test public void testConvert_noHyphen() throws Exception { - thrown.expect(IllegalArgumentException.class); - instance.convert("198412"); + assertThrows(IllegalArgumentException.class, () -> instance.convert("198412")); } @Test public void testValidate_sillyString_throwsParameterException() throws Exception { - thrown.expect(ParameterException.class); - thrown.expectMessage("--time=foo not a valid"); - instance.validate("--time", "foo"); + ParameterException thrown = + expectThrows(ParameterException.class, () -> instance.validate("--time", "foo")); + assertThat(thrown).hasMessageThat().contains("--time=foo not a valid"); } @Test diff --git a/javatests/google/registry/tools/server/CreateGroupsActionTest.java b/javatests/google/registry/tools/server/CreateGroupsActionTest.java index 075245b33..64ce15968 100644 --- a/javatests/google/registry/tools/server/CreateGroupsActionTest.java +++ b/javatests/google/registry/tools/server/CreateGroupsActionTest.java @@ -32,7 +32,6 @@ import google.registry.testing.InjectRule; import java.util.Optional; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -46,10 +45,6 @@ public class CreateGroupsActionTest { public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -67,17 +62,21 @@ public class CreateGroupsActionTest { @Test public void test_invalidRequest_missingClientId() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage("Error creating Google Groups, missing parameter: clientId"); - runAction(null); + BadRequestException thrown = expectThrows(BadRequestException.class, () -> runAction(null)); + assertThat(thrown) + .hasMessageThat() + .contains("Error creating Google Groups, missing parameter: clientId"); } @Test public void test_invalidRequest_invalidClientId() throws Exception { - thrown.expect(BadRequestException.class); - thrown.expectMessage( - "Error creating Google Groups; could not find registrar with id completelyMadeUpClientId"); - runAction("completelyMadeUpClientId"); + BadRequestException thrown = + expectThrows(BadRequestException.class, () -> runAction("completelyMadeUpClientId")); + assertThat(thrown) + .hasMessageThat() + .contains( + "Error creating Google Groups; " + + "could not find registrar with id completelyMadeUpClientId"); } @Test diff --git a/javatests/google/registry/tools/server/CreatePremiumListActionTest.java b/javatests/google/registry/tools/server/CreatePremiumListActionTest.java index 3af582c63..62e682784 100644 --- a/javatests/google/registry/tools/server/CreatePremiumListActionTest.java +++ b/javatests/google/registry/tools/server/CreatePremiumListActionTest.java @@ -30,7 +30,6 @@ import org.joda.money.Money; 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; @@ -41,8 +40,6 @@ import org.junit.runners.JUnit4; public class CreatePremiumListActionTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); - @Rule public final ExpectedException thrown = ExpectedException.none(); - CreatePremiumListAction action; FakeJsonResponse response; diff --git a/javatests/google/registry/tools/server/DeleteEntityActionTest.java b/javatests/google/registry/tools/server/DeleteEntityActionTest.java index 880e4dcf1..67fbfe8b2 100644 --- a/javatests/google/registry/tools/server/DeleteEntityActionTest.java +++ b/javatests/google/registry/tools/server/DeleteEntityActionTest.java @@ -18,6 +18,7 @@ import static com.google.appengine.api.datastore.DatastoreServiceFactory.getData import static com.google.common.truth.Truth.assertThat; import static com.googlecode.objectify.Key.create; import static google.registry.model.ofy.ObjectifyService.ofy; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.KeyFactory; @@ -28,7 +29,6 @@ import google.registry.testing.FakeResponse; 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; @@ -38,10 +38,6 @@ public class DeleteEntityActionTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - FakeResponse response = new FakeResponse(); DeleteEntityAction action = new DeleteEntityAction(); @@ -89,9 +85,8 @@ public class DeleteEntityActionTest { Entity entity = new Entity("not", "here"); String rawKey = KeyFactory.keyToString(entity.getKey()); action.rawKeys = rawKey; - thrown.expect(BadRequestException.class); - thrown.expectMessage("Could not find entity with key " + rawKey); - action.run(); + BadRequestException thrown = expectThrows(BadRequestException.class, () -> action.run()); + assertThat(thrown).hasMessageThat().contains("Could not find entity with key " + rawKey); } @Test @@ -102,8 +97,7 @@ public class DeleteEntityActionTest { Entity entity = new Entity("non", "existent"); String rawKey = KeyFactory.keyToString(entity.getKey()); action.rawKeys = String.format("%s,%s", ofyKey, rawKey); - thrown.expect(BadRequestException.class); - thrown.expectMessage("Could not find entity with key " + rawKey); - action.run(); + BadRequestException thrown = expectThrows(BadRequestException.class, () -> action.run()); + assertThat(thrown).hasMessageThat().contains("Could not find entity with key " + rawKey); } } diff --git a/javatests/google/registry/tools/server/ListActionTestCase.java b/javatests/google/registry/tools/server/ListActionTestCase.java index ee0809004..2ec02b285 100644 --- a/javatests/google/registry/tools/server/ListActionTestCase.java +++ b/javatests/google/registry/tools/server/ListActionTestCase.java @@ -23,7 +23,6 @@ import java.util.List; import java.util.Optional; import java.util.regex.Pattern; import org.junit.Rule; -import org.junit.rules.ExpectedException; /** * Base class for tests of list actions. @@ -35,9 +34,6 @@ public class ListActionTestCase { .withDatastore() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private FakeJsonResponse response; private void runAction( diff --git a/javatests/google/registry/tools/server/UpdatePremiumListActionTest.java b/javatests/google/registry/tools/server/UpdatePremiumListActionTest.java index 104028d2e..55af332c2 100644 --- a/javatests/google/registry/tools/server/UpdatePremiumListActionTest.java +++ b/javatests/google/registry/tools/server/UpdatePremiumListActionTest.java @@ -29,7 +29,6 @@ import org.joda.money.Money; 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; @@ -44,9 +43,6 @@ public class UpdatePremiumListActionTest { .withDatastore() .build(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - UpdatePremiumListAction action; FakeJsonResponse response; diff --git a/javatests/google/registry/ui/forms/FormFieldExceptionTest.java b/javatests/google/registry/ui/forms/FormFieldExceptionTest.java index df22b18b0..40383e09b 100644 --- a/javatests/google/registry/ui/forms/FormFieldExceptionTest.java +++ b/javatests/google/registry/ui/forms/FormFieldExceptionTest.java @@ -15,21 +15,16 @@ package google.registry.ui.forms; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import com.google.common.testing.NullPointerTester; -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 FormFieldException}. */ @RunWith(JUnit4.class) public class FormFieldExceptionTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testGetFieldName_multiplePropagations_joinsUsingJsonNotation() throws Exception { assertThat( @@ -53,8 +48,9 @@ public class FormFieldExceptionTest { @Test public void testGetFieldName_noPropagations_throwsIse() throws Exception { - thrown.expect(IllegalStateException.class); - new FormFieldException("This field is required.").getFieldName(); + assertThrows( + IllegalStateException.class, + () -> new FormFieldException("This field is required.").getFieldName()); } @Test diff --git a/javatests/google/registry/ui/server/registrar/SendEmailUtilsTest.java b/javatests/google/registry/ui/server/registrar/SendEmailUtilsTest.java index fea751085..16c387757 100644 --- a/javatests/google/registry/ui/server/registrar/SendEmailUtilsTest.java +++ b/javatests/google/registry/ui/server/registrar/SendEmailUtilsTest.java @@ -37,7 +37,6 @@ import javax.mail.internet.MimeMessage; 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; @@ -45,9 +44,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class SendEmailUtilsTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); diff --git a/javatests/google/registry/ui/server/registrar/SessionUtilsTest.java b/javatests/google/registry/ui/server/registrar/SessionUtilsTest.java index eabe3493e..8d5eb8820 100644 --- a/javatests/google/registry/ui/server/registrar/SessionUtilsTest.java +++ b/javatests/google/registry/ui/server/registrar/SessionUtilsTest.java @@ -19,6 +19,7 @@ import static google.registry.testing.AppEngineRule.THE_REGISTRAR_GAE_USER_ID; import static google.registry.testing.DatastoreHelper.deleteResource; import static google.registry.testing.DatastoreHelper.loadRegistrar; import static google.registry.testing.DatastoreHelper.persistResource; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.LogsSubject.assertAboutLogs; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; @@ -41,7 +42,6 @@ import org.junit.After; 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; @@ -50,9 +50,6 @@ import org.junit.runners.JUnit4; public class SessionUtilsTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); - - @Rule public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); private final HttpServletRequest req = mock(HttpServletRequest.class); @@ -96,9 +93,12 @@ public class SessionUtilsTest { @Test public void testCheckRegistrarConsoleLogin_notLoggedIn_throwsIllegalStateException() throws Exception { - thrown.expect(IllegalStateException.class); - @SuppressWarnings("unused") - boolean unused = sessionUtils.checkRegistrarConsoleLogin(req, null); + assertThrows( + IllegalStateException.class, + () -> { + @SuppressWarnings("unused") + boolean unused = sessionUtils.checkRegistrarConsoleLogin(req, null); + }); } /** diff --git a/javatests/google/registry/util/CollectionUtilsTest.java b/javatests/google/registry/util/CollectionUtilsTest.java index a60e56447..7b2073e10 100644 --- a/javatests/google/registry/util/CollectionUtilsTest.java +++ b/javatests/google/registry/util/CollectionUtilsTest.java @@ -15,6 +15,7 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.util.CollectionUtils.nullToEmpty; import static google.registry.util.CollectionUtils.partitionMap; @@ -22,9 +23,7 @@ import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -32,9 +31,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class CollectionUtilsTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testNullToEmptyMap_leavesNonNullAlone() { Map map = ImmutableMap.of("hello", 1); @@ -65,14 +61,12 @@ public class CollectionUtilsTest { @Test public void testPartitionMap_negativePartitionSize() { - thrown.expect(IllegalArgumentException.class); - partitionMap(ImmutableMap.of("A", "b"), -2); + assertThrows(IllegalArgumentException.class, () -> partitionMap(ImmutableMap.of("A", "b"), -2)); } @Test public void testPartitionMap_nullMap() { - thrown.expect(NullPointerException.class); - partitionMap(null, 100); + assertThrows(NullPointerException.class, () -> partitionMap(null, 100)); } @Test diff --git a/javatests/google/registry/util/DateTimeUtilsTest.java b/javatests/google/registry/util/DateTimeUtilsTest.java index a877e2b55..ae672b023 100644 --- a/javatests/google/registry/util/DateTimeUtilsTest.java +++ b/javatests/google/registry/util/DateTimeUtilsTest.java @@ -15,6 +15,7 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.util.DateTimeUtils.END_OF_TIME; import static google.registry.util.DateTimeUtils.START_OF_TIME; import static google.registry.util.DateTimeUtils.earliestOf; @@ -25,9 +26,7 @@ import static google.registry.util.DateTimeUtils.leapSafeAddYears; import com.google.common.collect.ImmutableList; import org.joda.time.DateTime; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -38,9 +37,6 @@ public class DateTimeUtilsTest { ImmutableList sampleDates = ImmutableList.of( START_OF_TIME, START_OF_TIME.plusDays(1), END_OF_TIME, END_OF_TIME); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testSuccess_earliestOf() { assertThat(earliestOf(START_OF_TIME, END_OF_TIME)).isEqualTo(START_OF_TIME); @@ -76,13 +72,11 @@ public class DateTimeUtilsTest { @Test public void testFailure_earliestOfEmpty() { - thrown.expect(IllegalArgumentException.class); - earliestOf(ImmutableList.of()); + assertThrows(IllegalArgumentException.class, () -> earliestOf(ImmutableList.of())); } @Test public void testFailure_latestOfEmpty() { - thrown.expect(IllegalArgumentException.class); - earliestOf(ImmutableList.of()); + assertThrows(IllegalArgumentException.class, () -> earliestOf(ImmutableList.of())); } } diff --git a/javatests/google/registry/util/DomainNameUtilsTest.java b/javatests/google/registry/util/DomainNameUtilsTest.java index a8f9daa9e..aea777bfa 100644 --- a/javatests/google/registry/util/DomainNameUtilsTest.java +++ b/javatests/google/registry/util/DomainNameUtilsTest.java @@ -15,21 +15,16 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.util.DomainNameUtils.canonicalizeDomainName; -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 DomainNameUtils}. */ @RunWith(JUnit4.class) public class DomainNameUtilsTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testCanonicalizeDomainName() throws Exception { assertThat(canonicalizeDomainName("foo")).isEqualTo("foo"); @@ -46,7 +41,6 @@ public class DomainNameUtilsTest { @Test public void testCanonicalizeDomainName_acePrefixUnicodeChars() throws Exception { - thrown.expect(IllegalArgumentException.class); - canonicalizeDomainName("xn--みんな"); + assertThrows(IllegalArgumentException.class, () -> canonicalizeDomainName("xn--みんな")); } } diff --git a/javatests/google/registry/util/HexDumperTest.java b/javatests/google/registry/util/HexDumperTest.java index 00dfbae3c..699531c4f 100644 --- a/javatests/google/registry/util/HexDumperTest.java +++ b/javatests/google/registry/util/HexDumperTest.java @@ -15,12 +15,11 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.StringWriter; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -28,9 +27,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class HexDumperTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testEmpty() throws Exception { String input = ""; @@ -169,37 +165,32 @@ public class HexDumperTest { @Test public void testBadArgumentPerLineZero() throws Exception { HexDumper.dumpHex(new byte[1], 1, 0); - thrown.expect(IllegalArgumentException.class); - HexDumper.dumpHex(new byte[1], 0, 0); + assertThrows(IllegalArgumentException.class, () -> HexDumper.dumpHex(new byte[1], 0, 0)); } @Test public void testBadArgumentPerLineNegative() throws Exception { HexDumper.dumpHex(new byte[1], 1, 0); - thrown.expect(IllegalArgumentException.class); - HexDumper.dumpHex(new byte[1], -1, 0); + assertThrows(IllegalArgumentException.class, () -> HexDumper.dumpHex(new byte[1], -1, 0)); } @Test public void testBadArgumentPerGroupNegative() throws Exception { HexDumper.dumpHex(new byte[1], 1, 0); - thrown.expect(IllegalArgumentException.class); - HexDumper.dumpHex(new byte[1], 1, -1); + assertThrows(IllegalArgumentException.class, () -> HexDumper.dumpHex(new byte[1], 1, -1)); } @Test public void testBadArgumentPerGroupGreaterThanOrEqualToPerLine() throws Exception { HexDumper.dumpHex(new byte[1], 1, 0); HexDumper.dumpHex(new byte[1], 2, 1); - thrown.expect(IllegalArgumentException.class); - HexDumper.dumpHex(new byte[1], 1, 1); + assertThrows(IllegalArgumentException.class, () -> HexDumper.dumpHex(new byte[1], 1, 1)); } @Test public void testBadArgumentBytesIsNull() throws Exception { HexDumper.dumpHex(new byte[1]); - thrown.expect(NullPointerException.class); - HexDumper.dumpHex(null); + assertThrows(NullPointerException.class, () -> HexDumper.dumpHex(null)); } @Test diff --git a/javatests/google/registry/util/PosixTarHeaderTest.java b/javatests/google/registry/util/PosixTarHeaderTest.java index 6785510ff..716c61f44 100644 --- a/javatests/google/registry/util/PosixTarHeaderTest.java +++ b/javatests/google/registry/util/PosixTarHeaderTest.java @@ -17,6 +17,7 @@ package google.registry.util; import static com.google.common.io.BaseEncoding.base64; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; +import static google.registry.testing.JUnitBackports.expectThrows; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.testing.EqualsTester; @@ -27,19 +28,13 @@ import java.util.Arrays; import java.util.zip.GZIPInputStream; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; -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 PosixTarHeader}. */ @RunWith(JUnit4.class) public class PosixTarHeaderTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testGnuTarBlob() throws Exception { // This data was generated as follows: @@ -206,9 +201,9 @@ public class PosixTarHeaderTest { byte[] bytes = header.getBytes(); bytes[150] = '0'; bytes[151] = '0'; - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("chksum invalid"); - PosixTarHeader.from(bytes); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> PosixTarHeader.from(bytes)); + assertThat(thrown).hasMessageThat().contains("chksum invalid"); } @Test diff --git a/javatests/google/registry/util/RetrierTest.java b/javatests/google/registry/util/RetrierTest.java index 3f1984df2..5baf2f592 100644 --- a/javatests/google/registry/util/RetrierTest.java +++ b/javatests/google/registry/util/RetrierTest.java @@ -15,14 +15,13 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import google.registry.testing.FakeClock; import google.registry.testing.FakeSleeper; import google.registry.util.Retrier.FailureReporter; import java.util.concurrent.Callable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -30,9 +29,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class RetrierTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - Retrier retrier = new Retrier(new FakeSleeper(new FakeClock()), 3); /** An exception to throw from {@link CountingThrower}. */ @@ -86,16 +82,20 @@ public class RetrierTest { @Test public void testRetryableException() throws Exception { - thrown.expect(CountingException.class); - thrown.expectMessage("3"); - retrier.callWithRetry(new CountingThrower(3), CountingException.class); + CountingException thrown = + expectThrows( + CountingException.class, + () -> retrier.callWithRetry(new CountingThrower(3), CountingException.class)); + assertThat(thrown).hasMessageThat().contains("3"); } @Test public void testUnretryableException() throws Exception { - thrown.expect(CountingException.class); - thrown.expectMessage("1"); - retrier.callWithRetry(new CountingThrower(5), IllegalArgumentException.class); + CountingException thrown = + expectThrows( + CountingException.class, + () -> retrier.callWithRetry(new CountingThrower(5), IllegalArgumentException.class)); + assertThat(thrown).hasMessageThat().contains("1"); } @Test @@ -106,15 +106,19 @@ public class RetrierTest { @Test public void testRetryFailed_withReporter() throws Exception { - thrown.expect(CountingException.class); - thrown.expectMessage("3"); - TestReporter reporter = new TestReporter(); - try { - retrier.callWithRetry(new CountingThrower(3), reporter, CountingException.class); - } catch (CountingException expected) { - reporter.assertNumbers(2, 1); - throw expected; - } + CountingException thrown = + expectThrows( + CountingException.class, + () -> { + TestReporter reporter = new TestReporter(); + try { + retrier.callWithRetry(new CountingThrower(3), reporter, CountingException.class); + } catch (CountingException expected) { + reporter.assertNumbers(2, 1); + throw expected; + } + }); + assertThat(thrown).hasMessageThat().contains("3"); } @Test diff --git a/javatests/google/registry/util/SerializeUtilsTest.java b/javatests/google/registry/util/SerializeUtilsTest.java index 412807086..63227abfd 100644 --- a/javatests/google/registry/util/SerializeUtilsTest.java +++ b/javatests/google/registry/util/SerializeUtilsTest.java @@ -15,12 +15,11 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.SerializeUtils.deserialize; import static google.registry.util.SerializeUtils.serialize; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -34,10 +33,6 @@ public class SerializeUtilsTest { return "LOL_VALUE"; } } - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testSerialize_nullValue_returnsNull() throws Exception { assertThat(serialize(null)).isNull(); @@ -55,15 +50,17 @@ public class SerializeUtilsTest { @Test public void testSerialize_objectDoesntImplementSerialize_hasInformativeError() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unable to serialize: LOL_VALUE"); - serialize(new Lol()); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> serialize(new Lol())); + assertThat(thrown).hasMessageThat().contains("Unable to serialize: LOL_VALUE"); } @Test public void testDeserialize_badValue_hasInformativeError() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unable to deserialize: objectBytes=FF"); - deserialize(String.class, new byte[] { (byte) 0xff }); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> deserialize(String.class, new byte[] {(byte) 0xff})); + assertThat(thrown).hasMessageThat().contains("Unable to deserialize: objectBytes=FF"); } } diff --git a/javatests/google/registry/util/SqlTemplateTest.java b/javatests/google/registry/util/SqlTemplateTest.java index 2d346ef73..b2f217231 100644 --- a/javatests/google/registry/util/SqlTemplateTest.java +++ b/javatests/google/registry/util/SqlTemplateTest.java @@ -15,10 +15,9 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.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; @@ -26,9 +25,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class SqlTemplateTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testFillSqlTemplate() throws Exception { assertThat( @@ -52,98 +48,99 @@ public class SqlTemplateTest { @Test public void testFillSqlTemplate_substitutionButNoVariables() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Not found in template: ONE"); - SqlTemplate.create("") - .put("ONE", "1") - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, () -> SqlTemplate.create("").put("ONE", "1").build()); + assertThat(thrown).hasMessageThat().contains("Not found in template: ONE"); } @Test public void testFillSqlTemplate_substitutionButMissingVariables() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Not found in template: TWO"); - SqlTemplate.create("%ONE%") - .put("ONE", "1") - .put("TWO", "2") - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> SqlTemplate.create("%ONE%").put("ONE", "1").put("TWO", "2").build()); + assertThat(thrown).hasMessageThat().contains("Not found in template: TWO"); } @Test public void testFillSqlTemplate_sameKeyTwice_failsEarly() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage(""); - SqlTemplate.create("%ONE%") - .put("ONE", "1") - .put("ONE", "2"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> SqlTemplate.create("%ONE%").put("ONE", "1").put("ONE", "2")); + assertThat(thrown).hasMessageThat().contains(""); } @Test public void testFillSqlTemplate_variablesButNotEnoughSubstitutions() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("%TWO% found in template but no substitution"); - SqlTemplate.create("%ONE% %TWO%") - .put("ONE", "1") - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> SqlTemplate.create("%ONE% %TWO%").put("ONE", "1").build()); + assertThat(thrown).hasMessageThat().contains("%TWO% found in template but no substitution"); } @Test public void testFillSqlTemplate_mismatchedVariableAndSubstitution() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("%TWO% found in template but no substitution"); - SqlTemplate.create("%TWO%") - .put("TOO", "2") - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> SqlTemplate.create("%TWO%").put("TOO", "2").build()); + assertThat(thrown).hasMessageThat().contains("%TWO% found in template but no substitution"); } @Test public void testFillSqlTemplate_missingKeyVals_whatsThePoint() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("%TWO% found in template but no substitution"); - SqlTemplate.create("%TWO%") - .build(); + IllegalArgumentException thrown = + expectThrows(IllegalArgumentException.class, () -> SqlTemplate.create("%TWO%").build()); + assertThat(thrown).hasMessageThat().contains("%TWO% found in template but no substitution"); } @Test public void testFillSqlTemplate_lowercaseKey_notAllowed() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Bad substitution key: test"); - SqlTemplate.create("%test%") - .put("test", "hello world") - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> SqlTemplate.create("%test%").put("test", "hello world").build()); + assertThat(thrown).hasMessageThat().contains("Bad substitution key: test"); } @Test public void testFillSqlTemplate_substitution_disallowsSingleQuotes() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Illegal characters in foo'bar"); - SqlTemplate.create("The words are '%LOS%' and baz") - .put("LOS", "foo'bar"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> SqlTemplate.create("The words are '%LOS%' and baz").put("LOS", "foo'bar")); + assertThat(thrown).hasMessageThat().contains("Illegal characters in foo'bar"); } @Test public void testFillSqlTemplate_substitution_disallowsDoubleQuotes() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Illegal characters in foo\"bar"); - SqlTemplate.create("The words are '%LOS%' and baz") - .put("LOS", "foo\"bar"); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> SqlTemplate.create("The words are '%LOS%' and baz").put("LOS", "foo\"bar")); + assertThat(thrown).hasMessageThat().contains("Illegal characters in foo\"bar"); } @Test public void testFillSqlTemplate_quoteMismatch_throwsError() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Quote mismatch: \"%LOS%'"); - SqlTemplate.create("The words are \"%LOS%' and baz") - .put("LOS", "foobar") - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + SqlTemplate.create("The words are \"%LOS%' and baz").put("LOS", "foobar").build()); + assertThat(thrown).hasMessageThat().contains("Quote mismatch: \"%LOS%'"); } @Test public void testFillSqlTemplate_extendedQuote_throwsError() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Quote mismatch: '%LOS%"); - SqlTemplate.create("The words are '%LOS%-lol' and baz") - .put("LOS", "roid") - .build(); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> + SqlTemplate.create("The words are '%LOS%-lol' and baz").put("LOS", "roid").build()); + assertThat(thrown).hasMessageThat().contains("Quote mismatch: '%LOS%"); } } diff --git a/javatests/google/registry/util/TaskEnqueuerTest.java b/javatests/google/registry/util/TaskEnqueuerTest.java index 8a9d32c2e..e9c6b527a 100644 --- a/javatests/google/registry/util/TaskEnqueuerTest.java +++ b/javatests/google/registry/util/TaskEnqueuerTest.java @@ -16,6 +16,8 @@ package google.registry.util; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -32,7 +34,6 @@ import google.registry.testing.FakeSleeper; import org.joda.time.DateTime; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -41,10 +42,6 @@ import org.junit.runners.JUnit4; public final class TaskEnqueuerTest { private static final int MAX_RETRIES = 3; - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final AppEngineRule appEngine = AppEngineRule.builder() .withDatastore() @@ -95,9 +92,9 @@ public final class TaskEnqueuerTest { .thenThrow(new TransientFailureException("two")) .thenThrow(new TransientFailureException("three")) .thenThrow(new TransientFailureException("four")); - thrown.expect(TransientFailureException.class); - thrown.expectMessage("three"); - taskEnqueuer.enqueue(queue, task); + TransientFailureException thrown = + expectThrows(TransientFailureException.class, () -> taskEnqueuer.enqueue(queue, task)); + assertThat(thrown).hasMessageThat().contains("three"); } @Test @@ -105,8 +102,7 @@ public final class TaskEnqueuerTest { when(queue.add(ImmutableList.of(task))).thenThrow(new TransientFailureException("")); try { Thread.currentThread().interrupt(); - thrown.expect(TransientFailureException.class); - taskEnqueuer.enqueue(queue, task); + assertThrows(TransientFailureException.class, () -> taskEnqueuer.enqueue(queue, task)); } finally { Thread.interrupted(); // Clear interrupt state so it doesn't pwn other tests. } diff --git a/javatests/google/registry/util/TeeOutputStreamTest.java b/javatests/google/registry/util/TeeOutputStreamTest.java index 0a6920d4d..89cc74f62 100644 --- a/javatests/google/registry/util/TeeOutputStreamTest.java +++ b/javatests/google/registry/util/TeeOutputStreamTest.java @@ -15,25 +15,21 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; import com.google.common.collect.ImmutableSet; import java.io.ByteArrayOutputStream; import java.io.OutputStream; -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 TeeOutputStream}. */ @RunWith(JUnit4.class) public class TeeOutputStreamTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final ByteArrayOutputStream outputA = new ByteArrayOutputStream(); private final ByteArrayOutputStream outputB = new ByteArrayOutputStream(); private final ByteArrayOutputStream outputC = new ByteArrayOutputStream(); @@ -60,34 +56,32 @@ public class TeeOutputStreamTest { @Test @SuppressWarnings("resource") public void testConstructor_failsWithEmptyIterable() { - thrown.expect(IllegalArgumentException.class); - new TeeOutputStream(ImmutableSet.of()); + assertThrows(IllegalArgumentException.class, () -> new TeeOutputStream(ImmutableSet.of())); } @Test public void testWriteInteger_failsAfterClose() throws Exception { OutputStream tee = new TeeOutputStream(asList(outputA)); tee.close(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("outputstream closed"); - tee.write(1); + IllegalStateException thrown = expectThrows(IllegalStateException.class, () -> tee.write(1)); + assertThat(thrown).hasMessageThat().contains("outputstream closed"); } @Test public void testWriteByteArray_failsAfterClose() throws Exception { OutputStream tee = new TeeOutputStream(asList(outputA)); tee.close(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("outputstream closed"); - tee.write("hello".getBytes(UTF_8)); + IllegalStateException thrown = + expectThrows(IllegalStateException.class, () -> tee.write("hello".getBytes(UTF_8))); + assertThat(thrown).hasMessageThat().contains("outputstream closed"); } @Test public void testWriteByteSubarray_failsAfterClose() throws Exception { OutputStream tee = new TeeOutputStream(asList(outputA)); tee.close(); - thrown.expect(IllegalStateException.class); - thrown.expectMessage("outputstream closed"); - tee.write("hello".getBytes(UTF_8), 1, 3); + IllegalStateException thrown = + expectThrows(IllegalStateException.class, () -> tee.write("hello".getBytes(UTF_8), 1, 3)); + assertThat(thrown).hasMessageThat().contains("outputstream closed"); } } diff --git a/javatests/google/registry/util/TypeUtilsTest.java b/javatests/google/registry/util/TypeUtilsTest.java index 6f9b3995c..001db1f4e 100644 --- a/javatests/google/registry/util/TypeUtilsTest.java +++ b/javatests/google/registry/util/TypeUtilsTest.java @@ -15,22 +15,17 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import java.io.Serializable; import java.util.ArrayList; -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 TypeUtils}. */ @RunWith(JUnit4.class) public class TypeUtilsTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void test_getClassFromString_validClass() { Class clazz = @@ -40,15 +35,21 @@ public class TypeUtilsTest { @Test public void test_getClassFromString_notAssignableFrom() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("ArrayList does not implement/extend Integer"); - TypeUtils.getClassFromString("java.util.ArrayList", Integer.class); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> TypeUtils.getClassFromString("java.util.ArrayList", Integer.class)); + assertThat(thrown).hasMessageThat().contains("ArrayList does not implement/extend Integer"); } @Test public void test_getClassFromString_unknownClass() { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Failed to load class com.fake.company.nonexistent.Class"); - TypeUtils.getClassFromString("com.fake.company.nonexistent.Class", Object.class); + IllegalArgumentException thrown = + expectThrows( + IllegalArgumentException.class, + () -> TypeUtils.getClassFromString("com.fake.company.nonexistent.Class", Object.class)); + assertThat(thrown) + .hasMessageThat() + .contains("Failed to load class com.fake.company.nonexistent.Class"); } } diff --git a/javatests/google/registry/util/UrlFetchUtilsTest.java b/javatests/google/registry/util/UrlFetchUtilsTest.java index 2621fa510..64bcfb10d 100644 --- a/javatests/google/registry/util/UrlFetchUtilsTest.java +++ b/javatests/google/registry/util/UrlFetchUtilsTest.java @@ -18,6 +18,7 @@ import static com.google.common.net.HttpHeaders.CONTENT_LENGTH; import static com.google.common.net.HttpHeaders.CONTENT_TYPE; import static com.google.common.net.MediaType.CSV_UTF_8; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.UrlFetchUtils.setPayloadMultipart; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.Matchers.any; @@ -37,7 +38,6 @@ import java.util.Random; 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; import org.mockito.ArgumentCaptor; @@ -49,10 +49,6 @@ public class UrlFetchUtilsTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder() .build(); - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public final InjectRule inject = new InjectRule(); @@ -98,9 +94,14 @@ public class UrlFetchUtilsTest { public void testSetPayloadMultipart_boundaryInPayload() throws Exception { HTTPRequest request = mock(HTTPRequest.class); String payload = "I screamed------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHHH"; - thrown.expect(IllegalStateException.class); - thrown.expectMessage("Multipart data contains autogenerated boundary: " - + "------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); - setPayloadMultipart(request, "lol", "cat", CSV_UTF_8, payload); + IllegalStateException thrown = + expectThrows( + IllegalStateException.class, + () -> setPayloadMultipart(request, "lol", "cat", CSV_UTF_8, payload)); + assertThat(thrown) + .hasMessageThat() + .contains( + "Multipart data contains autogenerated boundary: " + + "------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); } } diff --git a/javatests/google/registry/whois/WhoisReaderTest.java b/javatests/google/registry/whois/WhoisReaderTest.java index 591db9e00..bc5acc3b5 100644 --- a/javatests/google/registry/whois/WhoisReaderTest.java +++ b/javatests/google/registry/whois/WhoisReaderTest.java @@ -16,6 +16,7 @@ package google.registry.whois; import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatastoreHelper.createTlds; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.LogsSubject.assertAboutLogs; import com.google.common.testing.TestLogHandler; @@ -26,7 +27,6 @@ import java.util.logging.Level; 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; @@ -35,9 +35,6 @@ import org.junit.runners.JUnit4; public class WhoisReaderTest { @Rule public final AppEngineRule appEngine = AppEngineRule.builder().withDatastore().build(); - - @Rule public final ExpectedException thrown = ExpectedException.none(); - private final FakeClock clock = new FakeClock(); private final TestLogHandler testLogHandler = new TestLogHandler(); @@ -143,20 +140,17 @@ public class WhoisReaderTest { @Test public void testTooManyArgsDomainLookup() throws Exception { - thrown.expect(WhoisException.class); - readCommand("domain example.tld foo.bar"); + assertThrows(WhoisException.class, () -> readCommand("domain example.tld foo.bar")); } @Test public void testTooFewArgsDomainLookup() throws Exception { - thrown.expect(WhoisException.class); - readCommand("domain"); + assertThrows(WhoisException.class, () -> readCommand("domain")); } @Test public void testIllegalArgDomainLookup() throws Exception { - thrown.expect(WhoisException.class); - readCommand("domain 1.1"); + assertThrows(WhoisException.class, () -> readCommand("domain 1.1")); } @Test @@ -218,20 +212,17 @@ public class WhoisReaderTest { @Test public void testTooManyArgsNameserverLookup() throws Exception { - thrown.expect(WhoisException.class); - readCommand("nameserver ns.example.tld foo.bar"); + assertThrows(WhoisException.class, () -> readCommand("nameserver ns.example.tld foo.bar")); } @Test public void testTooFewArgsNameserverLookup() throws Exception { - thrown.expect(WhoisException.class); - readCommand("nameserver"); + assertThrows(WhoisException.class, () -> readCommand("nameserver")); } @Test public void testIllegalArgNameserverLookup() throws Exception { - thrown.expect(WhoisException.class); - readCommand("nameserver 1.1"); + assertThrows(WhoisException.class, () -> readCommand("nameserver 1.1")); } @Test @@ -261,8 +252,7 @@ public class WhoisReaderTest { @Test public void testRegistrarLookupNoArgs() throws Exception { - thrown.expect(WhoisException.class); - readCommand("registrar"); + assertThrows(WhoisException.class, () -> readCommand("registrar")); } @Test @@ -312,8 +302,7 @@ public class WhoisReaderTest { @Test public void testNameserverLookupByIpTooManyArgs() throws Exception { - thrown.expect(WhoisException.class); - readCommand("nameserver 43.34.12.213 43.34.12.213"); + assertThrows(WhoisException.class, () -> readCommand("nameserver 43.34.12.213 43.34.12.213")); } @Test @@ -342,8 +331,7 @@ public class WhoisReaderTest { @Test public void testNoArgs() throws Exception { - thrown.expect(WhoisException.class); - readCommand(""); + assertThrows(WhoisException.class, () -> readCommand("")); } @Test diff --git a/javatests/google/registry/xjc/XjcObjectTest.java b/javatests/google/registry/xjc/XjcObjectTest.java index dbaac35bc..c2f61ab3c 100644 --- a/javatests/google/registry/xjc/XjcObjectTest.java +++ b/javatests/google/registry/xjc/XjcObjectTest.java @@ -16,6 +16,7 @@ package google.registry.xjc; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.util.ResourceUtils.readResourceUtf8; import static google.registry.xjc.XjcXmlTransformer.unmarshal; import static java.nio.charset.StandardCharsets.UTF_16; @@ -27,19 +28,13 @@ import google.registry.xjc.rde.XjcRdeDepositTypeType; import google.registry.xjc.rdecontact.XjcRdeContact; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -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 {@code XjcObject}. */ @RunWith(JUnit4.class) public class XjcObjectTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private static final String RDE_DEPOSIT_FULL = readResourceUtf8(XjcObjectTest.class, "testdata/rde_deposit_full.xml"); @@ -69,9 +64,9 @@ public class XjcObjectTest { public void testMarshalValidation() throws Exception { XjcRdeDeposit deposit = unmarshalFullDeposit(); deposit.setId(""); - thrown.expect(Throwable.class); - thrown.expectMessage("pattern '\\w{1,13}' for type 'depositIdType'"); - deposit.marshal(new ByteArrayOutputStream(), UTF_8); + Throwable thrown = + expectThrows(Throwable.class, () -> deposit.marshal(new ByteArrayOutputStream(), UTF_8)); + assertThat(thrown).hasMessageThat().contains("pattern '\\w{1,13}' for type 'depositIdType'"); } @Test @@ -93,10 +88,17 @@ public class XjcObjectTest { @Test public void testUnmarshalValidation() throws Exception { - thrown.expect(Throwable.class); - thrown.expectMessage("pattern '\\w{1,13}' for type 'depositIdType'"); - unmarshal(XjcRdeDeposit.class, new ByteArrayInputStream( - RDE_DEPOSIT_FULL.replaceFirst("id=\"[^\"]+\"", "id=\"\"").getBytes(UTF_8))); + Throwable thrown = + expectThrows( + Throwable.class, + () -> + unmarshal( + XjcRdeDeposit.class, + new ByteArrayInputStream( + RDE_DEPOSIT_FULL + .replaceFirst("id=\"[^\"]+\"", "id=\"\"") + .getBytes(UTF_8)))); + assertThat(thrown).hasMessageThat().contains("pattern '\\w{1,13}' for type 'depositIdType'"); } @Test diff --git a/javatests/google/registry/xjc/XmlTestdataTest.java b/javatests/google/registry/xjc/XmlTestdataTest.java index ffa7bfbe1..fcb50ccaa 100644 --- a/javatests/google/registry/xjc/XmlTestdataTest.java +++ b/javatests/google/registry/xjc/XmlTestdataTest.java @@ -15,6 +15,7 @@ package google.registry.xjc; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import static google.registry.xjc.XjcXmlTransformer.unmarshal; import static java.nio.charset.StandardCharsets.UTF_8; @@ -22,11 +23,9 @@ import google.registry.testing.TestDataHelper; import google.registry.xjc.epp.XjcEpp; import google.registry.xjc.rde.XjcRdeDeposit; import java.io.ByteArrayInputStream; -import org.junit.Rule; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; /** @@ -35,10 +34,6 @@ import org.junit.runner.RunWith; */ @RunWith(Theories.class) public class XmlTestdataTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private static class Example { final ByteArrayInputStream xmlStream; @@ -151,8 +146,7 @@ public class XmlTestdataTest { @Theory public void testInvalid(Evil v) throws Exception { - thrown.expect(Throwable.class); - thrown.expectMessage(v.error); - unmarshal(XjcObject.class, v.xmlStream); + Throwable thrown = expectThrows(Throwable.class, () -> unmarshal(XjcObject.class, v.xmlStream)); + assertThat(thrown).hasMessageThat().contains(v.error); } } diff --git a/javatests/google/registry/xml/DateAdapterTest.java b/javatests/google/registry/xml/DateAdapterTest.java index 7b2b8c7c3..11f03ffe7 100644 --- a/javatests/google/registry/xml/DateAdapterTest.java +++ b/javatests/google/registry/xml/DateAdapterTest.java @@ -15,21 +15,16 @@ package google.registry.xml; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import org.joda.time.LocalDate; -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 DateAdapter}. */ @RunWith(JUnit4.class) public class DateAdapterTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testMarshal() { assertThat(new DateAdapter().marshal( @@ -61,7 +56,8 @@ public class DateAdapterTest { @Test public void testUnmarshalInvalid() { - thrown.expect(IllegalArgumentException.class); - assertThat((new DateAdapter()).unmarshal("oh my goth")).isNull(); + assertThrows( + IllegalArgumentException.class, + () -> assertThat((new DateAdapter()).unmarshal("oh my goth")).isNull()); } } diff --git a/javatests/google/registry/xml/UtcDateTimeAdapterTest.java b/javatests/google/registry/xml/UtcDateTimeAdapterTest.java index a75cabb5f..5f7d38d1e 100644 --- a/javatests/google/registry/xml/UtcDateTimeAdapterTest.java +++ b/javatests/google/registry/xml/UtcDateTimeAdapterTest.java @@ -15,23 +15,18 @@ package google.registry.xml; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import static org.joda.time.DateTimeZone.UTC; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -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 UtcDateTimeAdapter}. */ @RunWith(JUnit4.class) public class UtcDateTimeAdapterTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testMarshal() { assertThat(new UtcDateTimeAdapter().marshal(new DateTime(2010, 10, 17, 4, 20, 0, UTC))) @@ -70,7 +65,8 @@ public class UtcDateTimeAdapterTest { @Test public void testUnmarshalInvalid() { - thrown.expect(IllegalArgumentException.class); - assertThat((new UtcDateTimeAdapter()).unmarshal("oh my goth")).isNull(); + assertThrows( + IllegalArgumentException.class, + () -> assertThat((new UtcDateTimeAdapter()).unmarshal("oh my goth")).isNull()); } } diff --git a/javatests/google/registry/xml/XmlTestUtilsTest.java b/javatests/google/registry/xml/XmlTestUtilsTest.java index cd0ef3e85..b738d299a 100644 --- a/javatests/google/registry/xml/XmlTestUtilsTest.java +++ b/javatests/google/registry/xml/XmlTestUtilsTest.java @@ -14,12 +14,11 @@ package google.registry.xml; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.TestDataHelper.loadFile; import static google.registry.xml.XmlTestUtils.assertXmlEquals; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -27,9 +26,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class XmlTestUtilsTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - void runTest(String file1, String file2) throws Exception { assertXmlEquals(loadFile(getClass(), file1), loadFile(getClass(), file2)); } @@ -41,8 +37,8 @@ public class XmlTestUtilsTest { @Test public void testInequality() throws Exception { - thrown.expect(AssertionError.class); - runTest("simple.xml", "twoextensions_feeThenLaunch.xml"); + assertThrows( + AssertionError.class, () -> runTest("simple.xml", "twoextensions_feeThenLaunch.xml")); } @Test @@ -52,7 +48,8 @@ public class XmlTestUtilsTest { @Test public void testMultipleElementsInDifferentNamespaces_differentValues() throws Exception { - thrown.expect(AssertionError.class); - runTest("twoextensions_feeThenLaunch.xml", "twoextensions_feeThenLaunch2.xml"); + assertThrows( + AssertionError.class, + () -> runTest("twoextensions_feeThenLaunch.xml", "twoextensions_feeThenLaunch2.xml")); } }