From 467c227a5ce2bde01a5db6a03bca9a992cdfb729 Mon Sep 17 00:00:00 2001 From: Nick Babcock Date: Thu, 29 Sep 2016 22:17:15 -0400 Subject: [PATCH] Prefer use of assertj's java8 exception assertions --- ...pwizardSSLConnectionSocketFactoryTest.java | 59 +++++--------- .../ConfigurationFactoryTest.java | 76 ++++++++----------- .../UnitOfWorkApplicationListenerTest.java | 13 ++-- .../servlets/assets/ResourceURLTest.java | 14 ++-- 4 files changed, 61 insertions(+), 101 deletions(-) diff --git a/dropwizard-client/src/test/java/io/dropwizard/client/ssl/DropwizardSSLConnectionSocketFactoryTest.java b/dropwizard-client/src/test/java/io/dropwizard/client/ssl/DropwizardSSLConnectionSocketFactoryTest.java index c6865263d0..4cdc03ad19 100644 --- a/dropwizard-client/src/test/java/io/dropwizard/client/ssl/DropwizardSSLConnectionSocketFactoryTest.java +++ b/dropwizard-client/src/test/java/io/dropwizard/client/ssl/DropwizardSSLConnectionSocketFactoryTest.java @@ -35,7 +35,8 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; public class DropwizardSSLConnectionSocketFactoryTest { private TlsConfiguration tlsConfiguration; @@ -108,12 +109,9 @@ public void shouldReturn200IfServerCertInTruststore() throws Exception { public void shouldErrorIfServerCertNotFoundInTruststore() throws Exception { tlsConfiguration.setTrustStorePath(new File(ResourceHelpers.resourceFilePath("stores/server/other_cert_truststore.ts"))); final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("tls_broken_client"); - try { - client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get(); - fail("expected ProcessingException"); - } catch (ProcessingException e) { - assertThat(e.getCause()).isInstanceOf(SSLHandshakeException.class); - } + assertThatThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get()) + .isInstanceOf(ProcessingException.class) + .hasCauseInstanceOf(SSLHandshakeException.class); } @Test @@ -127,12 +125,9 @@ public void shouldNotErrorIfServerCertSelfSignedAndSelfSignedCertsAllowed() thro @Test public void shouldErrorIfServerCertSelfSignedAndSelfSignedCertsNotAllowed() throws Exception { final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("self_sign_failure"); - try { - client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(1))).request().get(ClientResponse.class); - fail("expected ProcessingException"); - } catch (ProcessingException e) { - assertThat(e.getCause()).isInstanceOf(SSLHandshakeException.class); - } + assertThatThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(1))).request().get(ClientResponse.class)) + .isInstanceOf(ProcessingException.class) + .hasCauseInstanceOf(SSLHandshakeException.class); } @Test @@ -151,36 +146,25 @@ public void shouldErrorIfClientAuthFails() throws Exception { tlsConfiguration.setKeyStorePassword("password"); tlsConfiguration.setKeyStoreType("PKCS12"); final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("client_auth_broken"); - try { - client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get(); - fail("expected ProcessingException"); - } catch (ProcessingException e) { - assertThat(e.getCause()).isInstanceOfAny(SocketException.class, SSLHandshakeException.class); - } + final Throwable exn = catchThrowable(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(2))).request().get()); + assertThat(exn).isInstanceOf(ProcessingException.class); + assertThat(exn.getCause()).isInstanceOfAny(SocketException.class, SSLHandshakeException.class); } @Test public void shouldErrorIfHostnameVerificationOnAndServerHostnameDoesntMatch() throws Exception { final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("bad_host_broken"); - try { - client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(3))).request().get(); - fail("Expected ProcessingException"); - } catch (ProcessingException e) { - assertThat(e.getCause()).isExactlyInstanceOf(SSLPeerUnverifiedException.class); - assertThat(e.getCause().getMessage()).isEqualTo("Host name 'localhost' does not match the certificate subject provided by the peer (O=server, CN=badhost)"); - } + final Throwable exn = catchThrowable(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(3))).request().get()); + assertThat(exn).hasCauseExactlyInstanceOf(SSLPeerUnverifiedException.class); + assertThat(exn.getCause()).hasMessage("Host name 'localhost' does not match the certificate subject provided by the peer (O=server, CN=badhost)"); } @Test public void shouldErrorIfHostnameVerificationOnAndServerHostnameMatchesAndFailVerifierSpecified() throws Exception { final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).using(new FailVerifier()).build("bad_host_broken_fail_verifier"); - try { - client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get(); - fail("Expected ProcessingException"); - } catch (ProcessingException e) { - assertThat(e.getCause()).isExactlyInstanceOf(SSLPeerUnverifiedException.class); - assertThat(e.getCause().getMessage()).isEqualTo("Host name 'localhost' does not match the certificate subject provided by the peer (O=server, CN=localhost)"); - } + final Throwable exn = catchThrowable(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getLocalPort())).request().get()); + assertThat(exn).hasCauseExactlyInstanceOf(SSLPeerUnverifiedException.class); + assertThat(exn.getCause()).hasMessage("Host name 'localhost' does not match the certificate subject provided by the peer (O=server, CN=localhost)"); } @Test @@ -210,12 +194,9 @@ public void shouldBeOkIfHostnameVerificationOffAndServerHostnameMatchesAndFailVe public void shouldRejectNonSupportedProtocols() throws Exception { tlsConfiguration.setSupportedProtocols(asList("TLSv1.2")); final Client client = new JerseyClientBuilder(TLS_APP_RULE.getEnvironment()).using(jerseyClientConfiguration).build("reject_non_supported"); - try { - client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(4))).request().get(); - fail("expected ProcessingException"); - } catch (ProcessingException e) { - assertThat(e).hasRootCauseInstanceOf(SSLException.class); - } + assertThatThrownBy(() -> client.target(String.format("https://localhost:%d", TLS_APP_RULE.getPort(4))).request().get()) + .isInstanceOf(ProcessingException.class) + .hasRootCauseInstanceOf(SSLException.class); } private static class FailVerifier implements HostnameVerifier { diff --git a/dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationFactoryTest.java b/dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationFactoryTest.java index b26a6ba8cf..7118826df4 100644 --- a/dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationFactoryTest.java +++ b/dropwizard-configuration/src/test/java/io/dropwizard/configuration/ConfigurationFactoryTest.java @@ -9,7 +9,6 @@ import io.dropwizard.validation.BaseValidator; import org.assertj.core.data.MapEntry; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -27,7 +26,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; public class ConfigurationFactoryTest { @@ -417,63 +416,50 @@ public void handleDefaultConfigurationWithoutOverriding() throws Exception { @Test public void throwsAnExceptionIfDefaultConfigurationCantBeInstantiated() throws Exception { System.setProperty("dw.name", "Coda Hale Overridden"); - try { - new YamlConfigurationFactory<>(NonInsatiableExample.class, validator, Jackson.newObjectMapper(), "dw").build(); - Assert.fail("Configuration is parsed, but shouldn't be"); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Unable create an instance of the configuration class: " + - "'io.dropwizard.configuration.ConfigurationFactoryTest.NonInsatiableExample'"); - } - + final YamlConfigurationFactory factory = + new YamlConfigurationFactory<>(NonInsatiableExample.class, validator, Jackson.newObjectMapper(), "dw"); + assertThatThrownBy(factory::build) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unable create an instance of the configuration class: " + + "'io.dropwizard.configuration.ConfigurationFactoryTest.NonInsatiableExample'"); } @Test public void printsDidYouMeanOnUnrecognizedField() throws Exception { final File resourceFileName = resourceFileName("factory-test-typo.yml"); - try { - factory.build(resourceFileName); - fail("Typo in a configuration should be caught"); - } catch (ConfigurationParsingException e) { - assertThat(e.getMessage()).isEqualTo(resourceFileName + " has an error:" + NEWLINE + - " * Unrecognized field at: propertis" + NEWLINE + - " Did you mean?:" + NEWLINE + - " - properties" + NEWLINE + - " - servers" + NEWLINE + - " - type" + NEWLINE + - " - name" + NEWLINE + - " - age" + NEWLINE + - " [2 more]" + NEWLINE); - } + assertThatThrownBy(() -> factory.build(resourceFileName)) + .isInstanceOf(ConfigurationParsingException.class) + .hasMessage(resourceFileName + " has an error:" + NEWLINE + + " * Unrecognized field at: propertis" + NEWLINE + + " Did you mean?:" + NEWLINE + + " - properties" + NEWLINE + + " - servers" + NEWLINE + + " - type" + NEWLINE + + " - name" + NEWLINE + + " - age" + NEWLINE + + " [2 more]" + NEWLINE); } @Test public void incorrectTypeIsFound() throws Exception { final File resourceFileName = resourceFileName("factory-test-wrong-type.yml"); - try { - factory.build(resourceFileName); - fail("Incorrect type in a configuration should be found"); - } catch (ConfigurationParsingException e) { - assertThat(e.getMessage()).isEqualTo(resourceFileName + " has an error:" + NEWLINE + - " * Incorrect type of value at: age; is of type: String, expected: int" + NEWLINE); - } + assertThatThrownBy(() -> factory.build(resourceFileName)) + .isInstanceOf(ConfigurationParsingException.class) + .hasMessage(resourceFileName + " has an error:" + NEWLINE + + " * Incorrect type of value at: age; is of type: String, expected: int" + NEWLINE); } @Test public void printsDetailedInformationOnMalformedYaml() throws Exception { final File resourceFileName = resourceFileName("factory-test-malformed-advanced.yml"); - try { - factory.build(resourceFileName); - fail("Should print a detailed error on a malformed YAML file"); - } catch (Exception e) { - assertThat(e.getMessage()).isEqualTo( - "YAML decoding problem: while parsing a flow sequence\n" + - " in 'reader', line 2, column 7:\n" + - " type: [ coder,wizard\n" + - " ^\n" + - "expected ',' or ']', but got StreamEnd\n" + - " in 'reader', line 2, column 21:\n" + - " wizard\n" + - " ^\n"); - } + assertThatThrownBy(() -> factory.build(resourceFileName)) + .hasMessage("YAML decoding problem: while parsing a flow sequence\n" + + " in 'reader', line 2, column 7:\n" + + " type: [ coder,wizard\n" + + " ^\n" + + "expected ',' or ']', but got StreamEnd\n" + + " in 'reader', line 2, column 21:\n" + + " wizard\n" + + " ^\n"); } } diff --git a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/UnitOfWorkApplicationListenerTest.java b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/UnitOfWorkApplicationListenerTest.java index 0b883d4f29..83e9b468bb 100644 --- a/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/UnitOfWorkApplicationListenerTest.java +++ b/dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/UnitOfWorkApplicationListenerTest.java @@ -13,7 +13,6 @@ import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.context.internal.ManagedSessionContext; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; @@ -21,6 +20,7 @@ import java.lang.reflect.Method; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hibernate.resource.transaction.spi.TransactionStatus.ACTIVE; import static org.hibernate.resource.transaction.spi.TransactionStatus.NOT_ACTIVE; import static org.mockito.Mockito.doAnswer; @@ -240,13 +240,10 @@ public void beginsAndCommitsATransactionForAnalytics() throws Exception { @Test public void throwsExceptionOnNotRegisteredDatabase() throws Exception { - try { - prepareAppEvent("methodWithUnitOfWorkOnNotRegisteredDatabase"); - execute(); - Assert.fail(); - } catch (IllegalArgumentException e) { - Assert.assertEquals(e.getMessage(), "Unregistered Hibernate bundle: 'warehouse'"); - } + prepareAppEvent("methodWithUnitOfWorkOnNotRegisteredDatabase"); + assertThatThrownBy(this::execute) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unregistered Hibernate bundle: 'warehouse'"); } private void prepareAppEvent(String resourceMethodName) throws NoSuchMethodException { diff --git a/dropwizard-servlets/src/test/java/io/dropwizard/servlets/assets/ResourceURLTest.java b/dropwizard-servlets/src/test/java/io/dropwizard/servlets/assets/ResourceURLTest.java index dbdc71f41d..7621d97c24 100644 --- a/dropwizard-servlets/src/test/java/io/dropwizard/servlets/assets/ResourceURLTest.java +++ b/dropwizard-servlets/src/test/java/io/dropwizard/servlets/assets/ResourceURLTest.java @@ -11,7 +11,7 @@ import java.util.jar.JarEntry; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ResourceURLTest { private File directory; @@ -78,14 +78,10 @@ public void isDirectoryReturnsTrueForDirectoriesInJarsWithoutTrailingSlashes() t @Test public void isDirectoryThrowsResourceNotFoundExceptionForMissingDirectories() throws Exception { - URL url = Resources.getResource("META-INF/"); - url = new URL(url.toExternalForm() + "missing"); - try { - ResourceURL.isDirectory(url); - fail("should have thrown an exception"); - } catch (ResourceNotFoundException ignored) { - // expected - } + final URL url = Resources.getResource("META-INF/"); + final URL nurl = new URL(url.toExternalForm() + "missing"); + assertThatThrownBy(() -> ResourceURL.isDirectory(nurl)) + .isInstanceOf(ResourceNotFoundException.class); } @Test