Automatically refactor some exception testing to use new JUnit rules

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=176550995
This commit is contained in:
mcilwain 2017-11-21 13:15:12 -08:00 committed by jianglai
parent f041b1bac0
commit c7484b25e0
13 changed files with 199 additions and 194 deletions

View file

@ -19,6 +19,7 @@ import static com.google.common.truth.Truth.assertThat;
import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService; import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;
import static google.registry.backup.BackupUtils.GcsMetadataKeys.LOWER_BOUND_CHECKPOINT; import static google.registry.backup.BackupUtils.GcsMetadataKeys.LOWER_BOUND_CHECKPOINT;
import static google.registry.backup.ExportCommitLogDiffAction.DIFF_FILE_PREFIX; 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 java.lang.reflect.Proxy.newProxyInstance;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -172,11 +173,7 @@ public class GcsDiffFileListerTest {
addGcsFile(i, i + 1); addGcsFile(i, i + 1);
} }
try { assertThrows(IllegalStateException.class, () -> listDiffFiles(now.minusMinutes(9), null));
listDiffFiles(now.minusMinutes(9), null);
fail("Should have thrown IllegalStateException.");
} catch (IllegalStateException expected) {
}
assertLogContains(String.format( assertLogContains(String.format(
"Found sequence from %s to %s", now.minusMinutes(9), now)); "Found sequence from %s to %s", now.minusMinutes(9), now));
assertLogContains(String.format( assertLogContains(String.format(
@ -204,11 +201,7 @@ public class GcsDiffFileListerTest {
addGcsFile(i, i + 1); addGcsFile(i, i + 1);
} }
try { assertThrows(IllegalStateException.class, () -> listDiffFiles(now.minusMinutes(9), null));
listDiffFiles(now.minusMinutes(9), null);
fail("Should have thrown IllegalStateException.");
} catch (IllegalStateException expected) {
}
assertLogContains(String.format( assertLogContains(String.format(
"Gap discovered in sequence terminating at %s, missing file commit_diff_until_%s", "Gap discovered in sequence terminating at %s, missing file commit_diff_until_%s",
now, now.minusMinutes(5))); now, now.minusMinutes(5)));

View file

@ -16,7 +16,7 @@ package google.registry.dns.writer.dnsupdate;
import static com.google.common.io.BaseEncoding.base16; import static com.google.common.io.BaseEncoding.base16;
import static com.google.common.truth.Truth.assertThat; 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.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -129,12 +129,9 @@ public class DnsMessageTransportTest {
Duration testTimeout = Duration.standardSeconds(1); Duration testTimeout = Duration.standardSeconds(1);
DnsMessageTransport resolver = new DnsMessageTransport(mockFactory, UPDATE_HOST, testTimeout); DnsMessageTransport resolver = new DnsMessageTransport(mockFactory, UPDATE_HOST, testTimeout);
Message expectedQuery = new Message(); Message expectedQuery = new Message();
try { SocketTimeoutException e =
resolver.send(expectedQuery); expectThrows(SocketTimeoutException.class, () -> resolver.send(expectedQuery));
fail("exception expected"); verify(mockSocket).setSoTimeout((int) testTimeout.getMillis());
} catch (SocketTimeoutException e) {
verify(mockSocket).setSoTimeout((int) testTimeout.getMillis());
}
} }
@Test @Test

View file

@ -15,9 +15,9 @@
package google.registry.keyring.api; package google.registry.keyring.api;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.LogsSubject.assertAboutLogs; import static google.registry.testing.LogsSubject.assertAboutLogs;
import static java.nio.charset.StandardCharsets.UTF_8; 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.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -242,11 +242,7 @@ public class ComparatorKeyringTest {
when(secondKeyring.getRdeSigningKey()).thenReturn(keyPair); when(secondKeyring.getRdeSigningKey()).thenReturn(keyPair);
Keyring comparatorKeyring = ComparatorKeyring.create(actualKeyring, secondKeyring); Keyring comparatorKeyring = ComparatorKeyring.create(actualKeyring, secondKeyring);
try { assertThrows(KeyringException.class, () -> comparatorKeyring.getRdeSigningKey());
comparatorKeyring.getRdeSigningKey();
fail("Should have thrown KeyringException");
} catch (KeyringException expected) {
}
assertAboutLogs() assertAboutLogs()
.that(testLogHandler) .that(testLogHandler)
@ -282,11 +278,7 @@ public class ComparatorKeyringTest {
when(secondKeyring.getRdeSigningKey()).thenThrow(new KeyringException("message")); when(secondKeyring.getRdeSigningKey()).thenThrow(new KeyringException("message"));
Keyring comparatorKeyring = ComparatorKeyring.create(actualKeyring, secondKeyring); Keyring comparatorKeyring = ComparatorKeyring.create(actualKeyring, secondKeyring);
try { assertThrows(KeyringException.class, () -> comparatorKeyring.getRdeSigningKey());
comparatorKeyring.getRdeSigningKey();
fail("Should have thrown KeyringException");
} catch (KeyringException expected) {
}
assertAboutLogs().that(testLogHandler).hasNoLogsAtLevel(Level.SEVERE); assertAboutLogs().that(testLogHandler).hasNoLogsAtLevel(Level.SEVERE);
} }

View file

@ -17,7 +17,7 @@ package google.registry.model.ofy;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ofy.ObjectifyService.initOfy; import static google.registry.model.ofy.ObjectifyService.initOfy;
import static google.registry.testing.DatastoreHelper.newContactResource; 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.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
@ -77,16 +77,12 @@ public class OfyFilterTest {
@Test @Test
public void testFilterRegistersTypes() throws Exception { public void testFilterRegistersTypes() throws Exception {
UnregisteredEntity entity = new UnregisteredEntity(5L); UnregisteredEntity entity = new UnregisteredEntity(5L);
try { IllegalStateException e = expectThrows(IllegalStateException.class, () -> Key.create(entity));
Key.create(entity); assertThat(e)
fail("Should not be able to create key for unregistered entity"); .hasMessageThat()
} catch (IllegalStateException e) { .isEqualTo(
assertThat(e) "class google.registry.model.ofy.OfyFilterTest$UnregisteredEntity "
.hasMessageThat() + "has not been registered");
.isEqualTo(
"class google.registry.model.ofy.OfyFilterTest$UnregisteredEntity "
+ "has not been registered");
}
} }
/** The filter should register all types for us. */ /** The filter should register all types for us. */

View file

@ -15,7 +15,7 @@
package google.registry.request.lock; package google.registry.request.lock;
import static com.google.common.truth.Truth.assertThat; 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.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -100,12 +100,11 @@ public final class LockHandlerImplTest {
public void testLockSucceeds_uncheckedException() throws Exception { public void testLockSucceeds_uncheckedException() throws Exception {
Lock lock = mock(Lock.class); Lock lock = mock(Lock.class);
Exception expectedException = new RuntimeException("test"); Exception expectedException = new RuntimeException("test");
try { RuntimeException exception =
executeWithLocks(new ThrowingCallable(expectedException), lock); expectThrows(
fail("Expected RuntimeException"); RuntimeException.class,
} catch (RuntimeException exception) { () -> executeWithLocks(new ThrowingCallable(expectedException), lock));
assertThat(exception).isSameAs(expectedException); assertThat(exception).isSameAs(expectedException);
}
verify(lock, times(1)).release(); verify(lock, times(1)).release();
} }
@ -113,12 +112,11 @@ public final class LockHandlerImplTest {
public void testLockSucceeds_checkedException() throws Exception { public void testLockSucceeds_checkedException() throws Exception {
Lock lock = mock(Lock.class); Lock lock = mock(Lock.class);
Exception expectedException = new Exception("test"); Exception expectedException = new Exception("test");
try { RuntimeException exception =
executeWithLocks(new ThrowingCallable(expectedException), lock); expectThrows(
fail("Expected RuntimeException"); RuntimeException.class,
} catch (RuntimeException exception) { () -> executeWithLocks(new ThrowingCallable(expectedException), lock));
assertThat(exception).hasCauseThat().isSameAs(expectedException); assertThat(exception).hasCauseThat().isSameAs(expectedException);
}
verify(lock, times(1)).release(); verify(lock, times(1)).release();
} }

View file

@ -27,8 +27,8 @@ import static google.registry.testing.DatastoreHelper.newDomainApplication;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.DomainApplicationSubject.assertAboutApplications; import static google.registry.testing.DomainApplicationSubject.assertAboutApplications;
import static google.registry.testing.HistoryEntrySubject.assertAboutHistoryEntries; import static google.registry.testing.HistoryEntrySubject.assertAboutHistoryEntries;
import static google.registry.testing.JUnitBackports.expectThrows;
import static org.joda.time.DateTimeZone.UTC; import static org.joda.time.DateTimeZone.UTC;
import static org.junit.Assert.fail;
import google.registry.model.domain.DomainApplication; import google.registry.model.domain.DomainApplication;
import google.registry.model.eppcommon.StatusValue; import google.registry.model.eppcommon.StatusValue;
@ -254,17 +254,18 @@ public class UpdateApplicationStatusCommandTest
.setApplicationStatus(ALLOCATED) .setApplicationStatus(ALLOCATED)
.build()); .build());
try { IllegalStateException e =
runCommandForced("--ids=2-Q9JYB4C", "--msg=\"Application rejected\"", "--status=REJECTED"); expectThrows(
fail("Expected IllegalStateException \"Domain application has final status ALLOCATED\""); IllegalStateException.class,
} catch (IllegalStateException e) { () ->
assertThat(e.getMessage()).contains("Domain application has final status ALLOCATED"); runCommandForced(
assertAboutApplications().that(ofy().load().entity(domainApplication).now()) "--ids=2-Q9JYB4C", "--msg=\"Application rejected\"", "--status=REJECTED"));
.hasApplicationStatus(ALLOCATED); assertThat(e).hasMessageThat().contains("Domain application has final status ALLOCATED");
assertThat(getPollMessageCount()).isEqualTo(0); assertAboutApplications().that(ofy().load().entity(domainApplication).now())
assertAboutHistoryEntries().that(loadLastHistoryEntry()) .hasApplicationStatus(ALLOCATED);
.hasType(HistoryEntry.Type.DOMAIN_APPLICATION_CREATE); assertThat(getPollMessageCount()).isEqualTo(0);
} assertAboutHistoryEntries().that(loadLastHistoryEntry())
.hasType(HistoryEntry.Type.DOMAIN_APPLICATION_CREATE);
} }
@Test @Test

View file

@ -15,8 +15,8 @@
package google.registry.tools.server; package google.registry.tools.server;
import static com.google.common.truth.Truth.assertThat; 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 javax.servlet.http.HttpServletResponse.SC_OK;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -98,11 +98,9 @@ public class CreateGroupsActionTest {
"registrar-technical-contacts@domain-registry.example", "registrar-technical-contacts@domain-registry.example",
"newregistrar-technical-contacts@domain-registry.example", "newregistrar-technical-contacts@domain-registry.example",
Role.MEMBER); Role.MEMBER);
try { InternalServerErrorException e =
runAction("NewRegistrar"); expectThrows(InternalServerErrorException.class, () -> runAction("NewRegistrar"));
fail("Should have thrown InternalServerErrorException."); String responseString = e.toString();
} catch (InternalServerErrorException e) {
String responseString = e.toString();
assertThat(responseString).contains("abuse => Success"); assertThat(responseString).contains("abuse => Success");
assertThat(responseString).contains("billing => Success"); assertThat(responseString).contains("billing => Success");
assertThat(responseString).contains("legal => Success"); assertThat(responseString).contains("legal => Success");
@ -113,7 +111,6 @@ public class CreateGroupsActionTest {
assertThat(responseString).contains( assertThat(responseString).contains(
"technical => java.lang.RuntimeException: Invalid access."); "technical => java.lang.RuntimeException: Invalid access.");
verifyGroupCreationCallsForNewRegistrar(); verifyGroupCreationCallsForNewRegistrar();
}
} }
private void verifyGroupCreationCallsForNewRegistrar() throws Exception { private void verifyGroupCreationCallsForNewRegistrar() throws Exception {

View file

@ -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.collect.Range.closed;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.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 static org.hamcrest.Matchers.equalTo;
import com.google.common.base.CharMatcher; import com.google.common.base.CharMatcher;
@ -33,9 +36,7 @@ import com.google.common.testing.NullPointerTester;
import com.google.re2j.Pattern; import com.google.re2j.Pattern;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -45,9 +46,6 @@ public class FormFieldTest {
private enum ICanHazEnum { LOL, CAT } private enum ICanHazEnum { LOL, CAT }
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testConvert_nullString_notPresent() { public void testConvert_nullString_notPresent() {
assertThat(FormField.named("lol").build().convert(null)).isEmpty(); assertThat(FormField.named("lol").build().convert(null)).isEmpty();
@ -77,14 +75,17 @@ public class FormFieldTest {
@Test @Test
public void testEmptyToNullRequired_emptyString_throwsFfe() { public void testEmptyToNullRequired_emptyString_throwsFfe() {
thrown.expect(equalTo(new FormFieldException("This field is required.").propagate("lol"))); FormFieldException thrown =
FormField.named("lol").emptyToNull().required().build().convert(""); expectThrows(
FormFieldException.class,
() -> FormField.named("lol").emptyToNull().required().build().convert(""));
assertThat(thrown, equalTo(new FormFieldException("This field is required.").propagate("lol")));
} }
@Test @Test
public void testEmptyToNull_typeMismatch() { public void testEmptyToNull_typeMismatch() {
thrown.expect(IllegalStateException.class); assertThrows(
FormField.named("lol", Object.class).emptyToNull(); IllegalStateException.class, () -> FormField.named("lol", Object.class).emptyToNull());
} }
@Test @Test
@ -130,8 +131,8 @@ public class FormFieldTest {
FormField<String, String> field = FormField.named("lol") FormField<String, String> field = FormField.named("lol")
.in(ImmutableSet.of("foo", "bar")) .in(ImmutableSet.of("foo", "bar"))
.build(); .build();
thrown.expect(equalTo(new FormFieldException("Unrecognized value.").propagate("lol"))); FormFieldException thrown = expectThrows(FormFieldException.class, () -> field.convert("omfg"));
field.convert("omfg"); assertThat(thrown, equalTo(new FormFieldException("Unrecognized value.").propagate("lol")));
} }
@Test @Test
@ -146,9 +147,11 @@ public class FormFieldTest {
@Test @Test
public void testRange_minimum_stringLengthShorterThanMinimum_throwsFfe() { public void testRange_minimum_stringLengthShorterThanMinimum_throwsFfe() {
thrown.expect(FormFieldException.class); FormFieldException thrown =
thrown.expectMessage("Number of characters (3) not in range [4"); expectThrows(
FormField.named("lol").range(atLeast(4)).build().convert("lol"); FormFieldException.class,
() -> FormField.named("lol").range(atLeast(4)).build().convert("lol"));
assertThat(thrown).hasMessageThat().contains("Number of characters (3) not in range [4");
} }
@Test @Test
@ -163,9 +166,11 @@ public class FormFieldTest {
@Test @Test
public void testRange_maximum_stringLengthShorterThanMaximum_throwsFfe() { public void testRange_maximum_stringLengthShorterThanMaximum_throwsFfe() {
thrown.expect(FormFieldException.class); FormFieldException thrown =
thrown.expectMessage("Number of characters (6) not in range"); expectThrows(
FormField.named("lol").range(atMost(5)).build().convert("omgomg"); FormFieldException.class,
() -> FormField.named("lol").range(atMost(5)).build().convert("omgomg"));
assertThat(thrown).hasMessageThat().contains("Number of characters (6) not in range");
} }
@Test @Test
@ -180,8 +185,8 @@ public class FormFieldTest {
@Test @Test
public void testRange_typeMismatch() { public void testRange_typeMismatch() {
thrown.expect(IllegalStateException.class); assertThrows(
FormField.named("lol", Object.class).range(atMost(5)); IllegalStateException.class, () -> FormField.named("lol", Object.class).range(atMost(5)));
} }
@Test @Test
@ -192,14 +197,23 @@ public class FormFieldTest {
@Test @Test
public void testMatches_mismatch_throwsFfeAndShowsDefaultErrorMessageWithPattern() { public void testMatches_mismatch_throwsFfeAndShowsDefaultErrorMessageWithPattern() {
thrown.expect(equalTo(new FormFieldException("Must match pattern: [a-z]+").propagate("lol"))); FormFieldException thrown =
FormField.named("lol").matches(Pattern.compile("[a-z]+")).build().convert("123abc456"); 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 @Test
public void testMatches_typeMismatch() { public void testMatches_typeMismatch() {
thrown.expect(IllegalStateException.class); assertThrows(
FormField.named("lol", Object.class).matches(Pattern.compile(".")); IllegalStateException.class,
() -> FormField.named("lol", Object.class).matches(Pattern.compile(".")));
} }
@Test @Test
@ -246,13 +260,17 @@ public class FormFieldTest {
@Test @Test
public void testAsListEmptyToNullRequired_empty_throwsFfe() { public void testAsListEmptyToNullRequired_empty_throwsFfe() {
thrown.expect(equalTo(new FormFieldException("This field is required.").propagate("lol"))); FormFieldException thrown =
FormField.named("lol") expectThrows(
.asList() FormFieldException.class,
.emptyToNull() () ->
.required() FormField.named("lol")
.build() .asList()
.convert(ImmutableList.of()); .emptyToNull()
.required()
.build()
.convert(ImmutableList.of()));
assertThat(thrown, equalTo(new FormFieldException("This field is required.").propagate("lol")));
} }
@Test @Test
@ -288,9 +306,12 @@ public class FormFieldTest {
FormField<String, ICanHazEnum> omgField = FormField.named("omg") FormField<String, ICanHazEnum> omgField = FormField.named("omg")
.asEnum(ICanHazEnum.class) .asEnum(ICanHazEnum.class)
.build(); .build();
thrown.expect(equalTo(new FormFieldException("Enum ICanHazEnum does not contain 'helo'") FormFieldException thrown =
.propagate("omg"))); expectThrows(FormFieldException.class, () -> omgField.convert("helo"));
omgField.convert("helo"); assertThat(
thrown,
equalTo(
new FormFieldException("Enum ICanHazEnum does not contain 'helo'").propagate("omg")));
} }
@Test @Test
@ -352,38 +373,53 @@ public class FormFieldTest {
@Test @Test
public void testAsListRequiredElements_nullElement_throwsFfeWithIndex() { public void testAsListRequiredElements_nullElement_throwsFfeWithIndex() {
thrown.expect(equalTo(new FormFieldException("This field is required.") FormFieldException thrown =
.propagate(1) expectThrows(
.propagate("lol"))); FormFieldException.class,
FormField.named("lol") () ->
.emptyToNull() FormField.named("lol")
.required() .emptyToNull()
.asList() .required()
.build() .asList()
.convert(ImmutableList.of("omg", "")); .build()
.convert(ImmutableList.of("omg", "")));
assertThat(
thrown,
equalTo(new FormFieldException("This field is required.").propagate(1).propagate("lol")));
} }
@Test @Test
public void testMapAsListRequiredElements_nullElement_throwsFfeWithIndexAndKey() { public void testMapAsListRequiredElements_nullElement_throwsFfeWithIndexAndKey() {
thrown.expect(equalTo(new FormFieldException("This field is required.") FormFieldException thrown =
.propagate("cat") expectThrows(
.propagate(0) FormFieldException.class,
.propagate("lol"))); () ->
FormField.mapNamed("lol") FormField.mapNamed("lol")
.transform( .transform(
String.class, String.class,
input -> input ->
FormField.named("cat").emptyToNull().required().build().extractUntyped(input).get()) FormField.named("cat")
.asList() .emptyToNull()
.build() .required()
.convert(ImmutableList.of(ImmutableMap.of("cat", ""))); .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 @Test
public void testAsListTrimmed_typeMismatch() { public void testAsListTrimmed_typeMismatch() {
FormField.named("lol").trimmed().asList(); FormField.named("lol").trimmed().asList();
thrown.expect(IllegalStateException.class); assertThrows(IllegalStateException.class, () -> FormField.named("lol").asList().trimmed());
FormField.named("lol").asList().trimmed();
} }
@Test @Test
@ -423,8 +459,7 @@ public class FormFieldTest {
@Test @Test
public void testTrimmed_typeMismatch() { public void testTrimmed_typeMismatch() {
thrown.expect(IllegalStateException.class); assertThrows(IllegalStateException.class, () -> FormField.named("lol", Object.class).trimmed());
FormField.named("lol", Object.class).trimmed();
} }
@Test @Test

View file

@ -14,13 +14,14 @@
package google.registry.ui.forms; package google.registry.ui.forms;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.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 static org.hamcrest.Matchers.equalTo;
import com.google.common.testing.NullPointerTester; import com.google.common.testing.NullPointerTester;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
@ -28,9 +29,6 @@ import org.junit.runners.JUnit4;
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class FormFieldsTest { public class FormFieldsTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testXsToken_collapsesAndTrimsWhitespace() { public void testXsToken_collapsesAndTrimsWhitespace() {
assertThat(FormFields.XS_TOKEN.convert(" hello \r\n\t there\n")).hasValue("hello there"); assertThat(FormFields.XS_TOKEN.convert(" hello \r\n\t there\n")).hasValue("hello there");
@ -48,10 +46,15 @@ public class FormFieldsTest {
@Test @Test
public void testXsNormalizedString_containsNonSpaceWhitespace_fails() { public void testXsNormalizedString_containsNonSpaceWhitespace_fails() {
thrown.expect(equalTo( FormFieldException thrown =
new FormFieldException("Must not contain tabs or multiple lines.") expectThrows(
.propagate("xsNormalizedString"))); FormFieldException.class,
FormFields.XS_NORMALIZED_STRING.convert(" hello \r\n\t there\n"); () -> 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 @Test
@ -67,9 +70,12 @@ public class FormFieldsTest {
@Test @Test
public void testXsEppE164PhoneNumber_localizedNumber_fails() { public void testXsEppE164PhoneNumber_localizedNumber_fails() {
thrown.expect(FormFieldException.class); FormFieldException thrown =
thrown.expectMessage("Must be a valid +E.164 phone number, e.g. +1.2125650000"); expectThrows(
FormFields.PHONE_NUMBER.convert("(212) 565-0000"); 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 @Test
@ -89,9 +95,9 @@ public class FormFieldsTest {
@Test @Test
public void testXsEppRoid_missingHyphen_fails() { public void testXsEppRoid_missingHyphen_fails() {
thrown.expect(FormFieldException.class); FormFieldException thrown =
thrown.expectMessage("Please enter a valid EPP ROID, e.g. SH8013-REP"); expectThrows(FormFieldException.class, () -> FormFields.ROID.convert("SH8013REP"));
FormFields.ROID.convert("SH8013REP"); assertThat(thrown).hasMessageThat().contains("Please enter a valid EPP ROID, e.g. SH8013-REP");
} }
@Test @Test

View file

@ -15,23 +15,19 @@
package google.registry.ui.server; package google.registry.ui.server;
import static com.google.common.truth.Truth8.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 static org.hamcrest.Matchers.equalTo;
import google.registry.testing.CertificateSamples; import google.registry.testing.CertificateSamples;
import google.registry.ui.forms.FormFieldException; import google.registry.ui.forms.FormFieldException;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; import org.junit.runners.JUnit4;
/** Unit tests for {@link RegistrarFormFields}. */ /** Unit tests for {@link RegistrarFormFields}. */
@RunWith(JUnit4.class) @RunWith(JUnit4.class)
public class RegistrarFormFieldsTest { public class RegistrarFormFieldsTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test @Test
public void testValidCertificate_doesntThrowError() { public void testValidCertificate_doesntThrowError() {
assertThat(RegistrarFormFields.CLIENT_CERTIFICATE_FIELD.convert(CertificateSamples.SAMPLE_CERT)) assertThat(RegistrarFormFields.CLIENT_CERTIFICATE_FIELD.convert(CertificateSamples.SAMPLE_CERT))
@ -40,10 +36,15 @@ public class RegistrarFormFieldsTest {
@Test @Test
public void testBadCertificate_throwsFfe() { public void testBadCertificate_throwsFfe() {
thrown.expect(equalTo( FormFieldException thrown =
new FormFieldException("Invalid X.509 PEM certificate") expectThrows(
.propagate("clientCertificate"))); FormFieldException.class,
RegistrarFormFields.CLIENT_CERTIFICATE_FIELD.convert("palfun"); () -> RegistrarFormFields.CLIENT_CERTIFICATE_FIELD.convert("palfun"));
assertThat(
thrown,
equalTo(
new FormFieldException("Invalid X.509 PEM certificate")
.propagate("clientCertificate")));
} }
@Test @Test
@ -56,9 +57,14 @@ public class RegistrarFormFieldsTest {
@Test @Test
public void testBadCertificateHash_throwsFfe() { public void testBadCertificateHash_throwsFfe() {
thrown.expect(equalTo( FormFieldException thrown =
new FormFieldException("Field must contain a base64 value.") expectThrows(
.propagate("clientCertificateHash"))); FormFieldException.class,
RegistrarFormFields.CLIENT_CERTIFICATE_HASH_FIELD.convert("~~~"); () -> RegistrarFormFields.CLIENT_CERTIFICATE_HASH_FIELD.convert("~~~"));
assertThat(
thrown,
equalTo(
new FormFieldException("Field must contain a base64 value.")
.propagate("clientCertificateHash")));
} }
} }

View file

@ -16,11 +16,11 @@ package google.registry.ui.server.registrar;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.loadRegistrar; 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.assertNoTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static google.registry.util.ResourceUtils.readResourceUtf8; import static google.registry.util.ResourceUtils.readResourceUtf8;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
@ -73,12 +73,8 @@ public class RegistrarSettingsActionTest extends RegistrarSettingsActionTestCase
when(sessionUtils.getRegistrarForAuthResult( when(sessionUtils.getRegistrarForAuthResult(
any(HttpServletRequest.class), any(AuthResult.class))) any(HttpServletRequest.class), any(AuthResult.class)))
.thenThrow(new ForbiddenException("Not authorized to access Registrar Console")); .thenThrow(new ForbiddenException("Not authorized to access Registrar Console"));
try { assertThrows(ForbiddenException.class, () -> action.handleJsonRequest(ImmutableMap.of()));
action.handleJsonRequest(ImmutableMap.of()); assertNoTasksEnqueued("sheet");
fail("expected ForbiddenException");
} catch (ForbiddenException ex) {
assertNoTasksEnqueued("sheet");
}
} }
/** /**

View file

@ -14,6 +14,8 @@
package google.registry.util; package google.registry.util;
import static google.registry.testing.JUnitBackports.assertThrows;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.net.InetAddresses; import com.google.common.net.InetAddresses;
import com.google.common.testing.NullPointerTester; import com.google.common.testing.NullPointerTester;
@ -289,12 +291,7 @@ public class CidrAddressBlockTest extends TestCase {
Iterator<InetAddress> i = b2.iterator(); Iterator<InetAddress> i = b2.iterator();
i.next(); i.next();
i.next(); i.next();
try { assertThrows(NoSuchElementException.class, () -> i.next());
// Let's run off the end and expect an IllegalArgumentException.
i.next();
fail();
} catch (NoSuchElementException expected) {
}
} }
public void testSerializability() { public void testSerializability() {
@ -310,18 +307,10 @@ public class CidrAddressBlockTest extends TestCase {
} }
private static void assertConstructionFails(String ip) { private static void assertConstructionFails(String ip) {
try { assertThrows(IllegalArgumentException.class, () -> new CidrAddressBlock(ip));
new CidrAddressBlock(ip);
fail();
} catch (IllegalArgumentException expected) {
}
} }
private static void assertConstructionFails(String ip, int netmask) { private static void assertConstructionFails(String ip, int netmask) {
try { assertThrows(IllegalArgumentException.class, () -> new CidrAddressBlock(ip, netmask));
new CidrAddressBlock(ip, netmask);
fail();
} catch (IllegalArgumentException expected) {
}
} }
} }

View file

@ -15,7 +15,7 @@
package google.registry.util; package google.registry.util;
import static com.google.common.truth.Truth.assertThat; 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.Function;
import com.google.common.base.Functions; import com.google.common.base.Functions;
@ -51,18 +51,17 @@ public class ConcurrentTest {
@Test @Test
public void testTransform_throwsException_isSinglyWrappedByUee() throws Exception { public void testTransform_throwsException_isSinglyWrappedByUee() throws Exception {
try { UncheckedExecutionException e =
Concurrent.transform( expectThrows(
ImmutableList.of(1, 2, 3), UncheckedExecutionException.class,
input -> { () ->
throw new RuntimeException("hello"); Concurrent.transform(
}); ImmutableList.of(1, 2, 3),
fail("Didn't throw!"); input -> {
} catch (UncheckedExecutionException e) { throw new RuntimeException("hello");
// We can't use ExpectedException because root cause must be one level of indirection away. }));
assertThat(e).hasCauseThat().isInstanceOf(RuntimeException.class); assertThat(e).hasCauseThat().isInstanceOf(RuntimeException.class);
assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("hello"); assertThat(e).hasCauseThat().hasMessageThat().isEqualTo("hello");
}
} }
@Test @Test