From c7484b25e0c6f0664eea65a9375d32937e2f5cc5 Mon Sep 17 00:00:00 2001 From: mcilwain Date: Tue, 21 Nov 2017 13:15:12 -0800 Subject: [PATCH] Automatically refactor some exception testing to use new JUnit rules ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=176550995 --- .../backup/GcsDiffFileListerTest.java | 13 +- .../dnsupdate/DnsMessageTransportTest.java | 11 +- .../keyring/api/ComparatorKeyringTest.java | 14 +- .../registry/model/ofy/OfyFilterTest.java | 18 +-- .../request/lock/LockHandlerImplTest.java | 24 ++- .../UpdateApplicationStatusCommandTest.java | 25 +-- .../tools/server/CreateGroupsActionTest.java | 11 +- .../registry/ui/forms/FormFieldTest.java | 151 +++++++++++------- .../registry/ui/forms/FormFieldsTest.java | 36 +++-- .../ui/server/RegistrarFormFieldsTest.java | 34 ++-- .../RegistrarSettingsActionTest.java | 10 +- .../registry/util/CidrAddressBlockTest.java | 21 +-- .../google/registry/util/ConcurrentTest.java | 25 ++- 13 files changed, 199 insertions(+), 194 deletions(-) diff --git a/javatests/google/registry/backup/GcsDiffFileListerTest.java b/javatests/google/registry/backup/GcsDiffFileListerTest.java index 6649298ee..6e892fb11 100644 --- a/javatests/google/registry/backup/GcsDiffFileListerTest.java +++ b/javatests/google/registry/backup/GcsDiffFileListerTest.java @@ -19,6 +19,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService; import static google.registry.backup.BackupUtils.GcsMetadataKeys.LOWER_BOUND_CHECKPOINT; import static google.registry.backup.ExportCommitLogDiffAction.DIFF_FILE_PREFIX; +import static google.registry.testing.JUnitBackports.assertThrows; import static java.lang.reflect.Proxy.newProxyInstance; import static org.joda.time.DateTimeZone.UTC; import static org.junit.Assert.fail; @@ -172,11 +173,7 @@ public class GcsDiffFileListerTest { addGcsFile(i, i + 1); } - try { - listDiffFiles(now.minusMinutes(9), null); - fail("Should have thrown IllegalStateException."); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> listDiffFiles(now.minusMinutes(9), null)); assertLogContains(String.format( "Found sequence from %s to %s", now.minusMinutes(9), now)); assertLogContains(String.format( @@ -204,11 +201,7 @@ public class GcsDiffFileListerTest { addGcsFile(i, i + 1); } - try { - listDiffFiles(now.minusMinutes(9), null); - fail("Should have thrown IllegalStateException."); - } catch (IllegalStateException expected) { - } + assertThrows(IllegalStateException.class, () -> listDiffFiles(now.minusMinutes(9), null)); assertLogContains(String.format( "Gap discovered in sequence terminating at %s, missing file commit_diff_until_%s", now, now.minusMinutes(5))); diff --git a/javatests/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java b/javatests/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java index 2fe235e08..31390816a 100644 --- a/javatests/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java +++ b/javatests/google/registry/dns/writer/dnsupdate/DnsMessageTransportTest.java @@ -16,7 +16,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 org.junit.Assert.fail; +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; @@ -129,12 +129,9 @@ public class DnsMessageTransportTest { Duration testTimeout = Duration.standardSeconds(1); DnsMessageTransport resolver = new DnsMessageTransport(mockFactory, UPDATE_HOST, testTimeout); Message expectedQuery = new Message(); - try { - resolver.send(expectedQuery); - fail("exception expected"); - } catch (SocketTimeoutException e) { - verify(mockSocket).setSoTimeout((int) testTimeout.getMillis()); - } + SocketTimeoutException e = + expectThrows(SocketTimeoutException.class, () -> resolver.send(expectedQuery)); + verify(mockSocket).setSoTimeout((int) testTimeout.getMillis()); } @Test diff --git a/javatests/google/registry/keyring/api/ComparatorKeyringTest.java b/javatests/google/registry/keyring/api/ComparatorKeyringTest.java index db12dd9e8..e4150ad15 100644 --- a/javatests/google/registry/keyring/api/ComparatorKeyringTest.java +++ b/javatests/google/registry/keyring/api/ComparatorKeyringTest.java @@ -15,9 +15,9 @@ package google.registry.keyring.api; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.LogsSubject.assertAboutLogs; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -242,11 +242,7 @@ public class ComparatorKeyringTest { when(secondKeyring.getRdeSigningKey()).thenReturn(keyPair); Keyring comparatorKeyring = ComparatorKeyring.create(actualKeyring, secondKeyring); - try { - comparatorKeyring.getRdeSigningKey(); - fail("Should have thrown KeyringException"); - } catch (KeyringException expected) { - } + assertThrows(KeyringException.class, () -> comparatorKeyring.getRdeSigningKey()); assertAboutLogs() .that(testLogHandler) @@ -282,11 +278,7 @@ public class ComparatorKeyringTest { when(secondKeyring.getRdeSigningKey()).thenThrow(new KeyringException("message")); Keyring comparatorKeyring = ComparatorKeyring.create(actualKeyring, secondKeyring); - try { - comparatorKeyring.getRdeSigningKey(); - fail("Should have thrown KeyringException"); - } catch (KeyringException expected) { - } + assertThrows(KeyringException.class, () -> comparatorKeyring.getRdeSigningKey()); assertAboutLogs().that(testLogHandler).hasNoLogsAtLevel(Level.SEVERE); } diff --git a/javatests/google/registry/model/ofy/OfyFilterTest.java b/javatests/google/registry/model/ofy/OfyFilterTest.java index cfc0104c6..dbc803f60 100644 --- a/javatests/google/registry/model/ofy/OfyFilterTest.java +++ b/javatests/google/registry/model/ofy/OfyFilterTest.java @@ -17,7 +17,7 @@ package google.registry.model.ofy; import static com.google.common.truth.Truth.assertThat; import static google.registry.model.ofy.ObjectifyService.initOfy; import static google.registry.testing.DatastoreHelper.newContactResource; -import static org.junit.Assert.fail; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; @@ -77,16 +77,12 @@ public class OfyFilterTest { @Test public void testFilterRegistersTypes() throws Exception { UnregisteredEntity entity = new UnregisteredEntity(5L); - try { - Key.create(entity); - fail("Should not be able to create key for unregistered entity"); - } catch (IllegalStateException e) { - assertThat(e) - .hasMessageThat() - .isEqualTo( - "class google.registry.model.ofy.OfyFilterTest$UnregisteredEntity " - + "has not been registered"); - } + IllegalStateException e = expectThrows(IllegalStateException.class, () -> Key.create(entity)); + assertThat(e) + .hasMessageThat() + .isEqualTo( + "class google.registry.model.ofy.OfyFilterTest$UnregisteredEntity " + + "has not been registered"); } /** The filter should register all types for us. */ diff --git a/javatests/google/registry/request/lock/LockHandlerImplTest.java b/javatests/google/registry/request/lock/LockHandlerImplTest.java index 61aff3de2..56c8beec5 100644 --- a/javatests/google/registry/request/lock/LockHandlerImplTest.java +++ b/javatests/google/registry/request/lock/LockHandlerImplTest.java @@ -15,7 +15,7 @@ package google.registry.request.lock; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +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; @@ -100,12 +100,11 @@ public final class LockHandlerImplTest { public void testLockSucceeds_uncheckedException() throws Exception { Lock lock = mock(Lock.class); Exception expectedException = new RuntimeException("test"); - try { - executeWithLocks(new ThrowingCallable(expectedException), lock); - fail("Expected RuntimeException"); - } catch (RuntimeException exception) { - assertThat(exception).isSameAs(expectedException); - } + RuntimeException exception = + expectThrows( + RuntimeException.class, + () -> executeWithLocks(new ThrowingCallable(expectedException), lock)); + assertThat(exception).isSameAs(expectedException); verify(lock, times(1)).release(); } @@ -113,12 +112,11 @@ public final class LockHandlerImplTest { public void testLockSucceeds_checkedException() throws Exception { Lock lock = mock(Lock.class); Exception expectedException = new Exception("test"); - try { - executeWithLocks(new ThrowingCallable(expectedException), lock); - fail("Expected RuntimeException"); - } catch (RuntimeException exception) { - assertThat(exception).hasCauseThat().isSameAs(expectedException); - } + RuntimeException exception = + expectThrows( + RuntimeException.class, + () -> executeWithLocks(new ThrowingCallable(expectedException), lock)); + assertThat(exception).hasCauseThat().isSameAs(expectedException); verify(lock, times(1)).release(); } diff --git a/javatests/google/registry/tools/UpdateApplicationStatusCommandTest.java b/javatests/google/registry/tools/UpdateApplicationStatusCommandTest.java index eef15bdc4..58f7a3d12 100644 --- a/javatests/google/registry/tools/UpdateApplicationStatusCommandTest.java +++ b/javatests/google/registry/tools/UpdateApplicationStatusCommandTest.java @@ -27,8 +27,8 @@ import static google.registry.testing.DatastoreHelper.newDomainApplication; import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DomainApplicationSubject.assertAboutApplications; import static google.registry.testing.HistoryEntrySubject.assertAboutHistoryEntries; +import static google.registry.testing.JUnitBackports.expectThrows; import static org.joda.time.DateTimeZone.UTC; -import static org.junit.Assert.fail; import google.registry.model.domain.DomainApplication; import google.registry.model.eppcommon.StatusValue; @@ -254,17 +254,18 @@ public class UpdateApplicationStatusCommandTest .setApplicationStatus(ALLOCATED) .build()); - try { - runCommandForced("--ids=2-Q9JYB4C", "--msg=\"Application rejected\"", "--status=REJECTED"); - fail("Expected IllegalStateException \"Domain application has final status ALLOCATED\""); - } catch (IllegalStateException e) { - assertThat(e.getMessage()).contains("Domain application has final status ALLOCATED"); - assertAboutApplications().that(ofy().load().entity(domainApplication).now()) - .hasApplicationStatus(ALLOCATED); - assertThat(getPollMessageCount()).isEqualTo(0); - assertAboutHistoryEntries().that(loadLastHistoryEntry()) - .hasType(HistoryEntry.Type.DOMAIN_APPLICATION_CREATE); - } + IllegalStateException e = + expectThrows( + IllegalStateException.class, + () -> + runCommandForced( + "--ids=2-Q9JYB4C", "--msg=\"Application rejected\"", "--status=REJECTED")); + assertThat(e).hasMessageThat().contains("Domain application has final status ALLOCATED"); + assertAboutApplications().that(ofy().load().entity(domainApplication).now()) + .hasApplicationStatus(ALLOCATED); + assertThat(getPollMessageCount()).isEqualTo(0); + assertAboutHistoryEntries().that(loadLastHistoryEntry()) + .hasType(HistoryEntry.Type.DOMAIN_APPLICATION_CREATE); } @Test diff --git a/javatests/google/registry/tools/server/CreateGroupsActionTest.java b/javatests/google/registry/tools/server/CreateGroupsActionTest.java index 5869a9ab1..af8cb205a 100644 --- a/javatests/google/registry/tools/server/CreateGroupsActionTest.java +++ b/javatests/google/registry/tools/server/CreateGroupsActionTest.java @@ -15,8 +15,8 @@ package google.registry.tools.server; import static com.google.common.truth.Truth.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; import static javax.servlet.http.HttpServletResponse.SC_OK; -import static org.junit.Assert.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -98,11 +98,9 @@ public class CreateGroupsActionTest { "registrar-technical-contacts@domain-registry.example", "newregistrar-technical-contacts@domain-registry.example", Role.MEMBER); - try { - runAction("NewRegistrar"); - fail("Should have thrown InternalServerErrorException."); - } catch (InternalServerErrorException e) { - String responseString = e.toString(); + InternalServerErrorException e = + expectThrows(InternalServerErrorException.class, () -> runAction("NewRegistrar")); + String responseString = e.toString(); assertThat(responseString).contains("abuse => Success"); assertThat(responseString).contains("billing => Success"); assertThat(responseString).contains("legal => Success"); @@ -113,7 +111,6 @@ public class CreateGroupsActionTest { assertThat(responseString).contains( "technical => java.lang.RuntimeException: Invalid access."); verifyGroupCreationCallsForNewRegistrar(); - } } private void verifyGroupCreationCallsForNewRegistrar() throws Exception { diff --git a/javatests/google/registry/ui/forms/FormFieldTest.java b/javatests/google/registry/ui/forms/FormFieldTest.java index bf2d3e755..111df1f07 100644 --- a/javatests/google/registry/ui/forms/FormFieldTest.java +++ b/javatests/google/registry/ui/forms/FormFieldTest.java @@ -19,6 +19,9 @@ import static com.google.common.collect.Range.atMost; import static com.google.common.collect.Range.closed; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; +import static google.registry.testing.JUnitBackports.assertThrows; +import static google.registry.testing.JUnitBackports.expectThrows; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import com.google.common.base.CharMatcher; @@ -33,9 +36,7 @@ import com.google.common.testing.NullPointerTester; import com.google.re2j.Pattern; import java.util.List; 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; @@ -45,9 +46,6 @@ public class FormFieldTest { private enum ICanHazEnum { LOL, CAT } - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testConvert_nullString_notPresent() { assertThat(FormField.named("lol").build().convert(null)).isEmpty(); @@ -77,14 +75,17 @@ public class FormFieldTest { @Test public void testEmptyToNullRequired_emptyString_throwsFfe() { - thrown.expect(equalTo(new FormFieldException("This field is required.").propagate("lol"))); - FormField.named("lol").emptyToNull().required().build().convert(""); + FormFieldException thrown = + expectThrows( + FormFieldException.class, + () -> FormField.named("lol").emptyToNull().required().build().convert("")); + assertThat(thrown, equalTo(new FormFieldException("This field is required.").propagate("lol"))); } @Test public void testEmptyToNull_typeMismatch() { - thrown.expect(IllegalStateException.class); - FormField.named("lol", Object.class).emptyToNull(); + assertThrows( + IllegalStateException.class, () -> FormField.named("lol", Object.class).emptyToNull()); } @Test @@ -130,8 +131,8 @@ public class FormFieldTest { FormField field = FormField.named("lol") .in(ImmutableSet.of("foo", "bar")) .build(); - thrown.expect(equalTo(new FormFieldException("Unrecognized value.").propagate("lol"))); - field.convert("omfg"); + FormFieldException thrown = expectThrows(FormFieldException.class, () -> field.convert("omfg")); + assertThat(thrown, equalTo(new FormFieldException("Unrecognized value.").propagate("lol"))); } @Test @@ -146,9 +147,11 @@ public class FormFieldTest { @Test public void testRange_minimum_stringLengthShorterThanMinimum_throwsFfe() { - thrown.expect(FormFieldException.class); - thrown.expectMessage("Number of characters (3) not in range [4"); - FormField.named("lol").range(atLeast(4)).build().convert("lol"); + FormFieldException thrown = + expectThrows( + FormFieldException.class, + () -> FormField.named("lol").range(atLeast(4)).build().convert("lol")); + assertThat(thrown).hasMessageThat().contains("Number of characters (3) not in range [4"); } @Test @@ -163,9 +166,11 @@ public class FormFieldTest { @Test public void testRange_maximum_stringLengthShorterThanMaximum_throwsFfe() { - thrown.expect(FormFieldException.class); - thrown.expectMessage("Number of characters (6) not in range"); - FormField.named("lol").range(atMost(5)).build().convert("omgomg"); + FormFieldException thrown = + expectThrows( + FormFieldException.class, + () -> FormField.named("lol").range(atMost(5)).build().convert("omgomg")); + assertThat(thrown).hasMessageThat().contains("Number of characters (6) not in range"); } @Test @@ -180,8 +185,8 @@ public class FormFieldTest { @Test public void testRange_typeMismatch() { - thrown.expect(IllegalStateException.class); - FormField.named("lol", Object.class).range(atMost(5)); + assertThrows( + IllegalStateException.class, () -> FormField.named("lol", Object.class).range(atMost(5))); } @Test @@ -192,14 +197,23 @@ public class FormFieldTest { @Test public void testMatches_mismatch_throwsFfeAndShowsDefaultErrorMessageWithPattern() { - thrown.expect(equalTo(new FormFieldException("Must match pattern: [a-z]+").propagate("lol"))); - FormField.named("lol").matches(Pattern.compile("[a-z]+")).build().convert("123abc456"); + FormFieldException thrown = + expectThrows( + FormFieldException.class, + () -> + FormField.named("lol") + .matches(Pattern.compile("[a-z]+")) + .build() + .convert("123abc456")); + assertThat( + thrown, equalTo(new FormFieldException("Must match pattern: [a-z]+").propagate("lol"))); } @Test public void testMatches_typeMismatch() { - thrown.expect(IllegalStateException.class); - FormField.named("lol", Object.class).matches(Pattern.compile(".")); + assertThrows( + IllegalStateException.class, + () -> FormField.named("lol", Object.class).matches(Pattern.compile("."))); } @Test @@ -246,13 +260,17 @@ public class FormFieldTest { @Test public void testAsListEmptyToNullRequired_empty_throwsFfe() { - thrown.expect(equalTo(new FormFieldException("This field is required.").propagate("lol"))); - FormField.named("lol") - .asList() - .emptyToNull() - .required() - .build() - .convert(ImmutableList.of()); + FormFieldException thrown = + expectThrows( + FormFieldException.class, + () -> + FormField.named("lol") + .asList() + .emptyToNull() + .required() + .build() + .convert(ImmutableList.of())); + assertThat(thrown, equalTo(new FormFieldException("This field is required.").propagate("lol"))); } @Test @@ -288,9 +306,12 @@ public class FormFieldTest { FormField omgField = FormField.named("omg") .asEnum(ICanHazEnum.class) .build(); - thrown.expect(equalTo(new FormFieldException("Enum ICanHazEnum does not contain 'helo'") - .propagate("omg"))); - omgField.convert("helo"); + FormFieldException thrown = + expectThrows(FormFieldException.class, () -> omgField.convert("helo")); + assertThat( + thrown, + equalTo( + new FormFieldException("Enum ICanHazEnum does not contain 'helo'").propagate("omg"))); } @Test @@ -352,38 +373,53 @@ public class FormFieldTest { @Test public void testAsListRequiredElements_nullElement_throwsFfeWithIndex() { - thrown.expect(equalTo(new FormFieldException("This field is required.") - .propagate(1) - .propagate("lol"))); - FormField.named("lol") - .emptyToNull() - .required() - .asList() - .build() - .convert(ImmutableList.of("omg", "")); + FormFieldException thrown = + expectThrows( + FormFieldException.class, + () -> + FormField.named("lol") + .emptyToNull() + .required() + .asList() + .build() + .convert(ImmutableList.of("omg", ""))); + assertThat( + thrown, + equalTo(new FormFieldException("This field is required.").propagate(1).propagate("lol"))); } @Test public void testMapAsListRequiredElements_nullElement_throwsFfeWithIndexAndKey() { - thrown.expect(equalTo(new FormFieldException("This field is required.") - .propagate("cat") - .propagate(0) - .propagate("lol"))); - FormField.mapNamed("lol") - .transform( - String.class, - input -> - FormField.named("cat").emptyToNull().required().build().extractUntyped(input).get()) - .asList() - .build() - .convert(ImmutableList.of(ImmutableMap.of("cat", ""))); + FormFieldException thrown = + expectThrows( + FormFieldException.class, + () -> + FormField.mapNamed("lol") + .transform( + String.class, + input -> + FormField.named("cat") + .emptyToNull() + .required() + .build() + .extractUntyped(input) + .get()) + .asList() + .build() + .convert(ImmutableList.of(ImmutableMap.of("cat", "")))); + assertThat( + thrown, + equalTo( + new FormFieldException("This field is required.") + .propagate("cat") + .propagate(0) + .propagate("lol"))); } @Test public void testAsListTrimmed_typeMismatch() { FormField.named("lol").trimmed().asList(); - thrown.expect(IllegalStateException.class); - FormField.named("lol").asList().trimmed(); + assertThrows(IllegalStateException.class, () -> FormField.named("lol").asList().trimmed()); } @Test @@ -423,8 +459,7 @@ public class FormFieldTest { @Test public void testTrimmed_typeMismatch() { - thrown.expect(IllegalStateException.class); - FormField.named("lol", Object.class).trimmed(); + assertThrows(IllegalStateException.class, () -> FormField.named("lol", Object.class).trimmed()); } @Test diff --git a/javatests/google/registry/ui/forms/FormFieldsTest.java b/javatests/google/registry/ui/forms/FormFieldsTest.java index 7c9dde5f7..be0d77eee 100644 --- a/javatests/google/registry/ui/forms/FormFieldsTest.java +++ b/javatests/google/registry/ui/forms/FormFieldsTest.java @@ -14,13 +14,14 @@ package google.registry.ui.forms; +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.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; 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; @@ -28,9 +29,6 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class FormFieldsTest { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testXsToken_collapsesAndTrimsWhitespace() { assertThat(FormFields.XS_TOKEN.convert(" hello \r\n\t there\n")).hasValue("hello there"); @@ -48,10 +46,15 @@ public class FormFieldsTest { @Test public void testXsNormalizedString_containsNonSpaceWhitespace_fails() { - thrown.expect(equalTo( - new FormFieldException("Must not contain tabs or multiple lines.") - .propagate("xsNormalizedString"))); - FormFields.XS_NORMALIZED_STRING.convert(" hello \r\n\t there\n"); + FormFieldException thrown = + expectThrows( + FormFieldException.class, + () -> FormFields.XS_NORMALIZED_STRING.convert(" hello \r\n\t there\n")); + assertThat( + thrown, + equalTo( + new FormFieldException("Must not contain tabs or multiple lines.") + .propagate("xsNormalizedString"))); } @Test @@ -67,9 +70,12 @@ public class FormFieldsTest { @Test public void testXsEppE164PhoneNumber_localizedNumber_fails() { - thrown.expect(FormFieldException.class); - thrown.expectMessage("Must be a valid +E.164 phone number, e.g. +1.2125650000"); - FormFields.PHONE_NUMBER.convert("(212) 565-0000"); + FormFieldException thrown = + expectThrows( + FormFieldException.class, () -> FormFields.PHONE_NUMBER.convert("(212) 565-0000")); + assertThat(thrown) + .hasMessageThat() + .contains("Must be a valid +E.164 phone number, e.g. +1.2125650000"); } @Test @@ -89,9 +95,9 @@ public class FormFieldsTest { @Test public void testXsEppRoid_missingHyphen_fails() { - thrown.expect(FormFieldException.class); - thrown.expectMessage("Please enter a valid EPP ROID, e.g. SH8013-REP"); - FormFields.ROID.convert("SH8013REP"); + FormFieldException thrown = + expectThrows(FormFieldException.class, () -> FormFields.ROID.convert("SH8013REP")); + assertThat(thrown).hasMessageThat().contains("Please enter a valid EPP ROID, e.g. SH8013-REP"); } @Test diff --git a/javatests/google/registry/ui/server/RegistrarFormFieldsTest.java b/javatests/google/registry/ui/server/RegistrarFormFieldsTest.java index 4f696d6e7..cd290a5cf 100644 --- a/javatests/google/registry/ui/server/RegistrarFormFieldsTest.java +++ b/javatests/google/registry/ui/server/RegistrarFormFieldsTest.java @@ -15,23 +15,19 @@ package google.registry.ui.server; import static com.google.common.truth.Truth8.assertThat; +import static google.registry.testing.JUnitBackports.expectThrows; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import google.registry.testing.CertificateSamples; import google.registry.ui.forms.FormFieldException; -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 RegistrarFormFields}. */ @RunWith(JUnit4.class) public class RegistrarFormFieldsTest { - - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void testValidCertificate_doesntThrowError() { assertThat(RegistrarFormFields.CLIENT_CERTIFICATE_FIELD.convert(CertificateSamples.SAMPLE_CERT)) @@ -40,10 +36,15 @@ public class RegistrarFormFieldsTest { @Test public void testBadCertificate_throwsFfe() { - thrown.expect(equalTo( - new FormFieldException("Invalid X.509 PEM certificate") - .propagate("clientCertificate"))); - RegistrarFormFields.CLIENT_CERTIFICATE_FIELD.convert("palfun"); + FormFieldException thrown = + expectThrows( + FormFieldException.class, + () -> RegistrarFormFields.CLIENT_CERTIFICATE_FIELD.convert("palfun")); + assertThat( + thrown, + equalTo( + new FormFieldException("Invalid X.509 PEM certificate") + .propagate("clientCertificate"))); } @Test @@ -56,9 +57,14 @@ public class RegistrarFormFieldsTest { @Test public void testBadCertificateHash_throwsFfe() { - thrown.expect(equalTo( - new FormFieldException("Field must contain a base64 value.") - .propagate("clientCertificateHash"))); - RegistrarFormFields.CLIENT_CERTIFICATE_HASH_FIELD.convert("~~~"); + FormFieldException thrown = + expectThrows( + FormFieldException.class, + () -> RegistrarFormFields.CLIENT_CERTIFICATE_HASH_FIELD.convert("~~~")); + assertThat( + thrown, + equalTo( + new FormFieldException("Field must contain a base64 value.") + .propagate("clientCertificateHash"))); } } diff --git a/javatests/google/registry/ui/server/registrar/RegistrarSettingsActionTest.java b/javatests/google/registry/ui/server/registrar/RegistrarSettingsActionTest.java index 813c63b96..b1a639883 100644 --- a/javatests/google/registry/ui/server/registrar/RegistrarSettingsActionTest.java +++ b/javatests/google/registry/ui/server/registrar/RegistrarSettingsActionTest.java @@ -16,11 +16,11 @@ package google.registry.ui.server.registrar; import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatastoreHelper.loadRegistrar; +import static google.registry.testing.JUnitBackports.assertThrows; import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.util.ResourceUtils.readResourceUtf8; import static java.util.Arrays.asList; -import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.never; @@ -73,12 +73,8 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase when(sessionUtils.getRegistrarForAuthResult( any(HttpServletRequest.class), any(AuthResult.class))) .thenThrow(new ForbiddenException("Not authorized to access Registrar Console")); - try { - action.handleJsonRequest(ImmutableMap.of()); - fail("expected ForbiddenException"); - } catch (ForbiddenException ex) { - assertNoTasksEnqueued("sheet"); - } + assertThrows(ForbiddenException.class, () -> action.handleJsonRequest(ImmutableMap.of())); + assertNoTasksEnqueued("sheet"); } /** diff --git a/javatests/google/registry/util/CidrAddressBlockTest.java b/javatests/google/registry/util/CidrAddressBlockTest.java index d2958764e..4b561c37a 100644 --- a/javatests/google/registry/util/CidrAddressBlockTest.java +++ b/javatests/google/registry/util/CidrAddressBlockTest.java @@ -14,6 +14,8 @@ package google.registry.util; +import static google.registry.testing.JUnitBackports.assertThrows; + import com.google.common.collect.ImmutableMap; import com.google.common.net.InetAddresses; import com.google.common.testing.NullPointerTester; @@ -289,12 +291,7 @@ public class CidrAddressBlockTest extends TestCase { Iterator i = b2.iterator(); i.next(); i.next(); - try { - // Let's run off the end and expect an IllegalArgumentException. - i.next(); - fail(); - } catch (NoSuchElementException expected) { - } + assertThrows(NoSuchElementException.class, () -> i.next()); } public void testSerializability() { @@ -310,18 +307,10 @@ public class CidrAddressBlockTest extends TestCase { } private static void assertConstructionFails(String ip) { - try { - new CidrAddressBlock(ip); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> new CidrAddressBlock(ip)); } private static void assertConstructionFails(String ip, int netmask) { - try { - new CidrAddressBlock(ip, netmask); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> new CidrAddressBlock(ip, netmask)); } } diff --git a/javatests/google/registry/util/ConcurrentTest.java b/javatests/google/registry/util/ConcurrentTest.java index f2b2159bf..7f0d54439 100644 --- a/javatests/google/registry/util/ConcurrentTest.java +++ b/javatests/google/registry/util/ConcurrentTest.java @@ -15,7 +15,7 @@ package google.registry.util; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.fail; +import static google.registry.testing.JUnitBackports.expectThrows; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -51,18 +51,17 @@ public class ConcurrentTest { @Test public void testTransform_throwsException_isSinglyWrappedByUee() throws Exception { - try { - Concurrent.transform( - ImmutableList.of(1, 2, 3), - input -> { - throw new RuntimeException("hello"); - }); - fail("Didn't throw!"); - } catch (UncheckedExecutionException e) { - // We can't use ExpectedException because root cause must be one level of indirection away. - assertThat(e).hasCauseThat().isInstanceOf(RuntimeException.class); - assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("hello"); - } + UncheckedExecutionException e = + expectThrows( + UncheckedExecutionException.class, + () -> + Concurrent.transform( + ImmutableList.of(1, 2, 3), + input -> { + throw new RuntimeException("hello"); + })); + assertThat(e).hasCauseThat().isInstanceOf(RuntimeException.class); + assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("hello"); } @Test