diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java index 11697546825..e9d75b6196e 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/convert/ConversionServiceParameterValueMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ import org.springframework.format.support.DefaultFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -61,15 +60,14 @@ public class ConversionServiceParameterValueMapperTests { given(conversionService.convert(any(), any())).willThrow(error); ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper( conversionService); - try { - mapper.mapParameterValue(new TestOperationParameter(Integer.class), "123"); - fail("Did not throw"); - } - catch (ParameterMappingException ex) { - assertThat(ex.getValue()).isEqualTo("123"); - assertThat(ex.getParameter().getType()).isEqualTo(Integer.class); - assertThat(ex.getCause()).isEqualTo(error); - } + assertThatExceptionOfType(ParameterMappingException.class) + .isThrownBy(() -> mapper.mapParameterValue( + new TestOperationParameter(Integer.class), "123")) + .satisfies((ex) -> { + assertThat(ex.getValue()).isEqualTo("123"); + assertThat(ex.getParameter().getType()).isEqualTo(Integer.class); + assertThat(ex.getCause()).isEqualTo(error); + }); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java index 062511a8b46..b08d7a2c074 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/reactive/HttpTraceWebFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchangeDecorator; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -123,19 +123,14 @@ public class HttpTraceWebFilterTests { @Test public void statusIsAssumedToBe500WhenChainFails() throws ServletException, IOException { - try { - this.filter - .filter(MockServerWebExchange - .from(MockServerHttpRequest.get("https://api.example.com")), - (exchange) -> Mono.error(new RuntimeException())) - .block(Duration.ofSeconds(30)); - fail(); - } - catch (Exception ex) { - assertThat(this.repository.findAll()).hasSize(1); - assertThat(this.repository.findAll().get(0).getResponse().getStatus()) - .isEqualTo(500); - } + assertThatExceptionOfType(Exception.class).isThrownBy(() -> this.filter + .filter(MockServerWebExchange + .from(MockServerHttpRequest.get("https://api.example.com")), + (exchange) -> Mono.error(new RuntimeException())) + .block(Duration.ofSeconds(30))); + assertThat(this.repository.findAll()).hasSize(1); + assertThat(this.repository.findAll().get(0).getResponse().getStatus()) + .isEqualTo(500); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java index 4bc332e5270..76f5ca6b265 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/trace/http/servlet/HttpTraceFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatIOException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -106,25 +106,24 @@ public class HttpTraceFilterTests { @Test public void statusIsAssumedToBe500WhenChainFails() throws ServletException, IOException { - try { - this.filter.doFilter(new MockHttpServletRequest(), - new MockHttpServletResponse(), new MockFilterChain(new HttpServlet() { + assertThatIOException() + .isThrownBy(() -> this.filter.doFilter(new MockHttpServletRequest(), + new MockHttpServletResponse(), + new MockFilterChain(new HttpServlet() { - @Override - protected void service(HttpServletRequest req, - HttpServletResponse resp) - throws ServletException, IOException { - throw new IOException(); - } + @Override + protected void service(HttpServletRequest req, + HttpServletResponse resp) + throws ServletException, IOException { + throw new IOException(); + } - })); - fail("Filter swallowed IOException"); - } - catch (IOException ex) { - assertThat(this.repository.findAll()).hasSize(1); - assertThat(this.repository.findAll().get(0).getResponse().getStatus()) - .isEqualTo(500); - } + }))) + .satisfies((ex) -> { + assertThat(this.repository.findAll()).hasSize(1); + assertThat(this.repository.findAll().get(0).getResponse().getStatus()) + .isEqualTo(500); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java index 17284b37085..b0e95570460 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import org.springframework.context.annotation.ImportSelector; import org.springframework.core.type.AnnotationMetadata; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link OnBeanCondition} when deduction of the bean's type fails @@ -44,21 +44,20 @@ public class OnBeanConditionTypeDeductionFailureTests { @Test public void conditionalOnMissingBeanWithDeducedTypeThatIsPartiallyMissingFromClassPath() { - try { - new AnnotationConfigApplicationContext(ImportingConfiguration.class).close(); - fail("Context refresh was successful"); - } - catch (Exception ex) { - Throwable beanTypeDeductionException = findNestedCause(ex, - BeanTypeDeductionException.class); - assertThat(beanTypeDeductionException) - .hasMessage("Failed to deduce bean type for " - + OnMissingBeanConfiguration.class.getName() - + ".objectMapper"); - assertThat(findNestedCause(beanTypeDeductionException, - NoClassDefFoundError.class)).isNotNull(); + assertThatExceptionOfType(Exception.class).isThrownBy( + () -> new AnnotationConfigApplicationContext(ImportingConfiguration.class) + .close()) + .satisfies((ex) -> { + Throwable beanTypeDeductionException = findNestedCause(ex, + BeanTypeDeductionException.class); + assertThat(beanTypeDeductionException) + .hasMessage("Failed to deduce bean type for " + + OnMissingBeanConfiguration.class.getName() + + ".objectMapper"); + assertThat(findNestedCause(beanTypeDeductionException, + NoClassDefFoundError.class)).isNotNull(); - } + }); } private Throwable findNestedCause(Throwable ex, Class target) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java index 36db35ca78f..66e4c8fbc93 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourceInitializerInvokerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link DataSourceInitializerInvoker}. @@ -178,16 +178,13 @@ public class DataSourceInitializerInvokerTests { private void assertDataSourceNotInitialized(DataSource dataSource) { JdbcOperations template = new JdbcTemplate(dataSource); - try { - template.queryForObject("SELECT COUNT(*) from BAR", Integer.class); - fail("Query should have failed as BAR table does not exist"); - } - catch (BadSqlGrammarException ex) { - SQLException sqlException = ex.getSQLException(); - int expectedCode = -5501; // user lacks privilege or object not - // found - assertThat(sqlException.getErrorCode()).isEqualTo(expectedCode); - } + assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( + () -> template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)) + .satisfies((ex) -> { + SQLException sqlException = ex.getSQLException(); + int expectedCode = -5501; // user lacks privilege or object not found + assertThat(sqlException.getErrorCode()).isEqualTo(expectedCode); + }); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java index 020025f4563..927060fa032 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link JooqAutoConfiguration}. @@ -90,15 +90,10 @@ public class JooqAutoConfigurationTests { "insert into jooqtest (name) values ('foo');")); dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "1")); - try { - dsl.transaction(new ExecuteSql(dsl, - "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');")); - fail("An DataIntegrityViolationException should have been thrown."); - } - catch (DataIntegrityViolationException ex) { - // Ignore - } + assertThatExceptionOfType(DataIntegrityViolationException.class) + .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, + "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');"))); dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest;", "2")); }); @@ -120,19 +115,14 @@ public class JooqAutoConfigurationTests { "insert into jooqtest_tx (name) values ('foo');")); dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); - try { - dsl.transaction(new ExecuteSql(dsl, - "insert into jooqtest (name) values ('bar');", - "insert into jooqtest (name) values ('foo');")); - fail("A DataIntegrityViolationException should have been thrown."); - } - catch (DataIntegrityViolationException ex) { - // Ignore - } + assertThatExceptionOfType(DataIntegrityViolationException.class) + .isThrownBy(() -> dsl.transaction(new ExecuteSql(dsl, + "insert into jooqtest (name) values ('bar');", + "insert into jooqtest (name) values ('foo');"))); dsl.transaction(new AssertFetch(dsl, "select count(*) as total from jooqtest_tx;", "1")); - }); + } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java index 793b58e0e1a..18fe5a06b72 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/logging/ConditionEvaluationReportLoggingListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,8 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.fail; /** * Tests for {@link ConditionEvaluationReportLoggingListener}. @@ -76,15 +76,10 @@ public class ConditionEvaluationReportLoggingListenerTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(ErrorConfig.class); - try { - context.refresh(); - fail("Did not error"); - } - catch (Exception ex) { - withDebugLogging( - () -> this.initializer.onApplicationEvent(new ApplicationFailedEvent( - new SpringApplication(), new String[0], context, ex))); - } + assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh).satisfies( + (ex) -> withDebugLogging(() -> this.initializer.onApplicationEvent( + new ApplicationFailedEvent(new SpringApplication(), new String[0], + context, ex)))); assertThat(this.outputCapture.toString()) .contains("CONDITIONS EVALUATION REPORT"); } @@ -94,14 +89,10 @@ public class ConditionEvaluationReportLoggingListenerTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); this.initializer.initialize(context); context.register(ErrorConfig.class); - try { - context.refresh(); - fail("Did not error"); - } - catch (Exception ex) { - this.initializer.onApplicationEvent(new ApplicationFailedEvent( - new SpringApplication(), new String[0], context, ex)); - } + assertThatExceptionOfType(Exception.class).isThrownBy(context::refresh) + .satisfies((ex) -> this.initializer.onApplicationEvent( + new ApplicationFailedEvent(new SpringApplication(), new String[0], + context, ex))); assertThat(this.outputCapture.toString()).contains("Error starting" + " ApplicationContext. To display the conditions report re-run" + " your application with 'debug' enabled."); diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java index 037246b5b67..18b5953ce27 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/GrabCommandIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import org.springframework.boot.cli.command.grab.GrabCommand; import org.springframework.util.FileSystemUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration tests for {@link GrabCommand} @@ -64,14 +64,10 @@ public class GrabCommandIntegrationTests { @Test public void duplicateDependencyManagementBomAnnotationsProducesAnError() { - try { - this.cli.grab("duplicateDependencyManagementBom.groovy"); - fail(); - } - catch (Exception ex) { - assertThat(ex.getMessage()) - .contains("Duplicate @DependencyManagementBom annotation"); - } + assertThatExceptionOfType(Exception.class) + .isThrownBy( + () -> this.cli.grab("duplicateDependencyManagementBom.groovy")) + .withMessageContaining("Duplicate @DependencyManagementBom annotation"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java index a8c806d9171..151973cd308 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/SocketTargetServerConnectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link SocketTargetServerConnection}. @@ -75,16 +75,13 @@ public class SocketTargetServerConnectionTests { this.server.start(); ByteChannel channel = this.connection.open(10); long startTime = System.currentTimeMillis(); - try { - channel.read(ByteBuffer.allocate(5)); - fail("No socket timeout thrown"); - } - catch (SocketTimeoutException ex) { - // Expected - long runTime = System.currentTimeMillis() - startTime; - assertThat(runTime).isGreaterThanOrEqualTo(10L); - assertThat(runTime).isLessThan(10000L); - } + assertThatExceptionOfType(SocketTimeoutException.class) + .isThrownBy(() -> channel.read(ByteBuffer.allocate(5))) + .satisfies((ex) -> { + long runTime = System.currentTimeMillis() - startTime; + assertThat(runTime).isGreaterThanOrEqualTo(10L); + assertThat(runTime).isLessThan(10000L); + }); } private static class MockServer { @@ -162,7 +159,7 @@ public class SocketTargetServerConnectionTests { channel.close(); } catch (Exception ex) { - fail(); + throw new RuntimeException(ex); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java index 982913be180..dda6df7b591 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWebDriverIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link WebMvcTest} with {@link WebDriver}. @@ -62,13 +62,8 @@ public class WebMvcTestWebDriverIntegrationTests { this.webDriver.get("/html"); WebElement element = this.webDriver.findElement(By.tagName("body")); assertThat(element.getText()).isEqualTo("Hello"); - try { - previousWebDriver.getWindowHandle(); - fail("Did not call quit()"); - } - catch (NoSuchWindowException ex) { - // Expected - } + assertThatExceptionOfType(NoSuchWindowException.class) + .isThrownBy(previousWebDriver::getWindowHandle); assertThat(previousWebDriver).isNotNull().isNotSameAs(this.webDriver); } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java index 3dbe4e9c28c..0d4b2f9ab92 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIOException; -import static org.junit.Assert.fail; /** * Abstract tests for {@link AbstractApplicationContextRunner} implementations. @@ -153,14 +153,11 @@ public abstract class AbstractApplicationContextRunnerTests { - try { - ClassUtils.forName(Gson.class.getName(), - context.getClassLoader()); - fail("Should have thrown a ClassNotFoundException"); - } - catch (ClassNotFoundException ex) { - // expected - } + assertThatExceptionOfType(ClassNotFoundException.class) + .isThrownBy(() -> { + ClassUtils.forName(Gson.class.getName(), + context.getClassLoader()); + }); }); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java index 5c421e0f0bb..4809a5c3d2a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,7 +107,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.atLeastOnce; @@ -770,17 +769,11 @@ public class SpringApplicationTests { ExitStatusException failure = new ExitStatusException(); willThrow(failure).given(listener) .onApplicationEvent(isA(ApplicationReadyEvent.class)); - try { - application.run(); - fail("Run should have failed with a RuntimeException"); - } - catch (RuntimeException ex) { - verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); - verify(listener, never()) - .onApplicationEvent(isA(ApplicationFailedEvent.class)); - assertThat(exitCodeListener.getExitCode()).isEqualTo(11); - assertThat(this.output.toString()).contains("Application run failed"); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(application::run); + verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); + verify(listener, never()).onApplicationEvent(isA(ApplicationFailedEvent.class)); + assertThat(exitCodeListener.getExitCode()).isEqualTo(11); + assertThat(this.output.toString()).contains("Application run failed"); } @Test @@ -855,12 +848,7 @@ public class SpringApplicationTests { ExitCodeListener listener = new ExitCodeListener(); application.addListeners(listener); application.setWebApplicationType(WebApplicationType.NONE); - try { - application.run(); - fail("Did not throw"); - } - catch (IllegalStateException ex) { - } + assertThatIllegalStateException().isThrownBy(application::run); verify(handler).registerExitCode(11); assertThat(listener.getExitCode()).isEqualTo(11); } @@ -880,12 +868,7 @@ public class SpringApplicationTests { ExitCodeListener listener = new ExitCodeListener(); application.addListeners(listener); application.setWebApplicationType(WebApplicationType.NONE); - try { - application.run(); - fail("Did not throw"); - } - catch (IllegalStateException ex) { - } + assertThatIllegalStateException().isThrownBy(application::run); verify(handler).registerExitCode(11); assertThat(listener.getExitCode()).isEqualTo(11); } @@ -905,12 +888,7 @@ public class SpringApplicationTests { ExitCodeListener listener = new ExitCodeListener(); application.addListeners(listener); application.setWebApplicationType(WebApplicationType.NONE); - try { - application.run(); - fail("Did not throw"); - } - catch (RuntimeException ex) { - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(application::run); ArgumentCaptor exceptionCaptor = ArgumentCaptor .forClass(RuntimeException.class); verify(handler).registerLoggedException(exceptionCaptor.capture()); @@ -998,16 +976,12 @@ public class SpringApplicationTests { ApplicationListener listener = mock(ApplicationListener.class); SpringApplication application = new SpringApplication(ExampleConfig.class); application.addListeners(listener); - try { - application.run(); - fail("Run should have failed with an ApplicationContextException"); - } - catch (ApplicationContextException ex) { - verifyListenerEvents(listener, ApplicationStartingEvent.class, - ApplicationEnvironmentPreparedEvent.class, - ApplicationContextInitializedEvent.class, - ApplicationPreparedEvent.class, ApplicationFailedEvent.class); - } + assertThatExceptionOfType(ApplicationContextException.class) + .isThrownBy(application::run); + verifyListenerEvents(listener, ApplicationStartingEvent.class, + ApplicationEnvironmentPreparedEvent.class, + ApplicationContextInitializedEvent.class, ApplicationPreparedEvent.class, + ApplicationFailedEvent.class); } @SuppressWarnings("unchecked") @@ -1018,16 +992,12 @@ public class SpringApplicationTests { BrokenPostConstructConfig.class); application.setWebApplicationType(WebApplicationType.NONE); application.addListeners(listener); - try { - application.run(); - fail("Run should have failed with a BeanCreationException"); - } - catch (BeanCreationException ex) { - verifyListenerEvents(listener, ApplicationStartingEvent.class, - ApplicationEnvironmentPreparedEvent.class, - ApplicationContextInitializedEvent.class, - ApplicationPreparedEvent.class, ApplicationFailedEvent.class); - } + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(application::run); + verifyListenerEvents(listener, ApplicationStartingEvent.class, + ApplicationEnvironmentPreparedEvent.class, + ApplicationContextInitializedEvent.class, ApplicationPreparedEvent.class, + ApplicationFailedEvent.class); } @SuppressWarnings("unchecked") @@ -1038,13 +1008,9 @@ public class SpringApplicationTests { SpringApplication application = new SpringApplication(ExampleConfig.class); application.addInitializers((applicationContext) -> applicationContext .addApplicationListener(listener)); - try { - application.run(); - fail("Run should have failed with an ApplicationContextException"); - } - catch (ApplicationContextException ex) { - verifyListenerEvents(listener, ApplicationFailedEvent.class); - } + assertThatExceptionOfType(ApplicationContextException.class) + .isThrownBy(application::run); + verifyListenerEvents(listener, ApplicationFailedEvent.class); } @SuppressWarnings("unchecked") @@ -1056,13 +1022,9 @@ public class SpringApplicationTests { application.setWebApplicationType(WebApplicationType.NONE); application.addInitializers((applicationContext) -> applicationContext .addApplicationListener(listener)); - try { - application.run(); - fail("Run should have failed with a BeanCreationException"); - } - catch (BeanCreationException ex) { - verifyListenerEvents(listener, ApplicationFailedEvent.class); - } + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(application::run); + verifyListenerEvents(listener, ApplicationFailedEvent.class); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java index dc6bf7afe1c..e6f82836995 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,7 +82,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.entry; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -702,15 +701,13 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenHasConfigurationPropertiesValidatorShouldApplyValidator() { - try { - load(WithCustomValidatorConfiguration.class); - fail("Did not throw"); - } - catch (Exception ex) { - assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()) - .hasCauseExactlyInstanceOf(BindValidationException.class); - } + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> load(WithCustomValidatorConfiguration.class)) + .satisfies((ex) -> { + assertThat(ex).hasCauseInstanceOf(BindException.class); + assertThat(ex.getCause()) + .hasCauseExactlyInstanceOf(BindValidationException.class); + }); } @Test @@ -723,15 +720,12 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenConfigurationPropertiesIsAlsoValidatorShouldApplyValidator() { - try { - load(ValidatorProperties.class); - fail("Did not throw"); - } - catch (Exception ex) { - assertThat(ex).hasCauseInstanceOf(BindException.class); - assertThat(ex.getCause()) - .hasCauseExactlyInstanceOf(BindValidationException.class); - } + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> load(ValidatorProperties.class)).satisfies((ex) -> { + assertThat(ex).hasCauseInstanceOf(BindException.class); + assertThat(ex.getCause()) + .hasCauseExactlyInstanceOf(BindValidationException.class); + }); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java index 41c572fa13f..d2ff61a9cd5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ArrayBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import org.springframework.boot.context.properties.source.MockConfigurationPrope import org.springframework.core.ResolvableType; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; @@ -145,18 +145,16 @@ public class ArrayBinderTests { source.put("foo[1]", "1"); source.put("foo[3]", "3"); this.sources.add(source); - try { - this.binder.bind("foo", INTEGER_ARRAY); - fail("No exception thrown"); - } - catch (BindException ex) { - Set unbound = ((UnboundConfigurationPropertiesException) ex - .getCause()).getUnboundProperties(); - assertThat(unbound.size()).isEqualTo(1); - ConfigurationProperty property = unbound.iterator().next(); - assertThat(property.getName().toString()).isEqualTo("foo[3]"); - assertThat(property.getValue()).isEqualTo("3"); - } + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("foo", INTEGER_ARRAY)) + .satisfies((ex) -> { + Set unbound = ((UnboundConfigurationPropertiesException) ex + .getCause()).getUnboundProperties(); + assertThat(unbound.size()).isEqualTo(1); + ConfigurationProperty property = unbound.iterator().next(); + assertThat(property.getName().toString()).isEqualTo("foo[3]"); + assertThat(property.getValue()).isEqualTo("3"); + }); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java index 16d3ff3bf33..85d2e0dab37 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/CollectionBinderTests.java @@ -38,7 +38,7 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.test.context.support.TestPropertySourceUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link CollectionBinder}. @@ -121,18 +121,16 @@ public class CollectionBinderTests { source.put("foo[1]", "1"); source.put("foo[3]", "3"); this.sources.add(source); - try { - this.binder.bind("foo", INTEGER_LIST); - fail("No exception thrown"); - } - catch (BindException ex) { - Set unbound = ((UnboundConfigurationPropertiesException) ex - .getCause()).getUnboundProperties(); - assertThat(unbound).hasSize(1); - ConfigurationProperty property = unbound.iterator().next(); - assertThat(property.getName().toString()).isEqualTo("foo[3]"); - assertThat(property.getValue()).isEqualTo("3"); - } + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("foo", INTEGER_LIST)) + .satisfies((ex) -> { + Set unbound = ((UnboundConfigurationPropertiesException) ex + .getCause()).getUnboundProperties(); + assertThat(unbound).hasSize(1); + ConfigurationProperty property = unbound.iterator().next(); + assertThat(property.getName().toString()).isEqualTo("foo[3]"); + assertThat(property.getValue()).isEqualTo("3"); + }); } @Test @@ -142,19 +140,16 @@ public class CollectionBinderTests { source.put("foo[1].value", "2"); source.put("foo[4].value", "4"); this.sources.add(source); - try { - Bindable> target = Bindable.listOf(JavaBean.class); - this.binder.bind("foo", target); - fail("No exception thrown"); - } - catch (BindException ex) { - Set unbound = ((UnboundConfigurationPropertiesException) ex - .getCause()).getUnboundProperties(); - assertThat(unbound).hasSize(1); - ConfigurationProperty property = unbound.iterator().next(); - assertThat(property.getName().toString()).isEqualTo("foo[4].value"); - assertThat(property.getValue()).isEqualTo("4"); - } + Bindable> target = Bindable.listOf(JavaBean.class); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("foo", target)).satisfies((ex) -> { + Set unbound = ((UnboundConfigurationPropertiesException) ex + .getCause()).getUnboundProperties(); + assertThat(unbound).hasSize(1); + ConfigurationProperty property = unbound.iterator().next(); + assertThat(property.getName().toString()).isEqualTo("foo[4].value"); + assertThat(property.getValue()).isEqualTo("4"); + }); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java index 4d8401b9b0a..b3d4e399c66 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/NoUnboundElementsBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import org.springframework.boot.context.properties.source.ConfigurationPropertyS import org.springframework.boot.context.properties.source.MockConfigurationPropertySource; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link NoUnboundElementsBindHandler}. @@ -75,15 +75,11 @@ public class NoUnboundElementsBindHandlerTests { source.put("example.baz", "bar"); this.sources.add(source); this.binder = new Binder(this.sources); - try { - this.binder.bind("example", Bindable.of(Example.class), - new NoUnboundElementsBindHandler()); - fail("did not throw"); - } - catch (BindException ex) { - assertThat(ex.getCause().getMessage()) - .contains("The elements [example.baz] were left unbound"); - } + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), + new NoUnboundElementsBindHandler())) + .satisfies((ex) -> assertThat(ex.getCause().getMessage()) + .contains("The elements [example.baz] were left unbound")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java index 4739f8f5c35..49de5d96bcb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ import org.springframework.boot.context.properties.source.ConfigurationPropertyN import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.fail; /** * Tests for {@link ConfigurationPropertyName}. @@ -78,13 +77,9 @@ public class ConfigurationPropertyNameTests { public void ofNameShouldNotContainInvalidChars() { String invalid = "_@$%*+=':;"; for (char c : invalid.toCharArray()) { - try { - ConfigurationPropertyName.of("foo" + c); - fail("Did not throw for invalid char " + c); - } - catch (InvalidConfigurationPropertyNameException ex) { - assertThat(ex.getMessage()).contains("is not valid"); - } + assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) + .isThrownBy(() -> ConfigurationPropertyName.of("foo" + c)).satisfies( + (ex) -> assertThat(ex.getMessage()).contains("is not valid")); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java index 200db849f96..9b42a8bb4af 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/DurationStyleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.fail; /** * Tests for {@link DurationStyle}. @@ -243,13 +242,10 @@ public class DurationStyleTests { @Test public void parseSimpleWhenUnknownUnitShouldThrowException() { - try { - DurationStyle.SIMPLE.parse("10mb"); - fail("Did not throw"); - } - catch (IllegalArgumentException ex) { - assertThat(ex.getCause().getMessage()).isEqualTo("Unknown unit 'mb'"); - } + assertThatIllegalArgumentException() + .isThrownBy(() -> DurationStyle.SIMPLE.parse("10mb")) + .satisfies((ex) -> assertThat(ex.getCause().getMessage()) + .isEqualTo("Unknown unit 'mb'")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java index ea29372b990..888f1bd8009 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ import org.springframework.boot.web.server.PortInUseException; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration tests for {@link FailureAnalyzers}. @@ -42,15 +42,10 @@ public class FailureAnalyzersIntegrationTests { @Test public void analysisIsPerformed() { - try { - new SpringApplicationBuilder(TestConfiguration.class) - .web(WebApplicationType.NONE).run(); - fail("Application started successfully"); - } - catch (Exception ex) { - assertThat(this.outputCapture.toString()) - .contains("APPLICATION FAILED TO START"); - } + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> new SpringApplicationBuilder(TestConfiguration.class) + .web(WebApplicationType.NONE).run()); + assertThat(this.outputCapture.toString()).contains("APPLICATION FAILED TO START"); } @Configuration diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java index bcd19182478..f79aeca5d22 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/ValidationExceptionFailureAnalyzerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,14 +21,13 @@ import org.junit.runner.RunWith; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.diagnostics.FailureAnalysis; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.validation.annotation.Validated; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link ValidationExceptionFailureAnalyzer} @@ -41,15 +40,12 @@ public class ValidationExceptionFailureAnalyzerTests { @Test public void validatedPropertiesTest() { - try { - new AnnotationConfigApplicationContext(TestConfiguration.class).close(); - fail("Expected failure did not occur"); - } - catch (Exception ex) { - FailureAnalysis analysis = new ValidationExceptionFailureAnalyzer() - .analyze(ex); - assertThat(analysis).isNotNull(); - } + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> new AnnotationConfigApplicationContext( + TestConfiguration.class).close()) + .satisfies((ex) -> assertThat( + new ValidationExceptionFailureAnalyzer().analyze(ex)) + .isNotNull()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java index 24dd45ad065..0e94164bac4 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/SslServerCustomizerTests.java @@ -34,6 +34,7 @@ import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.WebServerException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link SslServerCustomizer}. @@ -85,13 +86,14 @@ public class SslServerCustomizerTests { throws Exception { Ssl ssl = new Ssl(); SslServerCustomizer customizer = new SslServerCustomizer(null, ssl, null, null); - try { - customizer.configureSsl(new SslContextFactory(), ssl, null); - } - catch (Exception ex) { - assertThat(ex).isInstanceOf(WebServerException.class); - assertThat(ex).hasMessageContaining("Could not load key store 'null'"); - } + assertThatExceptionOfType(Exception.class) + .isThrownBy( + () -> customizer.configureSsl(new SslContextFactory(), ssl, null)) + .satisfies((ex) -> { + assertThat(ex).isInstanceOf(WebServerException.class); + assertThat(ex) + .hasMessageContaining("Could not load key store 'null'"); + }); } private Server createCustomizedServer() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java index e785577fd53..ad439ac765e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/SslServerCustomizerTests.java @@ -23,8 +23,7 @@ import org.junit.Test; import org.springframework.boot.web.server.Ssl; import org.springframework.boot.web.server.WebServerException; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link SslServerCustomizer}. @@ -41,15 +40,10 @@ public class SslServerCustomizerTests { ssl.setKeyStore("src/test/resources/test.jks"); ssl.setKeyStoreProvider("com.example.KeyStoreProvider"); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); - try { - customizer.getKeyManagerFactory(ssl, null); - fail(); - } - catch (IllegalStateException ex) { - Throwable cause = ex.getCause(); - assertThat(cause).isInstanceOf(NoSuchProviderException.class); - assertThat(cause).hasMessageContaining("com.example.KeyStoreProvider"); - } + assertThatIllegalStateException() + .isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.KeyStoreProvider"); } @Test @@ -59,15 +53,10 @@ public class SslServerCustomizerTests { ssl.setTrustStore("src/test/resources/test.jks"); ssl.setTrustStoreProvider("com.example.TrustStoreProvider"); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); - try { - customizer.getTrustManagerFactory(ssl, null); - fail(); - } - catch (IllegalStateException ex) { - Throwable cause = ex.getCause(); - assertThat(cause).isInstanceOf(NoSuchProviderException.class); - assertThat(cause).hasMessageContaining("com.example.TrustStoreProvider"); - } + assertThatIllegalStateException() + .isThrownBy(() -> customizer.getTrustManagerFactory(ssl, null)) + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.TrustStoreProvider"); } @Test @@ -75,15 +64,10 @@ public class SslServerCustomizerTests { throws Exception { Ssl ssl = new Ssl(); SslServerCustomizer customizer = new SslServerCustomizer(ssl, null, null); - try { - customizer.getKeyManagerFactory(ssl, null); - fail(); - } - catch (IllegalStateException ex) { - Throwable cause = ex.getCause(); - assertThat(cause).isInstanceOf(WebServerException.class); - assertThat(cause).hasMessageContaining("Could not load key store 'null'"); - } + assertThatIllegalStateException() + .isThrownBy(() -> customizer.getKeyManagerFactory(ssl, null)) + .withCauseInstanceOf(WebServerException.class) + .withMessageContaining("Could not load key store 'null'"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java index db7d130c6ab..a8b5c6b775b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizerTests.java @@ -43,7 +43,7 @@ import org.springframework.core.io.Resource; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -193,15 +193,10 @@ public class SslConnectorCustomizerTests { @Test public void customizeWhenSslIsEnabledWithNoKeyStoreThrowsWebServerException() { - try { - new SslConnectorCustomizer(new Ssl(), null) - .customize(this.tomcat.getConnector()); - fail(); - } - catch (Exception ex) { - assertThat(ex).isInstanceOf(WebServerException.class); - assertThat(ex).hasMessageContaining("Could not load key store 'null'"); - } + assertThatExceptionOfType(WebServerException.class) + .isThrownBy(() -> new SslConnectorCustomizer(new Ssl(), null) + .customize(this.tomcat.getConnector())) + .withMessageContaining("Could not load key store 'null'"); } private KeyStore loadStore() throws KeyStoreException, IOException, diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java index 487d12f7c26..6665e9f9279 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatServletWebServerFactoryTests.java @@ -65,7 +65,6 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -277,19 +276,14 @@ public class TomcatServletWebServerFactoryTests } @Test - public void primaryConnectorPortClashThrowsIllegalStateException() - throws IOException { + public void primaryConnectorPortClashThrowsWebServerException() throws IOException { doWithBlockedPort((port) -> { TomcatServletWebServerFactory factory = getFactory(); factory.setPort(port); - try { + assertThatExceptionOfType(WebServerException.class).isThrownBy(() -> { this.webServer = factory.getWebServer(); this.webServer.start(); - fail(); - } - catch (WebServerException ex) { - // Ignore - } + }); }); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java index e385705eb8d..5597a4e29f7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/SslBuilderCustomizerTests.java @@ -28,7 +28,7 @@ import org.springframework.boot.web.server.WebServerException; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link SslBuilderCustomizer} @@ -60,15 +60,11 @@ public class SslBuilderCustomizerTests { ssl.setKeyStoreProvider("com.example.KeyStoreProvider"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); - try { - ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null); - fail(); - } - catch (IllegalStateException ex) { - Throwable cause = ex.getCause(); - assertThat(cause).isInstanceOf(NoSuchProviderException.class); - assertThat(cause).hasMessageContaining("com.example.KeyStoreProvider"); - } + assertThatIllegalStateException() + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, + "getKeyManagers", ssl, null)) + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.KeyStoreProvider"); } @Test @@ -79,15 +75,11 @@ public class SslBuilderCustomizerTests { ssl.setTrustStoreProvider("com.example.TrustStoreProvider"); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); - try { - ReflectionTestUtils.invokeMethod(customizer, "getTrustManagers", ssl, null); - fail(); - } - catch (IllegalStateException ex) { - Throwable cause = ex.getCause(); - assertThat(cause).isInstanceOf(NoSuchProviderException.class); - assertThat(cause).hasMessageContaining("com.example.TrustStoreProvider"); - } + assertThatIllegalStateException() + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, + "getTrustManagers", ssl, null)) + .withCauseInstanceOf(NoSuchProviderException.class) + .withMessageContaining("com.example.TrustStoreProvider"); } @Test @@ -96,15 +88,11 @@ public class SslBuilderCustomizerTests { Ssl ssl = new Ssl(); SslBuilderCustomizer customizer = new SslBuilderCustomizer(8080, InetAddress.getLocalHost(), ssl, null); - try { - ReflectionTestUtils.invokeMethod(customizer, "getKeyManagers", ssl, null); - fail(); - } - catch (IllegalStateException ex) { - Throwable cause = ex.getCause(); - assertThat(cause).isInstanceOf(WebServerException.class); - assertThat(cause).hasMessageContaining("Could not load key store 'null'"); - } + assertThatIllegalStateException() + .isThrownBy(() -> ReflectionTestUtils.invokeMethod(customizer, + "getKeyManagers", ssl, null)) + .withCauseInstanceOf(WebServerException.class) + .withMessageContaining("Could not load key store 'null'"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java index 93ce49fc3e7..cc392fbf4f2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/server/AbstractServletWebServerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -911,17 +911,13 @@ public abstract class AbstractServletWebServerFactoryTests { public void portClashOfPrimaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort((port) -> { - try { + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> { AbstractServletWebServerFactory factory = getFactory(); factory.setPort(port); AbstractServletWebServerFactoryTests.this.webServer = factory .getWebServer(); AbstractServletWebServerFactoryTests.this.webServer.start(); - fail(); - } - catch (RuntimeException ex) { - handleExceptionCausedByBlockedPort(ex, port); - } + }).satisfies((ex) -> handleExceptionCausedByBlockedPort(ex, port)); }); } @@ -929,17 +925,13 @@ public abstract class AbstractServletWebServerFactoryTests { public void portClashOfSecondaryConnectorResultsInPortInUseException() throws IOException { doWithBlockedPort((port) -> { - try { + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> { AbstractServletWebServerFactory factory = getFactory(); addConnector(port, factory); AbstractServletWebServerFactoryTests.this.webServer = factory .getWebServer(); AbstractServletWebServerFactoryTests.this.webServer.start(); - fail(); - } - catch (RuntimeException ex) { - handleExceptionCausedByBlockedPort(ex, port); - } + }).satisfies((ex) -> handleExceptionCausedByBlockedPort(ex, port)); }); }