diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/AuthorizationExceptionMatcher.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/AuthorizationExceptionMatcher.java deleted file mode 100644 index fce89656dd4..00000000000 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/AuthorizationExceptionMatcher.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2012-2017 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.boot.actuate.autoconfigure.cloudfoundry; - -import org.hamcrest.CustomMatcher; -import org.hamcrest.Matcher; - -import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException.Reason; - -/** - * Hamcrest matcher to check the {@link AuthorizationExceptionMatcher} {@link Reason}. - * - * @author Madhura Bhave - */ -public final class AuthorizationExceptionMatcher { - - private AuthorizationExceptionMatcher() { - } - - public static Matcher withReason(Reason reason) { - return new CustomMatcher( - "CloudFoundryAuthorizationException with " + reason + " reason") { - - @Override - public boolean matches(Object object) { - return ((object instanceof CloudFoundryAuthorizationException) - && ((CloudFoundryAuthorizationException) object) - .getReason() == reason); - } - - }; - } - -} diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java index d4670583bbb..4b40e218ede 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/TokenTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,14 +16,15 @@ package org.springframework.boot.actuate.autoconfigure.cloudfoundry; -import org.junit.Rule; +import java.util.function.Consumer; + import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException.Reason; import org.springframework.util.Base64Utils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link Token}. @@ -32,43 +33,40 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class TokenTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void invalidJwtShouldThrowException() { - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - new Token("invalid-token"); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> new Token("invalid-token")) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test public void invalidJwtClaimsShouldThrowException() { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "invalid-claims"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - new Token(Base64Utils.encodeToString(header.getBytes()) + "." - + Base64Utils.encodeToString(claims.getBytes())); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> new Token(Base64Utils.encodeToString(header.getBytes()) + + "." + Base64Utils.encodeToString(claims.getBytes()))) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test public void invalidJwtHeaderShouldThrowException() { String header = "invalid-header"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - new Token(Base64Utils.encodeToString(header.getBytes()) + "." - + Base64Utils.encodeToString(claims.getBytes())); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> new Token(Base64Utils.encodeToString(header.getBytes()) + + "." + Base64Utils.encodeToString(claims.getBytes()))) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test public void emptyJwtSignatureShouldThrowException() { String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwu" + "Y29tIiwiZXhwIjoxNDI2NDIwODAwLCJhd2Vzb21lIjp0cnVlfQ."; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - new Token(token); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> new Token(token)) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -93,9 +91,9 @@ public class TokenTests { String header = "{\"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; Token token = createToken(header, claims); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - token.getSignatureAlgorithm(); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> token.getSignatureAlgorithm()) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -103,9 +101,9 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - token.getIssuer(); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> token.getIssuer()) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -113,9 +111,9 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647}"; Token token = createToken(header, claims); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - token.getKeyId(); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> token.getKeyId()) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -123,9 +121,9 @@ public class TokenTests { String header = "{\"alg\": \"RS256\", \"kid\": \"key-id\", \"typ\": \"JWT\"}"; String claims = "{\"iss\": \"http://localhost:8080/uaa/oauth/token\"" + "}"; Token token = createToken(header, claims); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - token.getExpiry(); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> token.getExpiry()) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } private Token createToken(String header, String claims) { @@ -135,4 +133,9 @@ public class TokenTests { return token; } + private Consumer reasonRequirement( + Reason reason) { + return (ex) -> assertThat(ex.getReason()).isEqualTo(reason); + } + } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java index 33324e4656a..8b0da127461 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/reactive/ReactiveCloudFoundryActuatorAutoConfigurationTests.java @@ -24,9 +24,7 @@ import java.util.stream.Collectors; import javax.net.ssl.SSLException; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import reactor.netty.http.HttpResources; import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration; @@ -65,7 +63,7 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; /** @@ -75,9 +73,6 @@ import static org.mockito.Mockito.mock; */ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of( ReactiveSecurityAutoConfiguration.class, @@ -335,9 +330,11 @@ public class ReactiveCloudFoundryActuatorAutoConfigurationTests { .getField(interceptor, "cloudFoundrySecurityService"); WebClient webClient = (WebClient) ReflectionTestUtils .getField(interceptorSecurityService, "webClient"); - this.thrown.expectCause(instanceOf(SSLException.class)); - webClient.get().uri("https://self-signed.badssl.com/").exchange() - .block(); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy( + webClient.get().uri("https://self-signed.badssl.com/") + .exchange()::block) + .withCauseInstanceOf(SSLException.class); }); } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java index 6be4bec67b0..20fb5995115 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -17,14 +17,13 @@ package org.springframework.boot.actuate.autoconfigure.cloudfoundry.servlet; import java.util.Map; +import java.util.function.Consumer; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.autoconfigure.cloudfoundry.AccessLevel; -import org.springframework.boot.actuate.autoconfigure.cloudfoundry.AuthorizationExceptionMatcher; +import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException; import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException.Reason; import org.springframework.boot.test.web.client.MockServerRestTemplateCustomizer; import org.springframework.boot.web.client.RestTemplateBuilder; @@ -35,6 +34,7 @@ import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError; @@ -49,9 +49,6 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat */ public class CloudFoundrySecurityServiceTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private static final String CLOUD_CONTROLLER = "http://my-cloud-controller.com"; private static final String CLOUD_CONTROLLER_PERMISSIONS = CLOUD_CONTROLLER @@ -123,9 +120,9 @@ public class CloudFoundrySecurityServiceTests { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withUnauthorizedRequest()); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_TOKEN)); - this.securityService.getAccessLevel("my-access-token", "my-app-id"); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( + () -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .satisfies(reasonRequirement(Reason.INVALID_TOKEN)); } @Test @@ -133,9 +130,9 @@ public class CloudFoundrySecurityServiceTests { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withStatus(HttpStatus.FORBIDDEN)); - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.ACCESS_DENIED)); - this.securityService.getAccessLevel("my-access-token", "my-app-id"); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( + () -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .satisfies(reasonRequirement(Reason.ACCESS_DENIED)); } @Test @@ -143,9 +140,9 @@ public class CloudFoundrySecurityServiceTests { this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS)) .andExpect(header("Authorization", "bearer my-access-token")) .andRespond(withServerError()); - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); - this.securityService.getAccessLevel("my-access-token", "my-app-id"); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class).isThrownBy( + () -> this.securityService.getAccessLevel("my-access-token", "my-app-id")) + .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); } @Test @@ -188,9 +185,9 @@ public class CloudFoundrySecurityServiceTests { "{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON)); this.server.expect(requestTo(UAA_URL + "/token_keys")) .andRespond(withServerError()); - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); - this.securityService.fetchTokenKeys(); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.securityService.fetchTokenKeys()) + .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); } @Test @@ -209,9 +206,14 @@ public class CloudFoundrySecurityServiceTests { public void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() { this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")) .andRespond(withServerError()); - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.SERVICE_UNAVAILABLE)); - this.securityService.getUaaUrl(); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.securityService.getUaaUrl()) + .satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE)); + } + + private Consumer reasonRequirement( + Reason reason) { + return (ex) -> assertThat(ex.getReason()).isEqualTo(reason); } } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java index fa58e753d73..aaa3a7b8901 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/SkipSslVerificationHttpRequestFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,11 +18,8 @@ package org.springframework.boot.actuate.autoconfigure.cloudfoundry.servlet; import javax.net.ssl.SSLHandshakeException; -import org.hamcrest.Matcher; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.testsupport.web.servlet.ExampleServlet; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; @@ -35,16 +32,13 @@ import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Test for {@link SkipSslVerificationHttpRequestFactory}. */ public class SkipSslVerificationHttpRequestFactoryTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private WebServer webServer; @After @@ -59,17 +53,13 @@ public class SkipSslVerificationHttpRequestFactoryTests { String httpsUrl = getHttpsUrl(); SkipSslVerificationHttpRequestFactory requestFactory = new SkipSslVerificationHttpRequestFactory(); RestTemplate restTemplate = new RestTemplate(requestFactory); + RestTemplate otherRestTemplate = new RestTemplate(); ResponseEntity responseEntity = restTemplate.getForEntity(httpsUrl, String.class); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); - this.thrown.expect(ResourceAccessException.class); - this.thrown.expectCause(isSSLHandshakeException()); - RestTemplate otherRestTemplate = new RestTemplate(); - otherRestTemplate.getForEntity(httpsUrl, String.class); - } - - private Matcher isSSLHandshakeException() { - return instanceOf(SSLHandshakeException.class); + assertThatExceptionOfType(ResourceAccessException.class) + .isThrownBy(() -> otherRestTemplate.getForEntity(httpsUrl, String.class)) + .withCauseInstanceOf(SSLHandshakeException.class); } private String getHttpsUrl() { diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java index fad41d659b1..7298b27f10d 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/TokenValidatorTests.java @@ -27,22 +27,23 @@ import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Collections; import java.util.Map; +import java.util.function.Consumer; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.springframework.boot.actuate.autoconfigure.cloudfoundry.AuthorizationExceptionMatcher; +import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException; import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException.Reason; import org.springframework.boot.actuate.autoconfigure.cloudfoundry.Token; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.Base64Utils; import org.springframework.util.StreamUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @@ -55,9 +56,6 @@ public class TokenValidatorTests { private static final byte[] DOT = ".".getBytes(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private CloudFoundrySecurityService securityService; @@ -100,10 +98,10 @@ public class TokenValidatorTests { given(this.securityService.fetchTokenKeys()).willReturn(INVALID_KEYS); String header = "{\"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{\"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_KEY_ID)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.tokenValidator.validate( + new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_KEY_ID)); } @Test @@ -148,10 +146,10 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\",\"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.INVALID_SIGNATURE)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.tokenValidator.validate( + new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_SIGNATURE)); } @Test @@ -160,10 +158,10 @@ public class TokenValidatorTests { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); String header = "{ \"alg\": \"HS256\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"actuator.read\"]}"; - this.thrown.expect(AuthorizationExceptionMatcher - .withReason(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.tokenValidator.validate( + new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)); } @Test @@ -172,10 +170,10 @@ public class TokenValidatorTests { given(this.securityService.fetchTokenKeys()).willReturn(VALID_KEYS); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"jti\": \"0236399c350c47f3ae77e67a75e75e7d\", \"exp\": 1477509977, \"scope\": [\"actuator.read\"]}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.TOKEN_EXPIRED)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.tokenValidator.validate( + new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.TOKEN_EXPIRED)); } @Test @@ -184,10 +182,10 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://other-uaa.com"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\", \"scope\": [\"actuator.read\"]}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\"}"; - this.thrown - .expect(AuthorizationExceptionMatcher.withReason(Reason.INVALID_ISSUER)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.tokenValidator.validate( + new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_ISSUER)); } @Test @@ -197,10 +195,10 @@ public class TokenValidatorTests { given(this.securityService.getUaaUrl()).willReturn("http://localhost:8080/uaa"); String header = "{ \"alg\": \"RS256\", \"kid\": \"valid-key\", \"typ\": \"JWT\"}"; String claims = "{ \"exp\": 2147483647, \"iss\": \"http://localhost:8080/uaa/oauth/token\", \"scope\": [\"foo.bar\"]}"; - this.thrown.expect( - AuthorizationExceptionMatcher.withReason(Reason.INVALID_AUDIENCE)); - this.tokenValidator.validate( - new Token(getSignedToken(header.getBytes(), claims.getBytes()))); + assertThatExceptionOfType(CloudFoundryAuthorizationException.class) + .isThrownBy(() -> this.tokenValidator.validate( + new Token(getSignedToken(header.getBytes(), claims.getBytes())))) + .satisfies(reasonRequirement(Reason.INVALID_AUDIENCE)); } private String getSignedToken(byte[] header, byte[] claims) throws Exception { @@ -265,4 +263,9 @@ public class TokenValidatorTests { return result.toByteArray(); } + private Consumer reasonRequirement( + Reason reason) { + return (ex) -> assertThat(ex.getReason()).isEqualTo(reason); + } + } diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java index 0b6b62555ba..9d06de887b7 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/ExposeExcludePropertyEndpointFilterTests.java @@ -17,9 +17,7 @@ package org.springframework.boot.actuate.autoconfigure.endpoint; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.MockitoAnnotations; import org.springframework.boot.actuate.endpoint.EndpointFilter; @@ -28,6 +26,7 @@ import org.springframework.boot.actuate.endpoint.web.ExposableWebEndpoint; import org.springframework.mock.env.MockEnvironment; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -38,9 +37,6 @@ import static org.mockito.Mockito.mock; */ public class ExposeExcludePropertyEndpointFilterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ExposeExcludePropertyEndpointFilter filter; @Before @@ -50,32 +46,34 @@ public class ExposeExcludePropertyEndpointFilterTests { @Test public void createWhenEndpointTypeIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("EndpointType must not be null"); - new ExposeExcludePropertyEndpointFilter<>(null, new MockEnvironment(), "foo"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>(null, + new MockEnvironment(), "foo")) + .withMessageContaining("EndpointType must not be null"); } @Test public void createWhenEnvironmentIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Environment must not be null"); - new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, null, "foo"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>( + ExposableEndpoint.class, null, "foo")) + .withMessageContaining("Environment must not be null"); } @Test public void createWhenPrefixIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Prefix must not be empty"); - new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, - new MockEnvironment(), null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>( + ExposableEndpoint.class, new MockEnvironment(), null)) + .withMessageContaining("Prefix must not be empty"); } @Test public void createWhenPrefixIsEmptyShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Prefix must not be empty"); - new ExposeExcludePropertyEndpointFilter<>(ExposableEndpoint.class, - new MockEnvironment(), ""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ExposeExcludePropertyEndpointFilter<>( + ExposableEndpoint.class, new MockEnvironment(), "")) + .withMessageContaining("Prefix must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java index f7413707d24..98e22db6754 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/jmx/DefaultEndpointObjectNameFactoryTests.java @@ -22,15 +22,14 @@ import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.jmx.ExposableJmxEndpoint; import org.springframework.mock.env.MockEnvironment; import org.springframework.util.ObjectUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -41,9 +40,6 @@ import static org.mockito.Mockito.mock; */ public class DefaultEndpointObjectNameFactoryTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final MockEnvironment environment = new MockEnvironment(); private final JmxEndpointProperties properties = new JmxEndpointProperties( @@ -101,10 +97,10 @@ public class DefaultEndpointObjectNameFactoryTests { public void generateObjectNameWithUniqueNamesDeprecatedPropertyMismatchMainProperty() { this.environment.setProperty("spring.jmx.unique-names", "false"); this.properties.setUniqueNames(true); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("spring.jmx.unique-names"); - this.thrown.expectMessage("management.endpoints.jmx.unique-names"); - generateObjectName(endpoint("test")); + assertThatIllegalArgumentException() + .isThrownBy(() -> generateObjectName(endpoint("test"))) + .withMessageContaining("spring.jmx.unique-names") + .withMessageContaining("management.endpoints.jmx.unique-names"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java index 93bfcfe62b8..99708be1996 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointPropertiesTests.java @@ -16,11 +16,10 @@ package org.springframework.boot.actuate.autoconfigure.endpoint.web; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link WebEndpointProperties}. @@ -29,9 +28,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class WebEndpointPropertiesTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void defaultBasePathShouldBeApplication() { WebEndpointProperties properties = new WebEndpointProperties(); @@ -50,9 +46,9 @@ public class WebEndpointPropertiesTests { @Test public void basePathMustStartWithSlash() { WebEndpointProperties properties = new WebEndpointProperties(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Base path must start with '/' or be empty"); - properties.setBasePath("admin"); + assertThatIllegalArgumentException() + .isThrownBy(() -> properties.setBasePath("admin")) + .withMessageContaining("Base path must start with '/' or be empty"); } @Test diff --git a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java index 0b8459a8334..d13ef843daf 100644 --- a/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java +++ b/spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/PropertiesMeterFilterTests.java @@ -25,9 +25,7 @@ import io.micrometer.core.instrument.config.MeterFilterReply; import io.micrometer.core.instrument.distribution.DistributionStatisticConfig; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -37,6 +35,7 @@ import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.mock.env.MockEnvironment; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link PropertiesMeterFilter}. @@ -46,9 +45,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class PropertiesMeterFilterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private DistributionStatisticConfig config; @@ -59,9 +55,9 @@ public class PropertiesMeterFilterTests { @Test public void createWhenPropertiesIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Properties must not be null"); - new PropertiesMeterFilter(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PropertiesMeterFilter(null)) + .withMessageContaining("Properties must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java index 8817f6282e5..e0990f81080 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/amqp/RabbitHealthIndicatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +21,7 @@ import java.util.Collections; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -33,6 +31,7 @@ import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.Status; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -44,9 +43,6 @@ import static org.mockito.Mockito.mock; */ public class RabbitHealthIndicatorTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private RabbitTemplate rabbitTemplate; @@ -64,9 +60,9 @@ public class RabbitHealthIndicatorTests { @Test public void createWhenRabbitTemplateIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RabbitTemplate must not be null"); - new RabbitHealthIndicator(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new RabbitHealthIndicator(null)) + .withMessageContaining("RabbitTemplate must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java index 5bcf5023aff..7c005089c7b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/AuditEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -19,13 +19,12 @@ package org.springframework.boot.actuate.audit; import java.util.Collections; import org.json.JSONObject; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link AuditEvent}. @@ -35,9 +34,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class AuditEventTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void nowEvent() { AuditEvent event = new AuditEvent("phil", "UNKNOWN", @@ -64,17 +60,18 @@ public class AuditEventTests { @Test public void nullTimestamp() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Timestamp must not be null"); - new AuditEvent(null, "phil", "UNKNOWN", - Collections.singletonMap("a", (Object) "b")); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AuditEvent(null, "phil", "UNKNOWN", + Collections.singletonMap("a", (Object) "b"))) + .withMessageContaining("Timestamp must not be null"); } @Test public void nullType() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must not be null"); - new AuditEvent("phil", null, Collections.singletonMap("a", (Object) "b")); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AuditEvent("phil", null, + Collections.singletonMap("a", (Object) "b"))) + .withMessageContaining("Type must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java index c9262135849..c8a4b87c676 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/audit/InMemoryAuditEventRepositoryTests.java @@ -22,11 +22,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link InMemoryAuditEventRepository}. @@ -37,9 +36,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class InMemoryAuditEventRepositoryTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void lessThanCapacity() { InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(); @@ -65,10 +61,9 @@ public class InMemoryAuditEventRepositoryTests { @Test public void addNullAuditEvent() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("AuditEvent must not be null"); InMemoryAuditEventRepository repository = new InMemoryAuditEventRepository(); - repository.add(null); + assertThatIllegalArgumentException().isThrownBy(() -> repository.add(null)) + .withMessageContaining("AuditEvent must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java index 5777c9d7380..ad3413e6311 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/cache/CachesEndpointTests.java @@ -22,9 +22,7 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.cache.CachesEndpoint.CacheEntry; import org.springframework.boot.actuate.cache.CachesEndpoint.CacheManagerDescriptor; @@ -34,6 +32,7 @@ import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.cache.support.SimpleCacheManager; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -46,9 +45,6 @@ import static org.mockito.Mockito.verify; */ public class CachesEndpointTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void allCachesWithSingleCacheManager() { CachesEndpoint endpoint = new CachesEndpoint(Collections.singletonMap("test", @@ -94,11 +90,10 @@ public class CachesEndpointTests { cacheManagers.put("test", new ConcurrentMapCacheManager("b", "dupe-cache")); cacheManagers.put("another", new ConcurrentMapCacheManager("c", "dupe-cache")); CachesEndpoint endpoint = new CachesEndpoint(cacheManagers); - this.thrown.expect(NonUniqueCacheException.class); - this.thrown.expectMessage("dupe-cache"); - this.thrown.expectMessage("test"); - this.thrown.expectMessage("another"); - endpoint.cache("dupe-cache", null); + assertThatExceptionOfType(NonUniqueCacheException.class) + .isThrownBy(() -> endpoint.cache("dupe-cache", null)) + .withMessageContaining("dupe-cache").withMessageContaining("test") + .withMessageContaining("another"); } @Test @@ -159,11 +154,10 @@ public class CachesEndpointTests { cacheManagers.put("test", cacheManager(mockCache("dupe-cache"), mockCache("b"))); cacheManagers.put("another", cacheManager(mockCache("dupe-cache"))); CachesEndpoint endpoint = new CachesEndpoint(cacheManagers); - - this.thrown.expectMessage("dupe-cache"); - this.thrown.expectMessage("test"); - this.thrown.expectMessage("another"); - endpoint.clearCache("dupe-cache", null); + assertThatExceptionOfType(NonUniqueCacheException.class) + .isThrownBy(() -> endpoint.clearCache("dupe-cache", null)) + .withMessageContaining("dupe-cache").withMessageContaining("test") + .withMessageContaining("another"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java index bb28a9a59e7..5d6a6bffa0b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscoveredOperationMethodTests.java @@ -18,15 +18,14 @@ package org.springframework.boot.actuate.endpoint.annotation; import java.lang.reflect.Method; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.OperationType; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DiscoveredOperationMethod}. @@ -35,15 +34,12 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class DiscoveredOperationMethodTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenAnnotationAttributesIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("AnnotationAttributes must not be null"); Method method = ReflectionUtils.findMethod(getClass(), "example"); - new DiscoveredOperationMethod(method, OperationType.READ, null); + assertThatIllegalArgumentException().isThrownBy( + () -> new DiscoveredOperationMethod(method, OperationType.READ, null)) + .withMessageContaining("AnnotationAttributes must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java index eb2ce70bee2..04d6fae6dda 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/DiscovererEndpointFilterTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.actuate.endpoint.annotation; import java.util.Collection; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.EndpointFilter; import org.springframework.boot.actuate.endpoint.ExposableEndpoint; @@ -30,6 +28,7 @@ import org.springframework.boot.actuate.endpoint.invoke.ParameterValueMapper; import org.springframework.context.ApplicationContext; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -40,14 +39,11 @@ import static org.mockito.Mockito.mock; */ public class DiscovererEndpointFilterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenDiscovererIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Discoverer must not be null"); - new TestDiscovererEndpointFilter(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new TestDiscovererEndpointFilter(null)) + .withMessageContaining("Discoverer must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java index b38c076ef63..bea769cdd06 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java @@ -32,9 +32,7 @@ import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.EndpointFilter; import org.springframework.boot.actuate.endpoint.ExposableEndpoint; @@ -54,6 +52,8 @@ import org.springframework.core.annotation.AliasFor; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.Mockito.mock; /** @@ -65,39 +65,39 @@ import static org.mockito.Mockito.mock; */ public class EndpointDiscovererTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenApplicationContextIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ApplicationContext must not be null"); - new TestEndpointDiscoverer(null, mock(ParameterValueMapper.class), - Collections.emptyList(), Collections.emptyList()); + assertThatIllegalArgumentException() + .isThrownBy(() -> new TestEndpointDiscoverer(null, + mock(ParameterValueMapper.class), Collections.emptyList(), + Collections.emptyList())) + .withMessageContaining("ApplicationContext must not be null"); } @Test public void createWhenParameterValueMapperIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ParameterValueMapper must not be null"); - new TestEndpointDiscoverer(mock(ApplicationContext.class), null, - Collections.emptyList(), Collections.emptyList()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new TestEndpointDiscoverer(mock(ApplicationContext.class), + null, Collections.emptyList(), Collections.emptyList())) + .withMessageContaining("ParameterValueMapper must not be null"); } @Test public void createWhenInvokerAdvisorsIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("InvokerAdvisors must not be null"); - new TestEndpointDiscoverer(mock(ApplicationContext.class), - mock(ParameterValueMapper.class), null, Collections.emptyList()); + assertThatIllegalArgumentException() + .isThrownBy(() -> new TestEndpointDiscoverer( + mock(ApplicationContext.class), mock(ParameterValueMapper.class), + null, Collections.emptyList())) + .withMessageContaining("InvokerAdvisors must not be null"); } @Test public void createWhenFiltersIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Filters must not be null"); - new TestEndpointDiscoverer(mock(ApplicationContext.class), - mock(ParameterValueMapper.class), Collections.emptyList(), null); + assertThatIllegalArgumentException().isThrownBy( + () -> new TestEndpointDiscoverer(mock(ApplicationContext.class), + mock(ParameterValueMapper.class), Collections.emptyList(), null)) + .withMessageContaining("Filters must not be null"); } @Test @@ -139,11 +139,11 @@ public class EndpointDiscovererTests { @Test public void getEndpointsWhenTwoEndpointsHaveTheSameIdShouldThrowException() { - load(ClashingEndpointConfiguration.class, (context) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Found two endpoints with the id 'test': "); - new TestEndpointDiscoverer(context).getEndpoints(); - }); + load(ClashingEndpointConfiguration.class, + (context) -> assertThatIllegalStateException() + .isThrownBy(new TestEndpointDiscoverer(context)::getEndpoints) + .withMessageContaining( + "Found two endpoints with the id 'test': ")); } @Test 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 e86da8a9574..11697546825 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 @@ -18,9 +18,7 @@ package org.springframework.boot.actuate.endpoint.invoke.convert; import java.time.OffsetDateTime; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.invoke.OperationParameter; import org.springframework.boot.actuate.endpoint.invoke.ParameterMappingException; @@ -29,6 +27,7 @@ import org.springframework.core.convert.support.DefaultConversionService; 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; @@ -43,9 +42,6 @@ import static org.mockito.Mockito.verify; */ public class ConversionServiceParameterValueMapperTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void mapParameterShouldDelegateToConversionService() { DefaultFormattingConversionService conversionService = spy( @@ -90,9 +86,9 @@ public class ConversionServiceParameterValueMapperTests { ConversionService conversionService = new DefaultConversionService(); ConversionServiceParameterValueMapper mapper = new ConversionServiceParameterValueMapper( conversionService); - this.thrown.expect(ParameterMappingException.class); - mapper.mapParameterValue(new TestOperationParameter(OffsetDateTime.class), - "2011-12-03T10:15:30+01:00"); + assertThatExceptionOfType(ParameterMappingException.class).isThrownBy(() -> mapper + .mapParameterValue(new TestOperationParameter(OffsetDateTime.class), + "2011-12-03T10:15:30+01:00")); } private static class TestOperationParameter implements OperationParameter { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java index d18d2733811..0039cf74127 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodParametersTests.java @@ -25,9 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.invoke.OperationParameter; import org.springframework.core.DefaultParameterNameDiscoverer; @@ -35,6 +33,8 @@ import org.springframework.core.ParameterNameDiscoverer; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.Mockito.mock; /** @@ -44,9 +44,6 @@ import static org.mockito.Mockito.mock; */ public class OperationMethodParametersTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private Method exampleMethod = ReflectionUtils.findMethod(getClass(), "example", String.class); @@ -55,24 +52,25 @@ public class OperationMethodParametersTests { @Test public void createWhenMethodIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Method must not be null"); - new OperationMethodParameters(null, mock(ParameterNameDiscoverer.class)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OperationMethodParameters(null, + mock(ParameterNameDiscoverer.class))) + .withMessageContaining("Method must not be null"); } @Test public void createWhenParameterNameDiscovererIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ParameterNameDiscoverer must not be null"); - new OperationMethodParameters(this.exampleMethod, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OperationMethodParameters(this.exampleMethod, null)) + .withMessageContaining("ParameterNameDiscoverer must not be null"); } @Test public void createWhenParameterNameDiscovererReturnsNullShouldThrowException() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Failed to extract parameter names"); - new OperationMethodParameters(this.exampleMethod, - mock(ParameterNameDiscoverer.class)); + assertThatIllegalStateException() + .isThrownBy(() -> new OperationMethodParameters(this.exampleMethod, + mock(ParameterNameDiscoverer.class))) + .withMessageContaining("Failed to extract parameter names"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java index 195ee875f6e..4d2cb4ee9a6 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/OperationMethodTests.java @@ -18,15 +18,14 @@ package org.springframework.boot.actuate.endpoint.invoke.reflect; import java.lang.reflect.Method; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.OperationType; import org.springframework.boot.actuate.endpoint.invoke.OperationParameters; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OperationMethod}. @@ -35,24 +34,21 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class OperationMethodTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private Method exampleMethod = ReflectionUtils.findMethod(getClass(), "example", String.class); @Test public void createWhenMethodIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Method must not be null"); - new OperationMethod(null, OperationType.READ); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OperationMethod(null, OperationType.READ)) + .withMessageContaining("Method must not be null"); } @Test public void createWhenOperationTypeIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("OperationType must not be null"); - new OperationMethod(this.exampleMethod, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OperationMethod(this.exampleMethod, null)) + .withMessageContaining("OperationType must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java index 4c6aa132a28..6c0b604d67a 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoke/reflect/ReflectiveOperationInvokerTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.actuate.endpoint.invoke.reflect; import java.util.Collections; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.InvocationContext; import org.springframework.boot.actuate.endpoint.OperationType; @@ -32,6 +30,8 @@ import org.springframework.lang.Nullable; import org.springframework.util.ReflectionUtils; 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.mockito.Mockito.mock; /** @@ -41,9 +41,6 @@ import static org.mockito.Mockito.mock; */ public class ReflectiveOperationInvokerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private Example target; private OperationMethod operationMethod; @@ -62,24 +59,26 @@ public class ReflectiveOperationInvokerTests { @Test public void createWhenTargetIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Target must not be null"); - new ReflectiveOperationInvoker(null, this.operationMethod, - this.parameterValueMapper); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ReflectiveOperationInvoker(null, + this.operationMethod, this.parameterValueMapper)) + .withMessageContaining("Target must not be null"); } @Test public void createWhenOperationMethodIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("OperationMethod must not be null"); - new ReflectiveOperationInvoker(this.target, null, this.parameterValueMapper); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, null, + this.parameterValueMapper)) + .withMessageContaining("OperationMethod must not be null"); } @Test public void createWhenParameterValueMapperIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ParameterValueMapper must not be null"); - new ReflectiveOperationInvoker(this.target, this.operationMethod, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ReflectiveOperationInvoker(this.target, + this.operationMethod, null)) + .withMessageContaining("ParameterValueMapper must not be null"); } @Test @@ -95,9 +94,9 @@ public class ReflectiveOperationInvokerTests { public void invokeWhenMissingNonNullableArgumentShouldThrowException() { ReflectiveOperationInvoker invoker = new ReflectiveOperationInvoker(this.target, this.operationMethod, this.parameterValueMapper); - this.thrown.expect(MissingParametersException.class); - invoker.invoke(new InvocationContext(mock(SecurityContext.class), - Collections.singletonMap("name", null))); + assertThatExceptionOfType(MissingParametersException.class).isThrownBy( + () -> invoker.invoke(new InvocationContext(mock(SecurityContext.class), + Collections.singletonMap("name", null)))); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java index c83ffa4b950..d18097bde6f 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/invoker/cache/CachingOperationInvokerTests.java @@ -21,15 +21,14 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.InvocationContext; import org.springframework.boot.actuate.endpoint.SecurityContext; import org.springframework.boot.actuate.endpoint.invoke.OperationInvoker; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -43,14 +42,11 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; */ public class CachingOperationInvokerTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void createInstanceWithTtlSetToZero() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TimeToLive"); - new CachingOperationInvoker(mock(OperationInvoker.class), 0); + assertThatIllegalArgumentException().isThrownBy( + () -> new CachingOperationInvoker(mock(OperationInvoker.class), 0)) + .withMessageContaining("TimeToLive"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java index 6813552892a..f666a78a405 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanTests.java @@ -27,9 +27,7 @@ import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.ReflectionException; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import reactor.core.publisher.Mono; import org.springframework.beans.FatalBeanException; @@ -38,7 +36,8 @@ import org.springframework.boot.actuate.endpoint.InvocationContext; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -55,9 +54,6 @@ public class EndpointMBeanTests { private static final String[] NO_SIGNATURE = {}; - @Rule - public ExpectedException thrown = ExpectedException.none(); - private TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint( new TestJmxOperation()); @@ -65,16 +61,17 @@ public class EndpointMBeanTests { @Test public void createWhenResponseMapperIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ResponseMapper must not be null"); - new EndpointMBean(null, null, mock(ExposableJmxEndpoint.class)); + assertThatIllegalArgumentException().isThrownBy( + () -> new EndpointMBean(null, null, mock(ExposableJmxEndpoint.class))) + .withMessageContaining("ResponseMapper must not be null"); } @Test public void createWhenEndpointIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Endpoint must not be null"); - new EndpointMBean(mock(JmxOperationResponseMapper.class), null, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new EndpointMBean( + mock(JmxOperationResponseMapper.class), null, null)) + .withMessageContaining("Endpoint must not be null"); } @Test @@ -100,10 +97,11 @@ public class EndpointMBeanTests { throw new FatalBeanException("test failure"); })); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); - this.thrown.expect(MBeanException.class); - this.thrown.expectCause(instanceOf(IllegalStateException.class)); - this.thrown.expectMessage("test failure"); - bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE); + assertThatExceptionOfType(MBeanException.class) + .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("test failure"); + } @Test @@ -114,20 +112,21 @@ public class EndpointMBeanTests { throw new UnsupportedOperationException("test failure"); })); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); - this.thrown.expect(MBeanException.class); - this.thrown.expectCause(instanceOf(UnsupportedOperationException.class)); - this.thrown.expectMessage("test failure"); - bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE); + assertThatExceptionOfType(MBeanException.class) + .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) + .withCauseInstanceOf(UnsupportedOperationException.class) + .withMessageContaining("test failure"); } @Test public void invokeWhenActionNameIsNotAnOperationShouldThrowException() throws MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); - this.thrown.expect(ReflectionException.class); - this.thrown.expectCause(instanceOf(IllegalArgumentException.class)); - this.thrown.expectMessage("no operation named missingOperation"); - bean.invoke("missingOperation", NO_PARAMS, NO_SIGNATURE); + assertThatExceptionOfType(ReflectionException.class) + .isThrownBy( + () -> bean.invoke("missingOperation", NO_PARAMS, NO_SIGNATURE)) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("no operation named missingOperation"); } @Test @@ -159,10 +158,10 @@ public class EndpointMBeanTests { }; TestExposableJmxEndpoint endpoint = new TestExposableJmxEndpoint(operation); EndpointMBean bean = new EndpointMBean(this.responseMapper, null, endpoint); - this.thrown.expect(ReflectionException.class); - this.thrown.expectCause(instanceOf(IllegalArgumentException.class)); - this.thrown.expectMessage("test failure"); - bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE); + assertThatExceptionOfType(ReflectionException.class) + .isThrownBy(() -> bean.invoke("testOperation", NO_PARAMS, NO_SIGNATURE)) + .withRootCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("test failure"); } @Test @@ -189,18 +188,18 @@ public class EndpointMBeanTests { public void getAttributeShouldThrowException() throws AttributeNotFoundException, MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); - this.thrown.expect(AttributeNotFoundException.class); - this.thrown.expectMessage("EndpointMBeans do not support attributes"); - bean.getAttribute("test"); + assertThatExceptionOfType(AttributeNotFoundException.class) + .isThrownBy(() -> bean.getAttribute("test")) + .withMessageContaining("EndpointMBeans do not support attributes"); } @Test public void setAttributeShouldThrowException() throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { EndpointMBean bean = createEndpointMBean(); - this.thrown.expect(AttributeNotFoundException.class); - this.thrown.expectMessage("EndpointMBeans do not support attributes"); - bean.setAttribute(new Attribute("test", "test")); + assertThatExceptionOfType(AttributeNotFoundException.class) + .isThrownBy(() -> bean.setAttribute(new Attribute("test", "test"))) + .withMessageContaining("EndpointMBeans do not support attributes"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java index b196e963639..ee07d56c486 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/JmxEndpointExporterTests.java @@ -26,9 +26,7 @@ import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -38,6 +36,9 @@ import org.springframework.jmx.JmxException; import org.springframework.jmx.export.MBeanExportException; 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.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; @@ -52,9 +53,6 @@ import static org.mockito.Mockito.verify; */ public class JmxEndpointExporterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private MBeanServer mBeanServer; @@ -82,34 +80,34 @@ public class JmxEndpointExporterTests { @Test public void createWhenMBeanServerIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("MBeanServer must not be null"); - new JmxEndpointExporter(null, this.objectNameFactory, this.responseMapper, - this.endpoints); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JmxEndpointExporter(null, this.objectNameFactory, + this.responseMapper, this.endpoints)) + .withMessageContaining("MBeanServer must not be null"); } @Test public void createWhenObjectNameFactoryIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ObjectNameFactory must not be null"); - new JmxEndpointExporter(this.mBeanServer, null, this.responseMapper, - this.endpoints); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, null, + this.responseMapper, this.endpoints)) + .withMessageContaining("ObjectNameFactory must not be null"); } @Test public void createWhenResponseMapperIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ResponseMapper must not be null"); - new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, null, - this.endpoints); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, + this.objectNameFactory, null, this.endpoints)) + .withMessageContaining("ResponseMapper must not be null"); } @Test public void createWhenEndpointsIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Endpoints must not be null"); - new JmxEndpointExporter(this.mBeanServer, this.objectNameFactory, - this.responseMapper, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JmxEndpointExporter(this.mBeanServer, + this.objectNameFactory, this.responseMapper, null)) + .withMessageContaining("Endpoints must not be null"); } @Test @@ -135,9 +133,8 @@ public class JmxEndpointExporterTests { given(this.objectNameFactory.getObjectName(any(ExposableJmxEndpoint.class))) .willThrow(MalformedObjectNameException.class); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Invalid ObjectName for endpoint 'test'"); - this.exporter.afterPropertiesSet(); + assertThatIllegalStateException().isThrownBy(this.exporter::afterPropertiesSet) + .withMessageContaining("Invalid ObjectName for endpoint 'test'"); } @Test @@ -145,9 +142,9 @@ public class JmxEndpointExporterTests { given(this.mBeanServer.registerMBean(any(), any(ObjectName.class))) .willThrow(new MBeanRegistrationException(new RuntimeException())); this.endpoints.add(new TestExposableJmxEndpoint(new TestJmxOperation())); - this.thrown.expect(MBeanExportException.class); - this.thrown.expectMessage("Failed to register MBean for endpoint 'test"); - this.exporter.afterPropertiesSet(); + assertThatExceptionOfType(MBeanExportException.class) + .isThrownBy(this.exporter::afterPropertiesSet) + .withMessageContaining("Failed to register MBean for endpoint 'test"); } @Test @@ -176,9 +173,9 @@ public class JmxEndpointExporterTests { this.exporter.afterPropertiesSet(); willThrow(new MBeanRegistrationException(new RuntimeException())) .given(this.mBeanServer).unregisterMBean(any(ObjectName.class)); - this.thrown.expect(JmxException.class); - this.thrown.expectMessage("Failed to unregister MBean with ObjectName 'boot"); - this.exporter.destroy(); + assertThatExceptionOfType(JmxException.class) + .isThrownBy(() -> this.exporter.destroy()).withMessageContaining( + "Failed to unregister MBean with ObjectName 'boot"); } /** diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java index 2dec1755529..05582e31b01 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/annotation/JmxEndpointDiscovererTests.java @@ -24,9 +24,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.annotation.DeleteOperation; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; @@ -49,6 +47,7 @@ import org.springframework.jmx.export.annotation.ManagedOperationParameters; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link JmxEndpointDiscoverer}. @@ -58,9 +57,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class JmxEndpointDiscovererTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { load(EmptyConfiguration.class, @@ -113,13 +109,10 @@ public class JmxEndpointDiscovererTests { @Test public void getEndpointsWhenJmxExtensionIsMissingEndpointShouldThrowException() { - load(TestJmxEndpointExtension.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': " - + "no endpoint found with id 'test'"); - discoverer.getEndpoints(); - }); + load(TestJmxEndpointExtension.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Invalid extension 'jmxEndpointDiscovererTests.TestJmxEndpointExtension': no endpoint found with id 'test'")); } @Test @@ -188,51 +181,42 @@ public class JmxEndpointDiscovererTests { @Test public void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { - load(ClashingJmxEndpointConfiguration.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Found multiple extensions for the endpoint bean " - + "testEndpoint (testExtensionOne, testExtensionTwo)"); - discoverer.getEndpoints(); - }); + load(ClashingJmxEndpointConfiguration.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Found multiple extensions for the endpoint bean testEndpoint (testExtensionOne, testExtensionTwo)")); } @Test public void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { - load(ClashingStandardEndpointConfiguration.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Found two endpoints with the id 'test': "); - discoverer.getEndpoints(); - }); + load(ClashingStandardEndpointConfiguration.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Found two endpoints with the id 'test': ")); } @Test public void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { - load(ClashingOperationsEndpoint.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to map duplicate endpoint operations: " - + "[MBean call 'getAll'] to jmxEndpointDiscovererTests.ClashingOperationsEndpoint"); - discoverer.getEndpoints(); - }); + load(ClashingOperationsEndpoint.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to jmxEndpointDiscovererTests.ClashingOperationsEndpoint")); } @Test public void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { - load(AdditionalClashingOperationsConfiguration.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to map duplicate endpoint operations: " - + "[MBean call 'getAll'] to testEndpoint (clashingOperationsJmxEndpointExtension)"); - discoverer.getEndpoints(); - }); + load(AdditionalClashingOperationsConfiguration.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Unable to map duplicate endpoint operations: [MBean call 'getAll'] to testEndpoint (clashingOperationsJmxEndpointExtension)")); } @Test public void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { - load(InvalidJmxExtensionConfiguration.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Endpoint bean 'nonJmxEndpoint' cannot support the " - + "extension bean 'nonJmxJmxEndpointExtension'"); - discoverer.getEndpoints(); - }); + load(InvalidJmxExtensionConfiguration.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Endpoint bean 'nonJmxEndpoint' cannot support the extension bean 'nonJmxJmxEndpointExtension'")); } private Object getInvoker(JmxOperation operation) { diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java index b36640143b8..00ce0cd7310 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointMediaTypesTests.java @@ -20,11 +20,10 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link EndpointMediaTypes}. @@ -33,21 +32,18 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class EndpointMediaTypesTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenProducedIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Produced must not be null"); - new EndpointMediaTypes(null, Collections.emptyList()); + assertThatIllegalArgumentException() + .isThrownBy(() -> new EndpointMediaTypes(null, Collections.emptyList())) + .withMessageContaining("Produced must not be null"); } @Test public void createWhenConsumedIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Consumed must not be null"); - new EndpointMediaTypes(Collections.emptyList(), null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new EndpointMediaTypes(Collections.emptyList(), null)) + .withMessageContaining("Consumed must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java index 58caf16d505..229d651b371 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/EndpointServletTests.java @@ -27,11 +27,10 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.entry; /** @@ -42,21 +41,18 @@ import static org.assertj.core.api.Assertions.entry; */ public class EndpointServletTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenServletClassIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Servlet must not be null"); - new EndpointServlet((Class) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new EndpointServlet((Class) null)) + .withMessageContaining("Servlet must not be null"); } @Test public void createWhenServletIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Servlet must not be null"); - new EndpointServlet((Servlet) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new EndpointServlet((Servlet) null)) + .withMessageContaining("Servlet must not be null"); } @Test @@ -75,15 +71,15 @@ public class EndpointServletTests { @Test public void withInitParameterNullName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); - this.thrown.expect(IllegalArgumentException.class); - endpointServlet.withInitParameter(null, "value"); + assertThatIllegalArgumentException() + .isThrownBy(() -> endpointServlet.withInitParameter(null, "value")); } @Test public void withInitParameterEmptyName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); - this.thrown.expect(IllegalArgumentException.class); - endpointServlet.withInitParameter(" ", "value"); + assertThatIllegalArgumentException() + .isThrownBy(() -> endpointServlet.withInitParameter(" ", "value")); } @Test @@ -105,15 +101,15 @@ public class EndpointServletTests { @Test public void withInitParametersNullName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); - this.thrown.expect(IllegalArgumentException.class); - endpointServlet.withInitParameters(Collections.singletonMap(null, "value")); + assertThatIllegalArgumentException().isThrownBy(() -> endpointServlet + .withInitParameters(Collections.singletonMap(null, "value"))); } @Test public void withInitParametersEmptyName() { EndpointServlet endpointServlet = new EndpointServlet(TestServlet.class); - this.thrown.expect(IllegalArgumentException.class); - endpointServlet.withInitParameters(Collections.singletonMap(" ", "value")); + assertThatIllegalArgumentException().isThrownBy(() -> endpointServlet + .withInitParameters(Collections.singletonMap(" ", "value"))); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java index 50ce59971d6..6bc7fbb9419 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/LinkTests.java @@ -16,11 +16,10 @@ package org.springframework.boot.actuate.endpoint.web; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link Link}. @@ -29,14 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class LinkTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenHrefIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("HREF must not be null"); - new Link(null); + assertThatIllegalArgumentException().isThrownBy(() -> new Link(null)) + .withMessageContaining("HREF must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java index a142c1b5fac..9afe33cf800 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/PathMappedEndpointsTests.java @@ -20,15 +20,14 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.EndpointsSupplier; import org.springframework.boot.actuate.endpoint.ExposableEndpoint; import org.springframework.boot.actuate.endpoint.Operation; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -39,21 +38,20 @@ import static org.mockito.Mockito.mock; */ public class PathMappedEndpointsTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenSupplierIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Supplier must not be null"); - new PathMappedEndpoints(null, (WebEndpointsSupplier) null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new PathMappedEndpoints(null, (WebEndpointsSupplier) null)) + .withMessageContaining("Supplier must not be null"); } @Test public void createWhenSuppliersIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Suppliers must not be null"); - new PathMappedEndpoints(null, (Collection>) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PathMappedEndpoints(null, + (Collection>) null)) + .withMessageContaining("Suppliers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java index 96cfc705ab5..1cf79e4163b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/ServletEndpointRegistrarTests.java @@ -27,15 +27,14 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -50,9 +49,6 @@ import static org.mockito.Mockito.verify; */ public class ServletEndpointRegistrarTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private ServletContext servletContext; @@ -71,9 +67,9 @@ public class ServletEndpointRegistrarTests { @Test public void createWhenServletEndpointsIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ServletEndpoints must not be null"); - new ServletEndpointRegistrar(null, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ServletEndpointRegistrar(null, null)) + .withMessageContaining("ServletEndpoints must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java index e3cd4c75626..7e3eeb97671 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ControllerEndpointDiscovererTests.java @@ -22,9 +22,7 @@ import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.ExposableEndpoint; import org.springframework.boot.actuate.endpoint.annotation.DiscoveredEndpoint; @@ -41,6 +39,7 @@ import org.springframework.context.annotation.Import; import org.springframework.validation.annotation.Validated; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link ControllerEndpointDiscoverer}. @@ -50,9 +49,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ControllerEndpointDiscovererTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test @@ -140,12 +136,10 @@ public class ControllerEndpointDiscovererTests { @Test public void getEndpointWhenEndpointHasOperationsShouldThrowException() { this.contextRunner.withUserConfiguration(TestControllerWithOperation.class) - .run(assertDiscoverer((discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "ControllerEndpoints must not declare operations"); - discoverer.getEndpoints(); - })); + .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType( + IllegalStateException.class).isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "ControllerEndpoints must not declare operations"))); } private ContextConsumer assertDiscoverer( diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java index 7ae9093cb27..f05cab02236 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/ServletEndpointDiscovererTests.java @@ -29,9 +29,7 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.ExposableEndpoint; import org.springframework.boot.actuate.endpoint.annotation.DiscoveredEndpoint; @@ -50,6 +48,7 @@ import org.springframework.context.annotation.Import; import org.springframework.validation.annotation.Validated; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link ServletEndpointDiscoverer}. @@ -59,9 +58,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ServletEndpointDiscovererTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @Test @@ -116,43 +112,36 @@ public class ServletEndpointDiscovererTests { @Test public void getEndpointWhenEndpointHasOperationsShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointWithOperation.class) - .run(assertDiscoverer((discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "ServletEndpoints must not declare operations"); - discoverer.getEndpoints(); - })); + .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType( + IllegalStateException.class).isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "ServletEndpoints must not declare operations"))); } @Test public void getEndpointWhenEndpointNotASupplierShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointNotASupplier.class) - .run(assertDiscoverer((discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("must be a supplier"); - discoverer.getEndpoints(); - })); + .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType( + IllegalStateException.class).isThrownBy(discoverer::getEndpoints) + .withMessageContaining("must be a supplier"))); } @Test public void getEndpointWhenEndpointSuppliesWrongTypeShouldThrowException() { this.contextRunner .withUserConfiguration(TestServletEndpointSupplierOfWrongType.class) - .run(assertDiscoverer((discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("must supply an EndpointServlet"); - discoverer.getEndpoints(); - })); + .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType( + IllegalStateException.class).isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "must supply an EndpointServlet"))); } @Test public void getEndpointWhenEndpointSuppliesNullShouldThrowException() { this.contextRunner.withUserConfiguration(TestServletEndpointSupplierOfNull.class) - .run(assertDiscoverer((discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("must not supply null"); - discoverer.getEndpoints(); - })); + .run(assertDiscoverer((discoverer) -> assertThatExceptionOfType( + IllegalStateException.class).isThrownBy(discoverer::getEndpoints) + .withMessageContaining("must not supply null"))); } private ContextConsumer assertDiscoverer( diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java index cf31c236d80..01856d0bf1b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/WebEndpointDiscovererTests.java @@ -29,9 +29,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import org.assertj.core.api.Condition; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.annotation.DeleteOperation; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; @@ -58,6 +56,7 @@ import org.springframework.core.io.Resource; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link WebEndpointDiscoverer}. @@ -68,9 +67,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class WebEndpointDiscovererTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void getEndpointsWhenNoEndpointBeansShouldReturnEmptyCollection() { load(EmptyConfiguration.class, @@ -79,13 +75,11 @@ public class WebEndpointDiscovererTests { @Test public void getEndpointsWhenWebExtensionIsMissingEndpointShouldThrowException() { - load(TestWebEndpointExtensionConfiguration.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Invalid extension 'endpointExtension': no endpoint found with id '" - + "test'"); - discoverer.getEndpoints(); - }); + load(TestWebEndpointExtensionConfiguration.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Invalid extension 'endpointExtension': no endpoint found with id '" + + "test'")); } @Test @@ -140,52 +134,49 @@ public class WebEndpointDiscovererTests { @Test public void getEndpointsWhenTwoExtensionsHaveTheSameEndpointTypeShouldThrowException() { - load(ClashingWebEndpointConfiguration.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Found multiple extensions for the endpoint bean " - + "testEndpoint (testExtensionOne, testExtensionTwo)"); - discoverer.getEndpoints(); - }); + load(ClashingWebEndpointConfiguration.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Found multiple extensions for the endpoint bean " + + "testEndpoint (testExtensionOne, testExtensionTwo)")); } @Test public void getEndpointsWhenTwoStandardEndpointsHaveTheSameIdShouldThrowException() { - load(ClashingStandardEndpointConfiguration.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Found two endpoints with the id 'test': "); - discoverer.getEndpoints(); - }); + load(ClashingStandardEndpointConfiguration.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Found two endpoints with the id 'test': ")); } @Test public void getEndpointsWhenWhenEndpointHasTwoOperationsWithTheSameNameShouldThrowException() { - load(ClashingOperationsEndpointConfiguration.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to map duplicate endpoint operations: " - + "[web request predicate GET to path 'test' " - + "produces: application/json] to clashingOperationsEndpoint"); - discoverer.getEndpoints(); - }); + load(ClashingOperationsEndpointConfiguration.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Unable to map duplicate endpoint operations: " + + "[web request predicate GET to path 'test' " + + "produces: application/json] to clashingOperationsEndpoint")); } @Test public void getEndpointsWhenExtensionIsNotCompatibleWithTheEndpointTypeShouldThrowException() { - load(InvalidWebExtensionConfiguration.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Endpoint bean 'nonWebEndpoint' cannot support the " - + "extension bean 'nonWebWebEndpointExtension'"); - discoverer.getEndpoints(); - }); + load(InvalidWebExtensionConfiguration.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints).withMessageContaining( + "Endpoint bean 'nonWebEndpoint' cannot support the " + + "extension bean 'nonWebWebEndpointExtension'")); } @Test public void getEndpointsWhenWhenExtensionHasTwoOperationsWithTheSameNameShouldThrowException() { - load(ClashingSelectorsWebEndpointExtensionConfiguration.class, (discoverer) -> { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to map duplicate endpoint operations"); - this.thrown.expectMessage("to testEndpoint (clashingSelectorsExtension)"); - discoverer.getEndpoints(); - }); + load(ClashingSelectorsWebEndpointExtensionConfiguration.class, + (discoverer) -> assertThatIllegalStateException() + .isThrownBy(discoverer::getEndpoints) + .withMessageContaining( + "Unable to map duplicate endpoint operations") + .withMessageContaining( + "to testEndpoint (clashingSelectorsExtension)")); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java index c789cb0b639..55f3f58a3a2 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/reactive/ControllerEndpointHandlerMappingTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.actuate.endpoint.web.reactive; import java.util.Arrays; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.web.EndpointMapping; import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpoint; @@ -36,6 +34,7 @@ import org.springframework.web.method.HandlerMethod; import org.springframework.web.server.MethodNotAllowedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -47,9 +46,6 @@ import static org.mockito.Mockito.mock; */ public class ControllerEndpointHandlerMappingTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final StaticApplicationContext context = new StaticApplicationContext(); @Test @@ -92,8 +88,8 @@ public class ControllerEndpointHandlerMappingTests { public void mappingNarrowedToMethod() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first); - this.thrown.expect(MethodNotAllowedException.class); - getHandler(mapping, HttpMethod.POST, "/actuator/first"); + assertThatExceptionOfType(MethodNotAllowedException.class).isThrownBy( + () -> getHandler(mapping, HttpMethod.POST, "/actuator/first")); } private Object getHandler(ControllerEndpointHandlerMapping mapping, HttpMethod method, diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java index acdc57b70bf..5616333c4ed 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/web/servlet/ControllerEndpointHandlerMappingTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.actuate.endpoint.web.servlet; import java.util.Arrays; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.web.EndpointMapping; import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpoint; @@ -34,6 +32,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.method.HandlerMethod; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -45,9 +44,6 @@ import static org.mockito.Mockito.mock; */ public class ControllerEndpointHandlerMappingTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final StaticApplicationContext context = new StaticApplicationContext(); @Test @@ -80,8 +76,8 @@ public class ControllerEndpointHandlerMappingTests { public void mappingNarrowedToMethod() throws Exception { ExposableControllerEndpoint first = firstEndpoint(); ControllerEndpointHandlerMapping mapping = createMapping("actuator", first); - this.thrown.expect(HttpRequestMethodNotSupportedException.class); - mapping.getHandler(request("POST", "/actuator/first")); + assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class) + .isThrownBy(() -> mapping.getHandler(request("POST", "/actuator/first"))); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java index 58e6fdcee69..5be4e67ce08 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultHealthIndicatorRegistryTests.java @@ -19,11 +19,11 @@ package org.springframework.boot.actuate.health; import java.util.Map; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -35,9 +35,6 @@ import static org.mockito.Mockito.mock; */ public class DefaultHealthIndicatorRegistryTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private HealthIndicator one = mock(HealthIndicator.class); private HealthIndicator two = mock(HealthIndicator.class); @@ -65,9 +62,10 @@ public class DefaultHealthIndicatorRegistryTests { @Test public void registerAlreadyUsedName() { this.registry.register("one", this.one); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("HealthIndicator with name 'one' already registered"); - this.registry.register("one", this.two); + assertThatIllegalStateException() + .isThrownBy(() -> this.registry.register("one", this.two)) + .withMessageContaining( + "HealthIndicator with name 'one' already registered"); } @Test @@ -102,9 +100,8 @@ public class DefaultHealthIndicatorRegistryTests { public void getAllIsImmutable() { this.registry.register("one", this.one); Map snapshot = this.registry.getAll(); - - this.thrown.expect(UnsupportedOperationException.class); - snapshot.clear(); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(snapshot::clear); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java index 63aa766a587..2a8f9397350 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/DefaultReactiveHealthIndicatorRegistryTests.java @@ -19,12 +19,12 @@ package org.springframework.boot.actuate.health; import java.util.Map; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import reactor.core.publisher.Mono; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -36,9 +36,6 @@ import static org.mockito.Mockito.mock; */ public class DefaultReactiveHealthIndicatorRegistryTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ReactiveHealthIndicator one = mock(ReactiveHealthIndicator.class); private ReactiveHealthIndicator two = mock(ReactiveHealthIndicator.class); @@ -66,9 +63,10 @@ public class DefaultReactiveHealthIndicatorRegistryTests { @Test public void registerAlreadyUsedName() { this.registry.register("one", this.one); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("HealthIndicator with name 'one' already registered"); - this.registry.register("one", this.two); + assertThatIllegalStateException() + .isThrownBy(() -> this.registry.register("one", this.two)) + .withMessageContaining( + "HealthIndicator with name 'one' already registered"); } @Test @@ -103,9 +101,8 @@ public class DefaultReactiveHealthIndicatorRegistryTests { public void getAllIsImmutable() { this.registry.register("one", this.one); Map snapshot = this.registry.getAll(); - - this.thrown.expect(UnsupportedOperationException.class); - snapshot.clear(); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(snapshot::clear); } } diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java index 057703cb3de..c29ba07182b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/HealthTests.java @@ -20,11 +20,10 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.entry; /** @@ -36,14 +35,11 @@ import static org.assertj.core.api.Assertions.entry; */ public class HealthTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void statusMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Status must not be null"); - new Health.Builder(null, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new Health.Builder(null, null)) + .withMessageContaining("Status must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java index ebff837d252..3e201e09589 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/InfoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,11 +16,10 @@ package org.springframework.boot.actuate.info; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.entry; /** @@ -30,15 +29,11 @@ import static org.assertj.core.api.Assertions.entry; */ public class InfoTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void infoIsImmutable() { Info info = new Info.Builder().withDetail("foo", "bar").build(); - - this.thrown.expect(UnsupportedOperationException.class); - info.getDetails().clear(); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(info.getDetails()::clear); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java index d7ac742d1a4..3c031155761 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/info/SimpleInfoContributorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,11 +16,10 @@ package org.springframework.boot.actuate.info; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link SimpleInfoContributor}. @@ -29,13 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class SimpleInfoContributorTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void prefixIsMandatory() { - this.thrown.expect(IllegalArgumentException.class); - new SimpleInfoContributor(null, new Object()); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SimpleInfoContributor(null, new Object())); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java index 3fe4279a386..9cf73189a9b 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/MetricsEndpointTests.java @@ -27,13 +27,12 @@ import io.micrometer.core.instrument.Statistic; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; import io.micrometer.core.instrument.simple.SimpleConfig; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.actuate.endpoint.InvalidEndpointRequestException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link MetricsEndpoint}. @@ -43,9 +42,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class MetricsEndpointTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock()); @@ -118,8 +114,8 @@ public class MetricsEndpointTests { @Test public void metricWithInvalidTag() { - this.thrown.expect(InvalidEndpointRequestException.class); - this.endpoint.metric("counter", Collections.singletonList("key")); + assertThatExceptionOfType(InvalidEndpointRequestException.class).isThrownBy( + () -> this.endpoint.metric("counter", Collections.singletonList("key"))); } @Test diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java index 1bc8cc6db23..e81bab8a8e1 100644 --- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java +++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/system/DiskSpaceHealthIndicatorTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.actuate.system; import java.io.File; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -45,9 +43,6 @@ public class DiskSpaceHealthIndicatorTests { private static final DataSize TOTAL_SPACE = DataSize.ofKilobytes(10); - @Rule - public ExpectedException exception = ExpectedException.none(); - @Mock private File fileMock; diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java index a92060eee92..eb7fd629b83 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationExcludeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,9 +20,7 @@ import java.util.Collections; import java.util.List; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.autoconfigure.context.filtersample.ExampleConfiguration; @@ -33,6 +31,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link AutoConfigurationExcludeFilter}. @@ -43,9 +42,6 @@ public class AutoConfigurationExcludeFilterTests { private static final Class FILTERED = ExampleFilteredAutoConfiguration.class; - @Rule - public ExpectedException thrown = ExpectedException.none(); - private AnnotationConfigApplicationContext context; @After @@ -60,8 +56,8 @@ public class AutoConfigurationExcludeFilterTests { this.context = new AnnotationConfigApplicationContext(Config.class); assertThat(this.context.getBeansOfType(String.class)).hasSize(1); assertThat(this.context.getBean(String.class)).isEqualTo("test"); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(FILTERED); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(FILTERED)); } @Configuration diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java index 9509cc4f1e0..2f83bc11735 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +23,7 @@ import java.util.List; import java.util.Set; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.MockitoAnnotations; import org.springframework.beans.BeansException; @@ -43,6 +41,7 @@ import org.springframework.core.type.StandardAnnotationMetadata; import org.springframework.mock.env.MockEnvironment; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link AutoConfigurationImportSelector} @@ -61,9 +60,6 @@ public class AutoConfigurationImportSelectorTests { private List filters = new ArrayList<>(); - @Rule - public ExpectedException expected = ExpectedException.none(); - @Before public void setup() { MockitoAnnotations.initMocks(this); @@ -173,14 +169,14 @@ public class AutoConfigurationImportSelectorTests { @Test public void nonAutoConfigurationClassExclusionsShouldThrowException() { - this.expected.expect(IllegalStateException.class); - selectImports(EnableAutoConfigurationWithFaultyClassExclude.class); + assertThatIllegalStateException().isThrownBy( + () -> selectImports(EnableAutoConfigurationWithFaultyClassExclude.class)); } @Test public void nonAutoConfigurationClassNameExclusionsWhenPresentOnClassPathShouldThrowException() { - this.expected.expect(IllegalStateException.class); - selectImports(EnableAutoConfigurationWithFaultyClassNameExclude.class); + assertThatIllegalStateException().isThrownBy(() -> selectImports( + EnableAutoConfigurationWithFaultyClassNameExclude.class)); } @Test @@ -188,8 +184,8 @@ public class AutoConfigurationImportSelectorTests { this.environment.setProperty("spring.autoconfigure.exclude", "org.springframework.boot.autoconfigure." + "AutoConfigurationImportSelectorTests.TestConfiguration"); - this.expected.expect(IllegalStateException.class); - selectImports(BasicEnableAutoConfiguration.class); + assertThatIllegalStateException() + .isThrownBy(() -> selectImports(BasicEnableAutoConfiguration.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java index 8e03fa83331..682a86d9ffc 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationPackagesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,9 +18,7 @@ package org.springframework.boot.autoconfigure; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.autoconfigure.AutoConfigurationPackages.Registrar; import org.springframework.boot.autoconfigure.packagestest.one.FirstConfiguration; @@ -30,6 +28,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link AutoConfigurationPackages}. @@ -40,9 +39,6 @@ import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings("resource") public class AutoConfigurationPackagesTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void setAndGet() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( @@ -55,10 +51,10 @@ public class AutoConfigurationPackagesTests { public void getWithoutSet() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( EmptyConfig.class); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Unable to retrieve @EnableAutoConfiguration base packages"); - AutoConfigurationPackages.get(context.getBeanFactory()); + assertThatIllegalStateException() + .isThrownBy(() -> AutoConfigurationPackages.get(context.getBeanFactory())) + .withMessageContaining( + "Unable to retrieve @EnableAutoConfiguration base packages"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java index ec08ad2f402..0a0be3a388b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationSorterTests.java @@ -24,9 +24,7 @@ import java.util.Properties; import java.util.Set; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.Ordered; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; @@ -36,6 +34,7 @@ import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.Mockito.mock; /** @@ -74,9 +73,6 @@ public class AutoConfigurationSorterTests { private static final String W2 = AutoConfigureW2.class.getName(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private AutoConfigurationSorter sorter; private AutoConfigurationMetadata autoConfigurationMetadata = mock( @@ -144,9 +140,10 @@ public class AutoConfigurationSorterTests { public void byAutoConfigureAfterWithCycle() { this.sorter = new AutoConfigurationSorter(new CachingMetadataReaderFactory(), this.autoConfigurationMetadata); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("AutoConfigure cycle detected"); - this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D)); + assertThatIllegalStateException() + .isThrownBy( + () -> this.sorter.getInPriorityOrder(Arrays.asList(A, B, C, D))) + .withMessageContaining("AutoConfigure cycle detected"); } @Test @@ -176,9 +173,9 @@ public class AutoConfigurationSorterTests { this.autoConfigurationMetadata = getAutoConfigurationMetadata(A, B, D); this.sorter = new AutoConfigurationSorter(readerFactory, this.autoConfigurationMetadata); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("AutoConfigure cycle detected"); - this.sorter.getInPriorityOrder(Arrays.asList(D, B)); + assertThatIllegalStateException() + .isThrownBy(() -> this.sorter.getInPriorityOrder(Arrays.asList(D, B))) + .withMessageContaining("AutoConfigure cycle detected"); } private AutoConfigurationMetadata getAutoConfigurationMetadata(String... classNames) diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java index 2a2e391916f..45819fe3404 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -24,9 +24,7 @@ import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -44,6 +42,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.jmx.export.MBeanExporter; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.fail; /** @@ -58,9 +57,6 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { private static final String DEFAULT_JMX_NAME = "org.springframework.boot:type=Admin,name=SpringApplication"; - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() @@ -70,10 +66,9 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { @Test public void notRegisteredByDefault() { - this.contextRunner.run((context) -> { - this.thrown.expect(InstanceNotFoundException.class); - this.server.getObjectInstance(createDefaultObjectName()); - }); + this.contextRunner.run((context) -> assertThatExceptionOfType( + InstanceNotFoundException.class).isThrownBy( + () -> this.server.getObjectInstance(createDefaultObjectName()))); } @Test @@ -99,9 +94,9 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { catch (InstanceNotFoundException ex) { fail("Admin MBean should have been exposed with custom name"); } - this.thrown.expect(InstanceNotFoundException.class); // Should not be - // exposed - this.server.getObjectInstance(createDefaultObjectName()); + assertThatExceptionOfType(InstanceNotFoundException.class) + .isThrownBy(() -> this.server + .getObjectInstance(createDefaultObjectName())); }); } @@ -139,9 +134,9 @@ public class SpringApplicationAdminJmxAutoConfigurationTests { .run("--" + ENABLE_ADMIN_PROP)) { BeanFactoryUtils.beanOfType(parent.getBeanFactory(), SpringApplicationAdminMXBeanRegistrar.class); - this.thrown.expect(NoSuchBeanDefinitionException.class); - BeanFactoryUtils.beanOfType(child.getBeanFactory(), - SpringApplicationAdminMXBeanRegistrar.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> BeanFactoryUtils.beanOfType(child.getBeanFactory(), + SpringApplicationAdminMXBeanRegistrar.class)); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java index 4e6ecea329c..d791d980221 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/amqp/RabbitAutoConfigurationTests.java @@ -28,9 +28,7 @@ import com.rabbitmq.client.Connection; import com.rabbitmq.client.SslContextFactory; import com.rabbitmq.client.TrustEverythingTrustManager; import org.aopalliance.aop.Advice; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.amqp.core.AcknowledgeMode; import org.springframework.amqp.core.AmqpAdmin; @@ -69,6 +67,7 @@ import org.springframework.retry.support.RetryTemplate; 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.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; @@ -85,9 +84,6 @@ import static org.mockito.Mockito.verify; */ public class RabbitAutoConfigurationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(RabbitAutoConfiguration.class)); @@ -413,15 +409,14 @@ public class RabbitAutoConfigurationTests { @Test public void testStaticQueues() { + // There should NOT be an AmqpAdmin bean when dynamic is switch to false this.contextRunner.withUserConfiguration(TestConfiguration.class) - .withPropertyValues("spring.rabbitmq.dynamic:false").run((context) -> { - // There should NOT be an AmqpAdmin bean when dynamic is switch to - // false - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.thrown.expectMessage("No qualifying bean of type"); - this.thrown.expectMessage(AmqpAdmin.class.getName()); - context.getBean(AmqpAdmin.class); - }); + .withPropertyValues("spring.rabbitmq.dynamic:false") + .run((context) -> assertThatExceptionOfType( + NoSuchBeanDefinitionException.class) + .isThrownBy(() -> context.getBean(AmqpAdmin.class)) + .withMessageContaining("No qualifying bean of type '" + + AmqpAdmin.class.getName() + "'")); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java index 12f22443590..76f0900fcc6 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -22,9 +22,7 @@ import java.util.Collections; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.Job; @@ -62,6 +60,7 @@ import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link BatchAutoConfiguration}. @@ -73,9 +72,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class BatchAutoConfigurationTests { - @Rule - public ExpectedException expected = ExpectedException.none(); - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(BatchAutoConfiguration.class, TransactionAutoConfiguration.class)); @@ -176,9 +172,9 @@ public class BatchAutoConfigurationTests { assertThat( context.getBean(BatchProperties.class).getInitializeSchema()) .isEqualTo(DataSourceInitializationMode.NEVER); - this.expected.expect(BadSqlGrammarException.class); - new JdbcTemplate(context.getBean(DataSource.class)) - .queryForList("select * from BATCH_JOB_EXECUTION"); + assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( + () -> new JdbcTemplate(context.getBean(DataSource.class)) + .queryForList("select * from BATCH_JOB_EXECUTION")); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java index ef7614bc81a..048679684f9 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,11 +20,10 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import java.util.function.Consumer; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; @@ -36,8 +35,7 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link ConditionalOnProperty}. @@ -49,9 +47,6 @@ import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage; */ public class ConditionalOnPropertyTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ConfigurableApplicationContext context; private ConfigurableEnvironment environment = new StandardEnvironment(); @@ -205,18 +200,22 @@ public class ConditionalOnPropertyTests { @Test public void nameOrValueMustBeSpecified() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectCause(hasMessage(containsString("The name or " - + "value attribute of @ConditionalOnProperty must be specified"))); - load(NoNameOrValueAttribute.class, "some.property"); + assertThatIllegalStateException() + .isThrownBy(() -> load(NoNameOrValueAttribute.class, "some.property")) + .satisfies(causeMessageContaining( + "The name or value attribute of @ConditionalOnProperty must be specified")); } @Test public void nameAndValueMustNotBeSpecified() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectCause(hasMessage(containsString("The name and " - + "value attributes of @ConditionalOnProperty are exclusive"))); - load(NameAndValueAttribute.class, "some.property"); + assertThatIllegalStateException() + .isThrownBy(() -> load(NameAndValueAttribute.class, "some.property")) + .satisfies(causeMessageContaining( + "The name and value attributes of @ConditionalOnProperty are exclusive")); + } + + private Consumer causeMessageContaining(String message) { + return (ex) -> assertThat(ex.getCause()).hasMessageContaining(message); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java index cb4099d467e..376b6adeb9c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnSingleCandidateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -17,9 +17,7 @@ package org.springframework.boot.autoconfigure.condition; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -27,7 +25,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.isA; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link ConditionalOnSingleCandidate}. @@ -37,9 +35,6 @@ import static org.hamcrest.CoreMatchers.isA; */ public class ConditionalOnSingleCandidateTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @After @@ -126,20 +121,20 @@ public class ConditionalOnSingleCandidateTests { @Test public void invalidAnnotationTwoTypes() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectCause(isA(IllegalArgumentException.class)); - this.thrown.expectMessage( - OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); - load(OnBeanSingleCandidateTwoTypesConfiguration.class); + assertThatIllegalStateException() + .isThrownBy(() -> load(OnBeanSingleCandidateTwoTypesConfiguration.class)) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining( + OnBeanSingleCandidateTwoTypesConfiguration.class.getName()); } @Test public void invalidAnnotationNoType() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectCause(isA(IllegalArgumentException.class)); - this.thrown - .expectMessage(OnBeanSingleCandidateNoTypeConfiguration.class.getName()); - load(OnBeanSingleCandidateNoTypeConfiguration.class); + assertThatIllegalStateException() + .isThrownBy(() -> load(OnBeanSingleCandidateNoTypeConfiguration.class)) + .withCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining( + OnBeanSingleCandidateNoTypeConfiguration.class.getName()); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java index 5ab850997b9..ec19e8bba38 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/SpringBootConditionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package org.springframework.boot.autoconfigure.condition; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -27,6 +25,8 @@ import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.core.type.AnnotatedTypeMetadata; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; + /** * Tests for {@link SpringBootCondition}. * @@ -35,23 +35,22 @@ import org.springframework.core.type.AnnotatedTypeMetadata; @SuppressWarnings("resource") public class SpringBootConditionTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void sensibleClassException() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Error processing condition on " + ErrorOnClass.class.getName()); - new AnnotationConfigApplicationContext(ErrorOnClass.class); + assertThatIllegalStateException() + .isThrownBy( + () -> new AnnotationConfigApplicationContext(ErrorOnClass.class)) + .withMessageContaining( + "Error processing condition on " + ErrorOnClass.class.getName()); } @Test public void sensibleMethodException() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Error processing condition on " - + ErrorOnMethod.class.getName() + ".myBean"); - new AnnotationConfigApplicationContext(ErrorOnMethod.class); + assertThatIllegalStateException() + .isThrownBy( + () -> new AnnotationConfigApplicationContext(ErrorOnMethod.class)) + .withMessageContaining("Error processing condition on " + + ErrorOnMethod.class.getName() + ".myBean"); } @Configuration diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java index 534433a32d6..2958999470f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScanPackagesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,9 +20,7 @@ import java.util.Collection; import java.util.Collections; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -30,6 +28,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.AnnotationConfigurationException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link EntityScanPackages}. @@ -40,9 +40,6 @@ public class EntityScanPackagesTests { private AnnotationConfigApplicationContext context; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @After public void cleanup() { if (this.context != null) { @@ -71,33 +68,36 @@ public class EntityScanPackagesTests { @Test public void registerFromArrayWhenRegistryIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Registry must not be null"); - EntityScanPackages.register(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> EntityScanPackages.register(null)) + .withMessageContaining("Registry must not be null"); } @Test public void registerFromArrayWhenPackageNamesIsNullShouldThrowException() { this.context = new AnnotationConfigApplicationContext(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("PackageNames must not be null"); - EntityScanPackages.register(this.context, (String[]) null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> EntityScanPackages.register(this.context, (String[]) null)) + .withMessageContaining("PackageNames must not be null"); } @Test public void registerFromCollectionWhenRegistryIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Registry must not be null"); - EntityScanPackages.register(null, Collections.emptyList()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> EntityScanPackages.register(null, Collections.emptyList())) + .withMessageContaining("Registry must not be null"); } @Test public void registerFromCollectionWhenPackageNamesIsNullShouldThrowException() { this.context = new AnnotationConfigApplicationContext(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("PackageNames must not be null"); - EntityScanPackages.register(this.context, (Collection) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> EntityScanPackages.register(this.context, + (Collection) null)) + .withMessageContaining("PackageNames must not be null"); } @Test @@ -128,9 +128,9 @@ public class EntityScanPackagesTests { @Test public void entityScanAnnotationWhenHasValueAndBasePackagesAttributeShouldThrow() { - this.thrown.expect(AnnotationConfigurationException.class); - this.context = new AnnotationConfigApplicationContext( - EntityScanValueAndBasePackagesConfig.class); + assertThatExceptionOfType(AnnotationConfigurationException.class) + .isThrownBy(() -> this.context = new AnnotationConfigApplicationContext( + EntityScanValueAndBasePackagesConfig.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java index b85a7f82cdd..124822ac0e8 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/domain/EntityScannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +21,7 @@ import java.util.Set; import javax.persistence.Embeddable; import javax.persistence.Entity; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.autoconfigure.domain.scan.a.EmbeddableA; import org.springframework.boot.autoconfigure.domain.scan.a.EntityA; @@ -35,6 +33,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link EntityScanner}. @@ -43,14 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class EntityScannerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenContextIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Context must not be null"); - new EntityScanner(null); + assertThatIllegalArgumentException().isThrownBy(() -> new EntityScanner(null)) + .withMessageContaining("Context must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java index 4beba145abc..4bc4f7cf88f 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,9 +18,7 @@ package org.springframework.boot.autoconfigure.h2; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.test.util.TestPropertyValues; @@ -29,6 +27,7 @@ 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; /** * Tests for {@link H2ConsoleAutoConfiguration} @@ -41,9 +40,6 @@ public class H2ConsoleAutoConfigurationTests { private AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Before public void setupContext() { this.context.setServletContext(new MockServletContext()); @@ -79,13 +75,13 @@ public class H2ConsoleAutoConfigurationTests { @Test public void customPathMustBeginWithASlash() { - this.thrown.expect(BeanCreationException.class); - this.thrown.expectMessage("Failed to bind properties under 'spring.h2.console'"); this.context.register(H2ConsoleAutoConfiguration.class); TestPropertyValues .of("spring.h2.console.enabled:true", "spring.h2.console.path:custom") .applyTo(this.context); - this.context.refresh(); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(this.context::refresh).withMessageContaining( + "Failed to bind properties under 'spring.h2.console'"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java index 1588c8c9b50..8cfb3be0d17 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/h2/H2ConsolePropertiesTests.java @@ -16,9 +16,9 @@ package org.springframework.boot.autoconfigure.h2; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; + +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link H2ConsoleProperties}. @@ -27,33 +27,29 @@ import org.junit.rules.ExpectedException; */ public class H2ConsolePropertiesTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private H2ConsoleProperties properties; @Test public void pathMustNotBeEmpty() { this.properties = new H2ConsoleProperties(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Path must have length greater than 1"); - this.properties.setPath(""); + assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("")) + .withMessageContaining("Path must have length greater than 1"); } @Test public void pathMustHaveLengthGreaterThanOne() { this.properties = new H2ConsoleProperties(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Path must have length greater than 1"); - this.properties.setPath("/"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.properties.setPath("/")) + .withMessageContaining("Path must have length greater than 1"); } @Test public void customPathMustBeginWithASlash() { this.properties = new H2ConsoleProperties(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Path must start with '/'"); - this.properties.setPath("custom"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.properties.setPath("custom")) + .withMessageContaining("Path must start with '/'"); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java index b3d72fd87a8..e4eb2d4586b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/integration/IntegrationAutoConfigurationTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.autoconfigure.integration; import javax.management.MBeanServer; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.DirectFieldAccessor; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -47,6 +45,7 @@ import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jmx.export.MBeanExporter; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; /** @@ -58,9 +57,6 @@ import static org.mockito.Mockito.mock; */ public class IntegrationAutoConfigurationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JmxAutoConfiguration.class, IntegrationAutoConfiguration.class)); @@ -189,8 +185,8 @@ public class IntegrationAutoConfigurationTests { assertThat(properties.getJdbc().getInitializeSchema()) .isEqualTo(DataSourceInitializationMode.NEVER); JdbcOperations jdbc = context.getBean(JdbcOperations.class); - this.thrown.expect(BadSqlGrammarException.class); - jdbc.queryForList("select * from INT_MESSAGE"); + assertThatExceptionOfType(BadSqlGrammarException.class).isThrownBy( + () -> jdbc.queryForList("select * from INT_MESSAGE")); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java index 3617fec16b2..5fd6a2764f0 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/jdbc/DataSourcePropertiesTests.java @@ -16,14 +16,13 @@ package org.springframework.boot.autoconfigure.jdbc; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.jdbc.EmbeddedDatabaseConnection; import org.springframework.boot.test.context.FilteredClassLoader; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link DataSourceProperties}. @@ -34,9 +33,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class DataSourcePropertiesTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void determineDriver() { DataSourceProperties properties = new DataSourceProperties(); @@ -71,9 +67,10 @@ public class DataSourcePropertiesTests { properties.setBeanClassLoader( new FilteredClassLoader("org.h2", "org.apache.derby", "org.hsqldb")); properties.afterPropertiesSet(); - this.thrown.expect(DataSourceProperties.DataSourceBeanCreationException.class); - this.thrown.expectMessage("Failed to determine suitable jdbc url"); - properties.determineUrl(); + assertThatExceptionOfType( + DataSourceProperties.DataSourceBeanCreationException.class) + .isThrownBy(properties::determineUrl) + .withMessageContaining("Failed to determine suitable jdbc url"); } @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 10b7c7586ff..3dfdb17a6f0 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 @@ -38,9 +38,7 @@ import org.jooq.TransactionListenerProvider; import org.jooq.TransactionalRunnable; import org.jooq.VisitListener; import org.jooq.VisitListenerProvider; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.jdbc.DataSourceBuilder; @@ -69,9 +67,6 @@ public class JooqAutoConfigurationTests { .withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) .withPropertyValues("spring.datasource.name:jooqtest"); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void noDataSource() { this.contextRunner 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 01ca0da25c2..793b58e0e1a 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-2017 the original author or authors. + * Copyright 2012-2018 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,7 +42,7 @@ 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; /** @@ -155,9 +155,9 @@ public class ConditionEvaluationReportLoggingListenerTests { @Test public void listenerSupportsOnlyInfoAndDebug() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy( + assertThatIllegalArgumentException().isThrownBy( () -> new ConditionEvaluationReportLoggingListener(LogLevel.TRACE)) - .withMessage("LogLevel must be INFO or DEBUG"); + .withMessageContaining("LogLevel must be INFO or DEBUG"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java index 5a9e30c3103..712a3cb6ab4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/mongo/ReactiveMongoClientFactoryTests.java @@ -24,14 +24,13 @@ import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.connection.ClusterSettings; import com.mongodb.reactivestreams.client.MongoClient; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.env.Environment; import org.springframework.mock.env.MockEnvironment; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -44,9 +43,6 @@ import static org.mockito.Mockito.verify; */ public class ReactiveMongoClientFactoryTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private MockEnvironment environment = new MockEnvironment(); @Test @@ -126,10 +122,9 @@ public class ReactiveMongoClientFactoryTests { properties.setUri("mongodb://127.0.0.1:1234/mydb"); properties.setUsername("user"); properties.setPassword("secret".toCharArray()); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Invalid mongo configuration, " - + "either uri or host/port/credentials must be specified"); - createMongoClient(properties); + assertThatIllegalStateException().isThrownBy(() -> createMongoClient(properties)) + .withMessageContaining("Invalid mongo configuration, " + + "either uri or host/port/credentials must be specified"); } @Test @@ -138,10 +133,9 @@ public class ReactiveMongoClientFactoryTests { properties.setUri("mongodb://127.0.0.1:1234/mydb"); properties.setHost("localhost"); properties.setPort(4567); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Invalid mongo configuration, " - + "either uri or host/port/credentials must be specified"); - createMongoClient(properties); + assertThatIllegalStateException().isThrownBy(() -> createMongoClient(properties)) + .withMessageContaining("Invalid mongo configuration, " + + "either uri or host/port/credentials must be specified"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java index 700f08019e3..1a5bd21e445 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesRegistrationAdapterTests.java @@ -23,9 +23,7 @@ import java.util.Map; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.LoginClientRegistration; @@ -40,6 +38,7 @@ import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link OAuth2ClientPropertiesRegistrationAdapter}. @@ -59,9 +58,6 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { } } - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void getClientRegistrationsWhenUsingDefinedProviderShouldAdapt() { OAuth2ClientProperties properties = new OAuth2ClientProperties(); @@ -195,9 +191,10 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { OAuth2ClientProperties.LoginClientRegistration login = new OAuth2ClientProperties.LoginClientRegistration(); login.setProvider("missing"); properties.getRegistration().getLogin().put("registration", login); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unknown provider ID 'missing'"); - OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties); + assertThatIllegalStateException() + .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter + .getClientRegistrations(properties)) + .withMessageContaining("Unknown provider ID 'missing'"); } @Test @@ -276,10 +273,11 @@ public class OAuth2ClientPropertiesRegistrationAdapterTests { OAuth2ClientProperties properties = new OAuth2ClientProperties(); OAuth2ClientProperties.LoginClientRegistration login = new OAuth2ClientProperties.LoginClientRegistration(); properties.getRegistration().getLogin().put("missing", login); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Provider ID must be specified for client registration 'missing'"); - OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties); + assertThatIllegalStateException() + .isThrownBy(() -> OAuth2ClientPropertiesRegistrationAdapter + .getClientRegistrations(properties)) + .withMessageContaining( + "Provider ID must be specified for client registration 'missing'"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java index 61c65485417..bf1016eaec2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientPropertiesTests.java @@ -16,13 +16,13 @@ package org.springframework.boot.autoconfigure.security.oauth2.client; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.AuthorizationCodeClientRegistration; import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.LoginClientRegistration; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; + /** * Tests for {@link OAuth2ClientProperties}. * @@ -33,18 +33,14 @@ public class OAuth2ClientPropertiesTests { private OAuth2ClientProperties properties = new OAuth2ClientProperties(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void clientIdAbsentForLoginClientsThrowsException() { LoginClientRegistration registration = new LoginClientRegistration(); registration.setClientSecret("secret"); registration.setProvider("google"); this.properties.getRegistration().getLogin().put("foo", registration); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Client id must not be empty."); - this.properties.validate(); + assertThatIllegalStateException().isThrownBy(this.properties::validate) + .withMessageContaining("Client id must not be empty."); } @Test @@ -62,9 +58,8 @@ public class OAuth2ClientPropertiesTests { registration.setClientSecret("secret"); registration.setProvider("google"); this.properties.getRegistration().getAuthorizationCode().put("foo", registration); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Client id must not be empty."); - this.properties.validate(); + assertThatIllegalStateException().isThrownBy(this.properties::validate) + .withMessageContaining("Client id must not be empty."); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java index ca02bc94285..47e6043d7f4 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/reactive/StaticResourceRequestTests.java @@ -17,9 +17,7 @@ package org.springframework.boot.autoconfigure.security.reactive; import org.assertj.core.api.AssertDelegateTarget; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.autoconfigure.security.StaticResourceLocation; import org.springframework.boot.autoconfigure.web.ServerProperties; @@ -35,6 +33,7 @@ import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.HttpWebHandlerAdapter; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -46,9 +45,6 @@ public class StaticResourceRequestTests { private StaticResourceRequest resourceRequest = StaticResourceRequest.INSTANCE; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void atCommonLocationsShouldMatchCommonLocations() { ServerWebExchangeMatcher matcher = this.resourceRequest.atCommonLocations(); @@ -78,16 +74,17 @@ public class StaticResourceRequestTests { @Test public void atLocationsFromSetWhenSetIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Locations must not be null"); - this.resourceRequest.at(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.resourceRequest.at(null)) + .withMessageContaining("Locations must not be null"); } @Test public void excludeFromSetWhenSetIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Locations must not be null"); - this.resourceRequest.atCommonLocations().excluding(null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> this.resourceRequest.atCommonLocations().excluding(null)) + .withMessageContaining("Locations must not be null"); } private RequestMatcherAssert assertMatcher(ServerWebExchangeMatcher matcher) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java index 8855a8f106e..b3c4ecc1b6c 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/security/servlet/StaticResourceRequestTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.autoconfigure.security.servlet; import javax.servlet.http.HttpServletRequest; import org.assertj.core.api.AssertDelegateTarget; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.autoconfigure.security.StaticResourceLocation; import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath; @@ -32,6 +30,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StaticWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link StaticResourceRequest}. @@ -43,9 +42,6 @@ public class StaticResourceRequestTests { private StaticResourceRequest resourceRequest = StaticResourceRequest.INSTANCE; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void atCommonLocationsShouldMatchCommonLocations() { RequestMatcher matcher = this.resourceRequest.atCommonLocations(); @@ -81,16 +77,17 @@ public class StaticResourceRequestTests { @Test public void atLocationsFromSetWhenSetIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Locations must not be null"); - this.resourceRequest.at(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.resourceRequest.at(null)) + .withMessageContaining("Locations must not be null"); } @Test public void excludeFromSetWhenSetIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Locations must not be null"); - this.resourceRequest.atCommonLocations().excluding(null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> this.resourceRequest.atCommonLocations().excluding(null)) + .withMessageContaining("Locations must not be null"); } private RequestMatcherAssert assertMatcher(RequestMatcher matcher) { diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java index fa85bff1486..edee75940c2 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/session/SessionAutoConfigurationJdbcTests.java @@ -16,9 +16,7 @@ package org.springframework.boot.autoconfigure.session; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.DirectFieldAccessor; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -39,6 +37,7 @@ import org.springframework.session.hazelcast.HazelcastSessionRepository; import org.springframework.session.jdbc.JdbcOperationsSessionRepository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * JDBC specific tests for {@link SessionAutoConfiguration}. @@ -49,9 +48,6 @@ import static org.assertj.core.api.Assertions.assertThat; public class SessionAutoConfigurationJdbcTests extends AbstractSessionAutoConfigurationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, @@ -109,9 +105,9 @@ public class SessionAutoConfigurationJdbcTests assertThat(context.getBean(JdbcSessionProperties.class) .getInitializeSchema()) .isEqualTo(DataSourceInitializationMode.NEVER); - this.thrown.expect(BadSqlGrammarException.class); - context.getBean(JdbcOperations.class) - .queryForList("select * from SPRING_SESSION"); + assertThatExceptionOfType(BadSqlGrammarException.class) + .isThrownBy(() -> context.getBean(JdbcOperations.class) + .queryForList("select * from SPRING_SESSION")); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java index 5ff219ab1c0..03a6f874330 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/template/TemplateAvailabilityProvidersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,9 +20,7 @@ import java.util.Collection; import java.util.Collections; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -31,6 +29,7 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.mock.env.MockEnvironment; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -43,9 +42,6 @@ import static org.mockito.Mockito.verify; */ public class TemplateAvailabilityProvidersTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private TemplateAvailabilityProviders providers; @Mock @@ -69,9 +65,9 @@ public class TemplateAvailabilityProvidersTests { @Test public void createWhenApplicationContextIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ClassLoader must not be null"); - new TemplateAvailabilityProviders((ApplicationContext) null); + assertThatIllegalArgumentException().isThrownBy( + () -> new TemplateAvailabilityProviders((ApplicationContext) null)) + .withMessageContaining("ClassLoader must not be null"); } @Test @@ -86,9 +82,9 @@ public class TemplateAvailabilityProvidersTests { @Test public void createWhenClassLoaderIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ClassLoader must not be null"); - new TemplateAvailabilityProviders((ClassLoader) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new TemplateAvailabilityProviders((ClassLoader) null)) + .withMessageContaining("ClassLoader must not be null"); } @Test @@ -100,10 +96,10 @@ public class TemplateAvailabilityProvidersTests { @Test public void createWhenProvidersIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Providers must not be null"); - new TemplateAvailabilityProviders( - (Collection) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new TemplateAvailabilityProviders( + (Collection) null)) + .withMessageContaining("Providers must not be null"); } @Test @@ -115,40 +111,41 @@ public class TemplateAvailabilityProvidersTests { @Test public void getProviderWhenApplicationContextIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ApplicationContext must not be null"); - this.providers.getProvider(this.view, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.providers.getProvider(this.view, null)) + .withMessageContaining("ApplicationContext must not be null"); } @Test public void getProviderWhenViewIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("View must not be null"); - this.providers.getProvider(null, this.environment, this.classLoader, - this.resourceLoader); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.providers.getProvider(null, this.environment, + this.classLoader, this.resourceLoader)) + .withMessageContaining("View must not be null"); } @Test public void getProviderWhenEnvironmentIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Environment must not be null"); - this.providers.getProvider(this.view, null, this.classLoader, - this.resourceLoader); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.providers.getProvider(this.view, null, + this.classLoader, this.resourceLoader)) + .withMessageContaining("Environment must not be null"); } @Test public void getProviderWhenClassLoaderIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ClassLoader must not be null"); - this.providers.getProvider(this.view, this.environment, null, - this.resourceLoader); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, + null, this.resourceLoader)) + .withMessageContaining("ClassLoader must not be null"); } @Test public void getProviderWhenResourceLoaderIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ResourceLoader must not be null"); - this.providers.getProvider(this.view, this.environment, this.classLoader, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.providers.getProvider(this.view, this.environment, + this.classLoader, null)) + .withMessageContaining("ResourceLoader must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java index 7d005602c19..652667d5143 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/transaction/jta/JtaAutoConfigurationTests.java @@ -36,9 +36,7 @@ import com.atomikos.icatch.jta.UserTransactionManager; import com.atomikos.jms.AtomikosConnectionFactoryBean; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration; @@ -60,6 +58,7 @@ import org.springframework.transaction.jta.JtaTransactionManager; import org.springframework.util.FileSystemUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -73,9 +72,6 @@ import static org.mockito.Mockito.mock; */ public class JtaAutoConfigurationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private AnnotationConfigApplicationContext context; @Before @@ -94,8 +90,8 @@ public class JtaAutoConfigurationTests { public void customPlatformTransactionManager() { this.context = new AnnotationConfigApplicationContext( CustomTransactionManagerConfig.class, JtaAutoConfiguration.class); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(JtaTransactionManager.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(JtaTransactionManager.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java index 10982001440..39b89687a83 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfigurationTests.java @@ -25,9 +25,7 @@ import javax.validation.constraints.Min; import javax.validation.constraints.Size; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -44,6 +42,7 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcess import org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; /** @@ -54,9 +53,6 @@ import static org.mockito.Mockito.mock; */ public class ValidationAutoConfigurationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private AnnotationConfigApplicationContext context; @After @@ -161,8 +157,8 @@ public class ValidationAutoConfigurationTests { assertThat(this.context.getBeansOfType(Validator.class)).hasSize(1); SampleService service = this.context.getBean(SampleService.class); service.doSomething("Valid"); - this.thrown.expect(ConstraintViolationException.class); - service.doSomething("KO"); + assertThatExceptionOfType(ConstraintViolationException.class) + .isThrownBy(() -> service.doSomething("KO")); } @Test @@ -172,8 +168,8 @@ public class ValidationAutoConfigurationTests { DefaultAnotherSampleService service = this.context .getBean(DefaultAnotherSampleService.class); service.doSomething(42); - this.thrown.expect(ConstraintViolationException.class); - service.doSomething(2); + assertThatExceptionOfType(ConstraintViolationException.class) + .isThrownBy(() -> service.doSomething(2)); } @Test @@ -185,8 +181,8 @@ public class ValidationAutoConfigurationTests { .isEmpty(); AnotherSampleService service = this.context.getBean(AnotherSampleService.class); service.doSomething(42); - this.thrown.expect(ConstraintViolationException.class); - service.doSomething(2); + assertThatExceptionOfType(ConstraintViolationException.class) + .isThrownBy(() -> service.doSomething(2)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java index 6a9a849838f..64bcafe2508 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/ServerPropertiesTests.java @@ -292,7 +292,7 @@ public class ServerPropertiesTests { jetty.start(); org.eclipse.jetty.server.Connector connector = jetty.getServer() .getConnectors()[0]; - final AtomicReference failure = new AtomicReference(); + final AtomicReference failure = new AtomicReference<>(); connector.addBean(new HttpChannel.Listener() { @Override @@ -318,14 +318,14 @@ public class ServerPropertiesTests { }); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - MultiValueMap body = new LinkedMultiValueMap(); + MultiValueMap body = new LinkedMultiValueMap<>(); StringBuilder data = new StringBuilder(); for (int i = 0; i < 250000; i++) { data.append("a"); } body.add("data", data.toString()); - HttpEntity> entity = new HttpEntity>( - body, headers); + HttpEntity> entity = new HttpEntity<>(body, + headers); template.postForEntity( URI.create("http://localhost:" + jetty.getPort() + "/form"), entity, Void.class); diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java index ba177ede8a2..b289338aa5a 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/reactive/error/DefaultErrorWebExceptionHandlerIntegrationTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.autoconfigure.web.reactive.error; import javax.validation.Valid; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import reactor.core.publisher.Mono; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -43,7 +41,7 @@ import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration tests for {@link DefaultErrorWebExceptionHandler} @@ -63,9 +61,6 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { "server.port=0") .withUserConfiguration(Application.class); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void jsonError() { this.contextRunner.run((context) -> { @@ -241,9 +236,11 @@ public class DefaultErrorWebExceptionHandlerIntegrationTests { this.contextRunner.run((context) -> { WebTestClient client = WebTestClient.bindToApplicationContext(context) .build(); - this.thrown.expectCause(instanceOf(IllegalStateException.class)); - this.thrown.expectMessage("already committed!"); - client.get().uri("/commit").exchange().expectStatus(); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy( + () -> client.get().uri("/commit").exchange().expectStatus()) + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("already committed!"); }); } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBeanTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBeanTests.java index 5f0e70278a3..a730288482b 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/DispatcherServletRegistrationBeanTests.java @@ -18,13 +18,13 @@ package org.springframework.boot.autoconfigure.web.servlet; import java.util.Collections; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.web.servlet.DispatcherServlet; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DispatcherServletRegistrationBean}. @@ -33,14 +33,12 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class DispatcherServletRegistrationBeanTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenPathIsNullThrowsException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Path must not be null"); - new DispatcherServletRegistrationBean(new DispatcherServlet(), null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DispatcherServletRegistrationBean( + new DispatcherServlet(), null)) + .withMessageContaining("Path must not be null"); } @Test @@ -61,16 +59,16 @@ public class DispatcherServletRegistrationBeanTests { public void setUrlMappingsCannotBeCalled() { DispatcherServletRegistrationBean bean = new DispatcherServletRegistrationBean( new DispatcherServlet(), "/test"); - this.thrown.expect(UnsupportedOperationException.class); - bean.setUrlMappings(Collections.emptyList()); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(() -> bean.setUrlMappings(Collections.emptyList())); } @Test public void addUrlMappingsCannotBeCalled() { DispatcherServletRegistrationBean bean = new DispatcherServletRegistrationBean( new DispatcherServlet(), "/test"); - this.thrown.expect(UnsupportedOperationException.class); - bean.addUrlMappings("/test"); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(() -> bean.addUrlMappings("/test")); } } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfigurationTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfigurationTests.java index ed2de567f72..31bcde0d68d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/HttpEncodingAutoConfigurationTests.java @@ -25,9 +25,7 @@ import java.util.Map; import javax.servlet.Filter; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.test.util.TestPropertyValues; @@ -44,6 +42,7 @@ import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.filter.HiddenHttpMethodFilter; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link HttpEncodingAutoConfiguration} @@ -52,9 +51,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class HttpEncodingAutoConfigurationTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private AnnotationConfigWebApplicationContext context; @After @@ -75,8 +71,8 @@ public class HttpEncodingAutoConfigurationTests { @Test public void disableConfiguration() { load(EmptyConfiguration.class, "spring.http.encoding.enabled:false"); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(CharacterEncodingFilter.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(CharacterEncodingFilter.class)); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerDirectMockMvcTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerDirectMockMvcTests.java index dd348473a2e..1590e756804 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerDirectMockMvcTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/BasicErrorControllerDirectMockMvcTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -29,9 +29,7 @@ import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -53,6 +51,7 @@ import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -65,9 +64,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ public class BasicErrorControllerDirectMockMvcTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private ConfigurableWebApplicationContext wac; private MockMvc mockMvc; @@ -110,8 +106,8 @@ public class BasicErrorControllerDirectMockMvcTests { setup((ConfigurableWebApplicationContext) new SpringApplication( WebMvcIncludedConfiguration.class).run("--server.port=0", "--server.error.whitelabel.enabled=false")); - this.thrown.expect(ServletException.class); - this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML)); + assertThatExceptionOfType(ServletException.class).isThrownBy( + () -> this.mockMvc.perform(get("/error").accept(MediaType.TEXT_HTML))); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java index 03c8272258c..4b7d49c214d 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +23,7 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -44,6 +42,7 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.web.servlet.ModelAndView; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -59,9 +58,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; */ public class DefaultErrorViewResolverTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private DefaultErrorViewResolver resolver; @Mock @@ -87,16 +83,16 @@ public class DefaultErrorViewResolverTests { @Test public void createWhenApplicationContextIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ApplicationContext must not be null"); - new DefaultErrorViewResolver(null, new ResourceProperties()); + assertThatIllegalArgumentException().isThrownBy( + () -> new DefaultErrorViewResolver(null, new ResourceProperties())) + .withMessageContaining("ApplicationContext must not be null"); } @Test public void createWhenResourcePropertiesIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ResourceProperties must not be null"); - new DefaultErrorViewResolver(mock(ApplicationContext.class), null); + assertThatIllegalArgumentException().isThrownBy( + () -> new DefaultErrorViewResolver(mock(ApplicationContext.class), null)) + .withMessageContaining("ResourceProperties must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java index f7000143641..92576a13e41 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/webservices/WebServicesPropertiesTests.java @@ -16,9 +16,9 @@ package org.springframework.boot.autoconfigure.webservices; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; + +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link WebServicesProperties}. @@ -27,33 +27,29 @@ import org.junit.rules.ExpectedException; */ public class WebServicesPropertiesTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private WebServicesProperties properties; @Test public void pathMustNotBeEmpty() { this.properties = new WebServicesProperties(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Path must have length greater than 1"); - this.properties.setPath(""); + assertThatIllegalArgumentException().isThrownBy(() -> this.properties.setPath("")) + .withMessageContaining("Path must have length greater than 1"); } @Test public void pathMustHaveLengthGreaterThanOne() { this.properties = new WebServicesProperties(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Path must have length greater than 1"); - this.properties.setPath("/"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.properties.setPath("/")) + .withMessageContaining("Path must have length greater than 1"); } @Test public void customPathMustBeginWithASlash() { this.properties = new WebServicesProperties(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Path must start with '/'"); - this.properties.setPath("custom"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.properties.setPath("custom")) + .withMessageContaining("Path must start with '/'"); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java index 033e552c617..0324d35593e 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/ReproIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,11 +16,13 @@ package org.springframework.boot.cli; +import java.util.concurrent.ExecutionException; + import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration tests to exercise and reproduce specific issues. @@ -34,9 +36,6 @@ public class ReproIntegrationTests { @Rule public CliTester cli = new CliTester("src/test/resources/repro-samples/"); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void grabAntBuilder() throws Exception { this.cli.run("grab-ant-builder.groovy"); @@ -57,9 +56,9 @@ public class ReproIntegrationTests { @Test public void jarFileExtensionNeeded() throws Exception { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("is not a JAR file"); - this.cli.jar("secure.groovy", "data-jpa.groovy"); + assertThatExceptionOfType(ExecutionException.class) + .isThrownBy(() -> this.cli.jar("secure.groovy", "data-jpa.groovy")) + .withMessageContaining("is not a JAR file"); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java index 7d56193ece6..a1391090d6b 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/CommandRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +21,7 @@ import java.util.Set; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -31,6 +29,7 @@ import org.springframework.boot.cli.command.core.HelpCommand; import org.springframework.boot.cli.command.core.HintCommand; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.verify; @@ -43,9 +42,6 @@ import static org.mockito.Mockito.verify; */ public class CommandRunnerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private CommandRunner commandRunner; @Mock @@ -101,8 +97,8 @@ public class CommandRunnerTests { @Test public void runWithoutArguments() throws Exception { - this.thrown.expect(NoArgumentsException.class); - this.commandRunner.run(); + assertThatExceptionOfType(NoArgumentsException.class) + .isThrownBy(this.commandRunner::run); } @Test @@ -113,8 +109,8 @@ public class CommandRunnerTests { @Test public void missingCommand() throws Exception { - this.thrown.expect(NoSuchCommandException.class); - this.commandRunner.run("missing"); + assertThatExceptionOfType(NoSuchCommandException.class) + .isThrownBy(() -> this.commandRunner.run("missing")); } @Test @@ -188,14 +184,14 @@ public class CommandRunnerTests { @Test public void helpNoCommand() throws Exception { - this.thrown.expect(NoHelpCommandArgumentsException.class); - this.commandRunner.run("help"); + assertThatExceptionOfType(NoHelpCommandArgumentsException.class) + .isThrownBy(() -> this.commandRunner.run("help")); } @Test public void helpUnknownCommand() throws Exception { - this.thrown.expect(NoSuchCommandException.class); - this.commandRunner.run("help", "missing"); + assertThatExceptionOfType(NoSuchCommandException.class) + .isThrownBy(() -> this.commandRunner.run("help", "missing")); } private enum Call { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java index 427805f1556..c728637dff4 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/InitializrServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,11 +18,10 @@ package org.springframework.boot.cli.command.init; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -34,9 +33,6 @@ import static org.mockito.Mockito.mock; */ public class InitializrServiceTests extends AbstractHttpClientMockTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final InitializrService invoker = new InitializrService(this.http); @Test @@ -81,18 +77,18 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { mockProjectGenerationError(400, jsonMessage); ProjectGenerationRequest request = new ProjectGenerationRequest(); request.getDependencies().add("foo:bar"); - this.thrown.expect(ReportableException.class); - this.thrown.expectMessage(jsonMessage); - this.invoker.generate(request); + assertThatExceptionOfType(ReportableException.class) + .isThrownBy(() -> this.invoker.generate(request)) + .withMessageContaining(jsonMessage); } @Test public void generateProjectBadRequestNoExtraMessage() throws Exception { mockProjectGenerationError(400, null); ProjectGenerationRequest request = new ProjectGenerationRequest(); - this.thrown.expect(ReportableException.class); - this.thrown.expectMessage("unexpected 400 error"); - this.invoker.generate(request); + assertThatExceptionOfType(ReportableException.class) + .isThrownBy(() -> this.invoker.generate(request)) + .withMessageContaining("unexpected 400 error"); } @Test @@ -102,9 +98,9 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { mockStatus(response, 500); given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); - this.thrown.expect(ReportableException.class); - this.thrown.expectMessage("No content received from server"); - this.invoker.generate(request); + assertThatExceptionOfType(ReportableException.class) + .isThrownBy(() -> this.invoker.generate(request)) + .withMessageContaining("No content received from server"); } @Test @@ -112,9 +108,9 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { String jsonMessage = "whatever error on the server"; mockMetadataGetError(500, jsonMessage); ProjectGenerationRequest request = new ProjectGenerationRequest(); - this.thrown.expect(ReportableException.class); - this.thrown.expectMessage(jsonMessage); - this.invoker.generate(request); + assertThatExceptionOfType(ReportableException.class) + .isThrownBy(() -> this.invoker.generate(request)) + .withMessageContaining(jsonMessage); } @Test @@ -124,9 +120,9 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { mockStatus(response, 200); given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); - this.thrown.expect(ReportableException.class); - this.thrown.expectMessage("Invalid content received from server"); - this.invoker.generate(request); + assertThatExceptionOfType(ReportableException.class) + .isThrownBy(() -> this.invoker.generate(request)) + .withMessageContaining("Invalid content received from server"); } @Test @@ -135,9 +131,9 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests { mockStatus(response, 500); given(this.http.execute(isA(HttpGet.class))).willReturn(response); ProjectGenerationRequest request = new ProjectGenerationRequest(); - this.thrown.expect(ReportableException.class); - this.thrown.expectMessage("No content received from server"); - this.invoker.generate(request); + assertThatExceptionOfType(ReportableException.class) + .isThrownBy(() -> this.invoker.generate(request)) + .withMessageContaining("No content received from server"); } private ProjectGenerationResponse generateProject(ProjectGenerationRequest request, diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java index c08d9f61d80..51182819fe0 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/init/ProjectGenerationRequestTests.java @@ -25,15 +25,14 @@ import java.util.Map; import org.json.JSONException; import org.json.JSONObject; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.StreamUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link ProjectGenerationRequest}. @@ -45,9 +44,6 @@ public class ProjectGenerationRequestTests { public static final Map EMPTY_TAGS = Collections.emptyMap(); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final ProjectGenerationRequest request = new ProjectGenerationRequest(); @Test @@ -172,19 +168,19 @@ public class ProjectGenerationRequestTests { public void buildNoMatch() throws Exception { InitializrServiceMetadata metadata = readMetadata(); setBuildAndFormat("does-not-exist", null); - this.thrown.expect(ReportableException.class); - this.thrown.expectMessage("does-not-exist"); - this.request.generateUrl(metadata); + assertThatExceptionOfType(ReportableException.class) + .isThrownBy(() -> this.request.generateUrl(metadata)) + .withMessageContaining("does-not-exist"); } @Test public void buildMultipleMatch() throws Exception { InitializrServiceMetadata metadata = readMetadata("types-conflict"); setBuildAndFormat("gradle", null); - this.thrown.expect(ReportableException.class); - this.thrown.expectMessage("gradle-project"); - this.thrown.expectMessage("gradle-project-2"); - this.request.generateUrl(metadata); + assertThatExceptionOfType(ReportableException.class) + .isThrownBy(() -> this.request.generateUrl(metadata)) + .withMessageContaining("gradle-project") + .withMessageContaining("gradle-project-2"); } @Test @@ -207,15 +203,16 @@ public class ProjectGenerationRequestTests { @Test public void invalidType() { this.request.setType("does-not-exist"); - this.thrown.expect(ReportableException.class); - this.request.generateUrl(createDefaultMetadata()); + assertThatExceptionOfType(ReportableException.class) + .isThrownBy(() -> this.request.generateUrl(createDefaultMetadata())); } @Test public void noTypeAndNoDefault() throws Exception { - this.thrown.expect(ReportableException.class); - this.thrown.expectMessage("no default is defined"); - this.request.generateUrl(readMetadata("types-conflict")); + assertThatExceptionOfType(ReportableException.class) + .isThrownBy( + () -> this.request.generateUrl(readMetadata("types-conflict"))) + .withMessageContaining("no default is defined"); } private static URI createUrl(String actionAndParam) { diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java index 6d8b64d383e..08e07cec081 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/command/run/SpringApplicationRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,11 +18,9 @@ package org.springframework.boot.cli.command.run; import java.util.logging.Level; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -33,19 +31,16 @@ import static org.mockito.Mockito.mock; */ public class SpringApplicationRunnerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void exceptionMessageWhenSourcesContainsNoClasses() throws Exception { SpringApplicationRunnerConfiguration configuration = mock( SpringApplicationRunnerConfiguration.class); given(configuration.getClasspath()).willReturn(new String[] { "foo", "bar" }); given(configuration.getLogLevel()).willReturn(Level.INFO); - this.thrown.expect(RuntimeException.class); - this.thrown.expectMessage(equalTo("No classes found in '[foo, bar]'")); - new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }) - .compileAndRun(); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> new SpringApplicationRunner(configuration, + new String[] { "foo", "bar" }).compileAndRun()) + .withMessage("No classes found in '[foo, bar]'"); } } diff --git a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java index bcc9294a19b..29206664135 100644 --- a/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java +++ b/spring-boot-project/spring-boot-cli/src/test/java/org/springframework/boot/cli/compiler/ExtendedGroovyClassLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -17,11 +17,10 @@ package org.springframework.boot.cli.compiler; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link ExtendedGroovyClassLoader}. @@ -30,9 +29,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ExtendedGroovyClassLoaderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ClassLoader contextClassLoader; private ExtendedGroovyClassLoader defaultScopeGroovyClassLoader; @@ -54,9 +50,9 @@ public class ExtendedGroovyClassLoaderTests { @Test public void filtersNonGroovy() throws Exception { this.contextClassLoader.loadClass("org.springframework.util.StringUtils"); - this.thrown.expect(ClassNotFoundException.class); - this.defaultScopeGroovyClassLoader - .loadClass("org.springframework.util.StringUtils"); + assertThatExceptionOfType(ClassNotFoundException.class) + .isThrownBy(() -> this.defaultScopeGroovyClassLoader + .loadClass("org.springframework.util.StringUtils")); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java index 91d274eefab..7d9c2750c04 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,9 +18,7 @@ package org.springframework.boot.devtools; import ch.qos.logback.classic.Logger; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; @@ -29,6 +27,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link RemoteUrlPropertyExtractor}. @@ -37,9 +36,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class RemoteUrlPropertyExtractorTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @After public void preventRunFailuresFromPollutingLoggerContext() { ((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class)) @@ -48,24 +44,23 @@ public class RemoteUrlPropertyExtractorTests { @Test public void missingUrl() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("No remote URL specified"); - doTest(); + assertThatIllegalStateException().isThrownBy(() -> doTest()) + .withMessageContaining("No remote URL specified"); } @Test public void malformedUrl() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Malformed URL '::://wibble'"); - doTest("::://wibble"); + assertThatIllegalStateException().isThrownBy(() -> doTest("::://wibble")) + .withMessageContaining("Malformed URL '::://wibble'"); } @Test public void multipleUrls() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Multiple URLs specified"); - doTest("http://localhost:8080", "http://localhost:9090"); + assertThatIllegalStateException() + .isThrownBy( + () -> doTest("http://localhost:8080", "http://localhost:9090")) + .withMessageContaining("Multiple URLs specified"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java index 35297c72a7b..775a896b26f 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/LocalDevToolsAutoConfigurationTests.java @@ -28,7 +28,6 @@ import org.apache.jasper.EmbeddedServletOptions; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -56,6 +55,7 @@ import org.springframework.data.redis.core.RedisTemplate; 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.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -71,9 +71,6 @@ import static org.mockito.Mockito.verify; */ public class LocalDevToolsAutoConfigurationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public MockRestarter mockRestarter = new MockRestarter(); @@ -168,8 +165,8 @@ public class LocalDevToolsAutoConfigurationTests { Map properties = new HashMap<>(); properties.put("spring.devtools.livereload.enabled", false); this.context = initializeAndRun(Config.class, properties); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(OptionalLiveReloadServer.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); } @Test @@ -203,8 +200,8 @@ public class LocalDevToolsAutoConfigurationTests { Map properties = new HashMap<>(); properties.put("spring.devtools.restart.enabled", false); this.context = initializeAndRun(Config.class, properties); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(ClassPathFileSystemWatcher.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java index a44ad1aec13..6ba057993d8 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/RemoteDevToolsAutoConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,7 +20,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; @@ -41,6 +40,7 @@ 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.mockito.Mockito.mock; /** @@ -58,9 +58,6 @@ public class RemoteDevToolsAutoConfigurationTests { @Rule public MockRestarter mockRestarter = new MockRestarter(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private AnnotationConfigWebApplicationContext context; private MockHttpServletRequest request; @@ -86,8 +83,8 @@ public class RemoteDevToolsAutoConfigurationTests { @Test public void disabledIfRemoteSecretIsMissing() { loadContext("a:b"); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(DispatcherFilter.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(DispatcherFilter.class)); } @Test @@ -144,8 +141,8 @@ public class RemoteDevToolsAutoConfigurationTests { public void disableRestart() { loadContext("spring.devtools.remote.secret:supersecret", "spring.devtools.remote.restart.enabled:false"); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean("remoteRestartHandlerMapper"); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean("remoteRestartHandlerMapper")); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java index f84352ce964..6679efee77b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/autoconfigure/TriggerFileFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,10 +20,10 @@ import java.io.File; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link TriggerFileFilter}. @@ -32,17 +32,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class TriggerFileFilterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void nameMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Name must not be null"); - new TriggerFileFilter(null); + assertThatIllegalArgumentException().isThrownBy(() -> new TriggerFileFilter(null)) + .withMessageContaining("Name must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java index e1cd9652bb8..fedb5a202f7 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathChangedEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -19,13 +19,12 @@ package org.springframework.boot.devtools.classpath; import java.util.LinkedHashSet; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.devtools.filewatch.ChangedFiles; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ClassPathChangedEvent}. @@ -34,16 +33,13 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ClassPathChangedEventTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private Object source = new Object(); @Test public void changeSetMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ChangeSet must not be null"); - new ClassPathChangedEvent(this.source, null, false); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassPathChangedEvent(this.source, null, false)) + .withMessageContaining("ChangeSet must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java index dd126b41e1d..22cb896c51b 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileChangeListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -22,9 +22,7 @@ import java.util.LinkedHashSet; import java.util.Set; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -37,6 +35,7 @@ import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -48,9 +47,6 @@ import static org.mockito.Mockito.verify; */ public class ClassPathFileChangeListenerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private ApplicationEventPublisher eventPublisher; @@ -70,18 +66,18 @@ public class ClassPathFileChangeListenerTests { @Test public void eventPublisherMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("EventPublisher must not be null"); - new ClassPathFileChangeListener(null, this.restartStrategy, - this.fileSystemWatcher); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassPathFileChangeListener(null, + this.restartStrategy, this.fileSystemWatcher)) + .withMessageContaining("EventPublisher must not be null"); } @Test public void restartStrategyMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RestartStrategy must not be null"); - new ClassPathFileChangeListener(this.eventPublisher, null, - this.fileSystemWatcher); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassPathFileChangeListener(this.eventPublisher, + null, this.fileSystemWatcher)) + .withMessageContaining("RestartStrategy must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java index cec76f85a28..c86cde1a869 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/classpath/ClassPathFileSystemWatcherTests.java @@ -26,7 +26,6 @@ import java.util.Map; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.devtools.filewatch.FileSystemWatcher; @@ -40,6 +39,7 @@ import org.springframework.core.env.MapPropertySource; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -49,19 +49,16 @@ import static org.mockito.Mockito.mock; */ public class ClassPathFileSystemWatcherTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void urlsMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Urls must not be null"); - URL[] urls = null; - new ClassPathFileSystemWatcher(mock(FileSystemWatcherFactory.class), - mock(ClassPathRestartStrategy.class), urls); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassPathFileSystemWatcher( + mock(FileSystemWatcherFactory.class), + mock(ClassPathRestartStrategy.class), (URL[]) null)) + .withMessageContaining("Urls must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java index 264cc94a6e3..6b229e56810 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolPropertiesIntegrationTests.java @@ -21,9 +21,7 @@ import java.util.Collections; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.SpringApplication; @@ -38,6 +36,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration tests for the configuration of development-time properties @@ -46,9 +45,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class DevToolPropertiesIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ConfigurableApplicationContext context; @Before @@ -90,8 +86,8 @@ public class DevToolPropertiesIntegrationTests { BeanConditionConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); this.context = application.run(); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(MyBean.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(MyBean.class)); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java index 54819bab47c..13f498301e8 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/ChangedFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,12 +20,12 @@ import java.io.File; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ChangedFile}. @@ -34,31 +34,28 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ChangedFileTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void sourceFolderMustNotBeNull() throws Exception { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("SourceFolder must not be null"); - new ChangedFile(null, this.temp.newFile(), Type.ADD); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ChangedFile(null, this.temp.newFile(), Type.ADD)) + .withMessageContaining("SourceFolder must not be null"); } @Test public void fileMustNotBeNull() throws Exception { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("File must not be null"); - new ChangedFile(this.temp.newFolder(), null, Type.ADD); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ChangedFile(this.temp.newFolder(), null, Type.ADD)) + .withMessageContaining("File must not be null"); } @Test public void typeMustNotBeNull() throws Exception { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must not be null"); - new ChangedFile(this.temp.newFile(), this.temp.newFolder(), null); + assertThatIllegalArgumentException().isThrownBy( + () -> new ChangedFile(this.temp.newFile(), this.temp.newFolder(), null)) + .withMessageContaining("Type must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java index 6ead7a99076..01bc5fe4af8 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSnapshotTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,12 +23,12 @@ import java.util.concurrent.TimeUnit; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link FileSnapshot}. @@ -42,24 +42,20 @@ public class FileSnapshotTests { private static final long MODIFIED = new Date().getTime() - TimeUnit.DAYS.toMillis(10); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test public void fileMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("File must not be null"); - new FileSnapshot(null); + assertThatIllegalArgumentException().isThrownBy(() -> new FileSnapshot(null)) + .withMessageContaining("File must not be null"); } @Test public void fileMustNotBeAFolder() throws Exception { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("File must not be a folder"); - new FileSnapshot(this.temporaryFolder.newFolder()); + assertThatIllegalArgumentException() + .isThrownBy(() -> new FileSnapshot(this.temporaryFolder.newFolder())) + .withMessageContaining("File must not be a folder"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java index abaf6d742fd..e42fce7c327 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FileSystemWatcherTests.java @@ -30,13 +30,14 @@ import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.Mockito.mock; /** @@ -46,9 +47,6 @@ import static org.mockito.Mockito.mock; */ public class FileSystemWatcherTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private FileSystemWatcher watcher; private List> changes = Collections @@ -64,62 +62,66 @@ public class FileSystemWatcherTests { @Test public void pollIntervalMustBePositive() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("PollInterval must be positive"); - new FileSystemWatcher(true, Duration.ofMillis(0), Duration.ofMillis(1)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(0), + Duration.ofMillis(1))) + .withMessageContaining("PollInterval must be positive"); } @Test public void quietPeriodMustBePositive() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("QuietPeriod must be positive"); - new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(0)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), + Duration.ofMillis(0))) + .withMessageContaining("QuietPeriod must be positive"); } @Test public void pollIntervalMustBeGreaterThanQuietPeriod() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("PollInterval must be greater than QuietPeriod"); - new FileSystemWatcher(true, Duration.ofMillis(1), Duration.ofMillis(1)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new FileSystemWatcher(true, Duration.ofMillis(1), + Duration.ofMillis(1))) + .withMessageContaining("PollInterval must be greater than QuietPeriod"); } @Test public void listenerMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("FileChangeListener must not be null"); - this.watcher.addListener(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.watcher.addListener(null)) + .withMessageContaining("FileChangeListener must not be null"); } @Test public void cannotAddListenerToStartedListener() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("FileSystemWatcher already started"); this.watcher.start(); - this.watcher.addListener(mock(FileChangeListener.class)); + assertThatIllegalStateException() + .isThrownBy( + () -> this.watcher.addListener(mock(FileChangeListener.class))) + .withMessageContaining("FileSystemWatcher already started"); } @Test public void sourceFolderMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Folder must not be null"); - this.watcher.addSourceFolder(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.watcher.addSourceFolder(null)) + .withMessageContaining("Folder must not be null"); } @Test public void sourceFolderMustNotBeAFile() { File folder = new File("pom.xml"); assertThat(folder.isFile()).isTrue(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Folder 'pom.xml' must not be a file"); - this.watcher.addSourceFolder(new File("pom.xml")); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.watcher.addSourceFolder(new File("pom.xml"))) + .withMessageContaining("Folder 'pom.xml' must not be a file"); } @Test public void cannotAddSourceFolderToStartedListener() throws Exception { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("FileSystemWatcher already started"); this.watcher.start(); - this.watcher.addSourceFolder(this.temp.newFolder()); + assertThatIllegalStateException() + .isThrownBy(() -> this.watcher.addSourceFolder(this.temp.newFolder())) + .withMessageContaining("FileSystemWatcher already started"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java index 269c7a153ed..adf7894d62d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/filewatch/FolderSnapshotTests.java @@ -22,13 +22,13 @@ import java.io.IOException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.devtools.filewatch.ChangedFile.Type; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link FolderSnapshot}. @@ -37,9 +37,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class FolderSnapshotTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -55,17 +52,15 @@ public class FolderSnapshotTests { @Test public void folderMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Folder must not be null"); - new FolderSnapshot(null); + assertThatIllegalArgumentException().isThrownBy(() -> new FolderSnapshot(null)) + .withMessageContaining("Folder must not be null"); } @Test public void folderMustNotBeFile() throws Exception { File file = this.temporaryFolder.newFile(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Folder '" + file + "' must not be a file"); - new FolderSnapshot(file); + assertThatIllegalArgumentException().isThrownBy(() -> new FolderSnapshot(file)) + .withMessageContaining("Folder '" + file + "' must not be a file"); } @Test @@ -106,17 +101,18 @@ public class FolderSnapshotTests { @Test public void getChangedFilesSnapshotMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Snapshot must not be null"); - this.initialSnapshot.getChangedFiles(null, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.initialSnapshot.getChangedFiles(null, null)) + .withMessageContaining("Snapshot must not be null"); } @Test public void getChangedFilesSnapshotMustBeTheSameSourceFolder() throws Exception { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Snapshot source folder must be '" + this.folder + "'"); - this.initialSnapshot - .getChangedFiles(new FolderSnapshot(createTestFolderStructure()), null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.initialSnapshot.getChangedFiles( + new FolderSnapshot(createTestFolderStructure()), null)) + .withMessageContaining( + "Snapshot source folder must be '" + this.folder + "'"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java index 3d07bcbf9b8..59bd5e41f0d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/ConnectionInputStreamTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,11 +21,10 @@ import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIOException; /** * Tests for {@link ConnectionInputStream}. @@ -37,9 +36,6 @@ public class ConnectionInputStreamTests { private static final byte[] NO_BYTES = {}; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void readHeader() throws Exception { String header = ""; @@ -68,19 +64,18 @@ public class ConnectionInputStreamTests { public void checkedRead() throws Exception { ConnectionInputStream inputStream = new ConnectionInputStream( new ByteArrayInputStream(NO_BYTES)); - this.thrown.expect(IOException.class); - this.thrown.expectMessage("End of stream"); - inputStream.checkedRead(); + assertThatIOException().isThrownBy(inputStream::checkedRead) + .withMessageContaining("End of stream"); } @Test public void checkedReadArray() throws Exception { + byte[] buffer = new byte[100]; ConnectionInputStream inputStream = new ConnectionInputStream( new ByteArrayInputStream(NO_BYTES)); - this.thrown.expect(IOException.class); - this.thrown.expectMessage("End of stream"); - byte[] buffer = new byte[100]; - inputStream.checkedRead(buffer, 0, buffer.length); + assertThatIOException() + .isThrownBy(() -> inputStream.checkedRead(buffer, 0, buffer.length)) + .withMessageContaining("End of stream"); } private static class LimitedInputStream extends FilterInputStream { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java index fe641714514..021e58c0d8d 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/livereload/FrameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,11 +20,11 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Arrays; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link Frame}. @@ -33,21 +33,17 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class FrameTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void payloadMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Payload must not be null"); - new Frame((String) null); + assertThatIllegalArgumentException().isThrownBy(() -> new Frame((String) null)) + .withMessageContaining("Payload must not be null"); } @Test public void typeMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must not be null"); - new Frame((Frame.Type) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new Frame((Frame.Type) null)) + .withMessageContaining("Type must not be null"); } @Test @@ -92,17 +88,17 @@ public class FrameTests { @Test public void readFragmentedNotSupported() throws Exception { byte[] bytes = new byte[] { 0x0F }; - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Fragmented frames are not supported"); - Frame.read(newConnectionInputStream(bytes)); + assertThatIllegalStateException() + .isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) + .withMessageContaining("Fragmented frames are not supported"); } @Test public void readLargeFramesNotSupported() throws Exception { byte[] bytes = new byte[] { (byte) 0x80, (byte) 0xFF }; - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Large frames are not supported"); - Frame.read(newConnectionInputStream(bytes)); + assertThatIllegalStateException() + .isThrownBy(() -> Frame.read(newConnectionInputStream(bytes))) + .withMessageContaining("Large frames are not supported"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java index de9de9d1edd..05fed152147 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/ClassPathChangeUploaderTests.java @@ -29,7 +29,6 @@ import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.devtools.classpath.ClassPathChangedEvent; @@ -46,6 +45,7 @@ import org.springframework.mock.http.client.MockClientHttpRequest; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ClassPathChangeUploader}. @@ -55,9 +55,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ClassPathChangeUploaderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -74,30 +71,32 @@ public class ClassPathChangeUploaderTests { @Test public void urlMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("URL must not be empty"); - new ClassPathChangeUploader(null, this.requestFactory); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassPathChangeUploader(null, this.requestFactory)) + .withMessageContaining("URL must not be empty"); } @Test public void urlMustNotBeEmpty() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("URL must not be empty"); - new ClassPathChangeUploader("", this.requestFactory); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassPathChangeUploader("", this.requestFactory)) + .withMessageContaining("URL must not be empty"); } @Test public void requestFactoryMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RequestFactory must not be null"); - new ClassPathChangeUploader("http://localhost:8080", null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new ClassPathChangeUploader("http://localhost:8080", null)) + .withMessageContaining("RequestFactory must not be null"); } @Test public void urlMustNotBeMalformed() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Malformed URL 'htttttp:///ttest'"); - new ClassPathChangeUploader("htttttp:///ttest", this.requestFactory); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassPathChangeUploader("htttttp:///ttest", + this.requestFactory)) + .withMessageContaining("Malformed URL 'htttttp:///ttest'"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java index b92c3decfe8..eb8c2c4bf7e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/DelayedLiveReloadTriggerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,9 +20,7 @@ import java.io.IOException; import java.net.URI; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -34,6 +32,7 @@ import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -47,9 +46,6 @@ public class DelayedLiveReloadTriggerTests { private static final String URL = "http://localhost:8080"; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private OptionalLiveReloadServer liveReloadServer; @@ -84,30 +80,32 @@ public class DelayedLiveReloadTriggerTests { @Test public void liveReloadServerMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("LiveReloadServer must not be null"); - new DelayedLiveReloadTrigger(null, this.requestFactory, URL); + assertThatIllegalArgumentException().isThrownBy( + () -> new DelayedLiveReloadTrigger(null, this.requestFactory, URL)) + .withMessageContaining("LiveReloadServer must not be null"); } @Test public void requestFactoryMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RequestFactory must not be null"); - new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL); + assertThatIllegalArgumentException().isThrownBy( + () -> new DelayedLiveReloadTrigger(this.liveReloadServer, null, URL)) + .withMessageContaining("RequestFactory must not be null"); } @Test public void urlMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("URL must not be empty"); - new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, + this.requestFactory, null)) + .withMessageContaining("URL must not be empty"); } @Test public void urlMustNotBeEmpty() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("URL must not be empty"); - new DelayedLiveReloadTrigger(this.liveReloadServer, this.requestFactory, ""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelayedLiveReloadTrigger(this.liveReloadServer, + this.requestFactory, "")) + .withMessageContaining("URL must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java index a84716eb1df..8ab7b71e137 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -19,9 +19,7 @@ package org.springframework.boot.devtools.remote.client; import java.io.IOException; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -32,6 +30,7 @@ import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; /** @@ -42,9 +41,6 @@ import static org.mockito.BDDMockito.given; */ public class HttpHeaderInterceptorTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private String name; private String value; @@ -77,30 +73,30 @@ public class HttpHeaderInterceptorTests { @Test public void constructorNullHeaderName() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Name must not be empty"); - new HttpHeaderInterceptor(null, this.value); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpHeaderInterceptor(null, this.value)) + .withMessageContaining("Name must not be empty"); } @Test public void constructorEmptyHeaderName() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Name must not be empty"); - new HttpHeaderInterceptor("", this.value); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpHeaderInterceptor("", this.value)) + .withMessageContaining("Name must not be empty"); } @Test public void constructorNullHeaderValue() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Value must not be empty"); - new HttpHeaderInterceptor(this.name, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpHeaderInterceptor(this.name, null)) + .withMessageContaining("Value must not be empty"); } @Test public void constructorEmptyHeaderValue() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Value must not be empty"); - new HttpHeaderInterceptor(this.name, ""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpHeaderInterceptor(this.name, "")) + .withMessageContaining("Value must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java index 561f8f963e0..e73d597333c 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/client/RemoteClientConfigurationTests.java @@ -24,7 +24,6 @@ import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -49,6 +48,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -67,9 +67,6 @@ public class RemoteClientConfigurationTests { @Rule public OutputCapture output = new OutputCapture(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private AnnotationConfigServletWebServerApplicationContext context; private AnnotationConfigApplicationContext clientContext; @@ -104,9 +101,9 @@ public class RemoteClientConfigurationTests { @Test public void failIfNoSecret() { - this.thrown.expect(BeanCreationException.class); - this.thrown.expectMessage("required to secure your connection"); - configure("http://localhost", false); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> configure("http://localhost", false)) + .withMessageContaining("required to secure your connection"); } @Test @@ -126,15 +123,15 @@ public class RemoteClientConfigurationTests { @Test public void liveReloadDisabled() { configure("spring.devtools.livereload.enabled:false"); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(OptionalLiveReloadServer.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(OptionalLiveReloadServer.class)); } @Test public void remoteRestartDisabled() { configure("spring.devtools.remote.restart.enabled:false"); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(ClassPathFileSystemWatcher.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(ClassPathFileSystemWatcher.class)); } private void configure(String... pairs) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java index 42994733412..0f38d6f5faa 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +23,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -39,6 +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.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.mock; @@ -52,9 +51,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ public class DispatcherFilterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private Dispatcher dispatcher; @@ -77,9 +73,8 @@ public class DispatcherFilterTests { @Test public void dispatcherMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Dispatcher must not be null"); - new DispatcherFilter(null); + assertThatIllegalArgumentException().isThrownBy(() -> new DispatcherFilter(null)) + .withMessageContaining("Dispatcher must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java index 9c1ee5a1bdc..070ca340ddc 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/DispatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +21,7 @@ import java.util.Collections; import java.util.List; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -37,6 +35,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.inOrder; @@ -52,9 +51,6 @@ import static org.mockito.Mockito.withSettings; */ public class DispatcherTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private AccessManager accessManager; @@ -77,16 +73,16 @@ public class DispatcherTests { @Test public void accessManagerMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("AccessManager must not be null"); - new Dispatcher(null, Collections.emptyList()); + assertThatIllegalArgumentException() + .isThrownBy(() -> new Dispatcher(null, Collections.emptyList())) + .withMessageContaining("AccessManager must not be null"); } @Test public void mappersMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Mappers must not be null"); - new Dispatcher(this.accessManager, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new Dispatcher(this.accessManager, null)) + .withMessageContaining("Mappers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java index 84939b40c8e..0eea68e45b1 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpHeaderAccessManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -17,15 +17,14 @@ package org.springframework.boot.devtools.remote.server; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link HttpHeaderAccessManager}. @@ -39,9 +38,6 @@ public class HttpHeaderAccessManagerTests { private static final String SECRET = "password"; - @Rule - public ExpectedException thrown = ExpectedException.none(); - private MockHttpServletRequest request; private ServerHttpRequest serverRequest; @@ -57,30 +53,30 @@ public class HttpHeaderAccessManagerTests { @Test public void headerNameMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("HeaderName must not be empty"); - new HttpHeaderAccessManager(null, SECRET); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpHeaderAccessManager(null, SECRET)) + .withMessageContaining("HeaderName must not be empty"); } @Test public void headerNameMustNotBeEmpty() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("HeaderName must not be empty"); - new HttpHeaderAccessManager("", SECRET); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpHeaderAccessManager("", SECRET)) + .withMessageContaining("HeaderName must not be empty"); } @Test public void expectedSecretMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ExpectedSecret must not be empty"); - new HttpHeaderAccessManager(HEADER, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpHeaderAccessManager(HEADER, null)) + .withMessageContaining("ExpectedSecret must not be empty"); } @Test public void expectedSecretMustNotBeEmpty() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ExpectedSecret must not be empty"); - new HttpHeaderAccessManager(HEADER, ""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpHeaderAccessManager(HEADER, "")) + .withMessageContaining("ExpectedSecret must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java index 39c2ab7a114..6b9d9054185 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/HttpStatusHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -17,9 +17,7 @@ package org.springframework.boot.devtools.remote.server; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.http.HttpStatus; import org.springframework.http.server.ServerHttpRequest; @@ -30,6 +28,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link HttpStatusHandler}. @@ -38,9 +37,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class HttpStatusHandlerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private MockHttpServletRequest servletRequest; private MockHttpServletResponse servletResponse; @@ -59,9 +55,8 @@ public class HttpStatusHandlerTests { @Test public void statusMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Status must not be null"); - new HttpStatusHandler(null); + assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusHandler(null)) + .withMessageContaining("Status must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java index bd30412827c..b4595857daf 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/remote/server/UrlHandlerMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,15 +18,14 @@ package org.springframework.boot.devtools.remote.server; import javax.servlet.http.HttpServletRequest; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -37,30 +36,27 @@ import static org.mockito.Mockito.mock; */ public class UrlHandlerMapperTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private Handler handler = mock(Handler.class); @Test public void requestUriMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("URL must not be empty"); - new UrlHandlerMapper(null, this.handler); + assertThatIllegalArgumentException() + .isThrownBy(() -> new UrlHandlerMapper(null, this.handler)) + .withMessageContaining("URL must not be empty"); } @Test public void requestUriMustNotBeEmpty() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("URL must not be empty"); - new UrlHandlerMapper("", this.handler); + assertThatIllegalArgumentException() + .isThrownBy(() -> new UrlHandlerMapper("", this.handler)) + .withMessageContaining("URL must not be empty"); } @Test public void requestUrlMustStartWithSlash() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("URL must start with '/'"); - new UrlHandlerMapper("tunnel", this.handler); + assertThatIllegalArgumentException() + .isThrownBy(() -> new UrlHandlerMapper("tunnel", this.handler)) + .withMessageContaining("URL must start with '/'"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java index 3c6aea21704..b9ae78b9288 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/MainMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -19,13 +19,13 @@ package org.springframework.boot.devtools.restart; import java.lang.reflect.Method; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link MainMethod}. @@ -34,9 +34,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class MainMethodTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private static ThreadLocal mainMethod = new ThreadLocal<>(); private Method actualMain; @@ -48,9 +45,8 @@ public class MainMethodTests { @Test public void threadMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Thread must not be null"); - new MainMethod(null); + assertThatIllegalArgumentException().isThrownBy(() -> new MainMethod(null)) + .withMessageContaining("Thread must not be null"); } @Test @@ -63,16 +59,16 @@ public class MainMethodTests { @Test public void missingArgsMainMethod() throws Exception { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find main method"); - new TestThread(MissingArgs::main).test(); + assertThatIllegalStateException() + .isThrownBy(() -> new TestThread(MissingArgs::main).test()) + .withMessageContaining("Unable to find main method"); } @Test public void nonStatic() throws Exception { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find main method"); - new TestThread(() -> new NonStaticMain().main()).test(); + assertThatIllegalStateException() + .isThrownBy(() -> new TestThread(() -> new NonStaticMain().main()).test()) + .withMessageContaining("Unable to find main method"); } private static class TestThread extends Thread { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java index 47763ceb84a..a8b9eb518bf 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/RestarterTests.java @@ -26,7 +26,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile; @@ -43,6 +42,8 @@ import org.springframework.util.FileCopyUtils; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -56,9 +57,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ public class RestarterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public OutputCapture out = new OutputCapture(); @@ -75,9 +73,8 @@ public class RestarterTests { @Test public void cantGetInstanceBeforeInitialize() { Restarter.clearInstance(); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Restarter has not been initialized"); - Restarter.getInstance(); + assertThatIllegalStateException().isThrownBy(Restarter::getInstance) + .withMessageContaining("Restarter has not been initialized"); } @Test @@ -103,9 +100,9 @@ public class RestarterTests { @Test public void addUrlsMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Urls must not be null"); - Restarter.getInstance().addUrls(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> Restarter.getInstance().addUrls(null)) + .withMessageContaining("Urls must not be null"); } @Test @@ -122,9 +119,9 @@ public class RestarterTests { @Test public void addClassLoaderFilesMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ClassLoaderFiles must not be null"); - Restarter.getInstance().addClassLoaderFiles(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> Restarter.getInstance().addClassLoaderFiles(null)) + .withMessageContaining("ClassLoaderFiles must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java index 73c70c67968..ce5161d2f46 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,13 +16,12 @@ package org.springframework.boot.devtools.restart.classloader; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ClassLoaderFile}. @@ -33,35 +32,32 @@ public class ClassLoaderFileTests { public static final byte[] BYTES = "ABC".getBytes(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void kindMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Kind must not be null"); - new ClassLoaderFile(null, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassLoaderFile(null, null)) + .withMessageContaining("Kind must not be null"); } @Test public void addedContentsMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Contents must not be null"); - new ClassLoaderFile(Kind.ADDED, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassLoaderFile(Kind.ADDED, null)) + .withMessageContaining("Contents must not be null"); } @Test public void modifiedContentsMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Contents must not be null"); - new ClassLoaderFile(Kind.MODIFIED, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassLoaderFile(Kind.MODIFIED, null)) + .withMessageContaining("Contents must not be null"); } @Test public void deletedContentsMustBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Contents must be null"); - new ClassLoaderFile(Kind.DELETED, new byte[10]); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ClassLoaderFile(Kind.DELETED, new byte[10])) + .withMessageContaining("Contents must be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java index 881a11c3c41..e794f6f4412 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFilesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -22,14 +22,13 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Iterator; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles.SourceFolder; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -39,23 +38,20 @@ import static org.mockito.Mockito.mock; */ public class ClassLoaderFilesTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ClassLoaderFiles files = new ClassLoaderFiles(); @Test public void addFileNameMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Name must not be null"); - this.files.addFile(null, mock(ClassLoaderFile.class)); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.files.addFile(null, mock(ClassLoaderFile.class))) + .withMessageContaining("Name must not be null"); } @Test public void addFileFileMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("File must not be null"); - this.files.addFile("test", null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.files.addFile("test", null)) + .withMessageContaining("File must not be null"); } @Test @@ -161,9 +157,8 @@ public class ClassLoaderFilesTests { @Test public void classLoaderFilesMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ClassLoaderFiles must not be null"); - new ClassLoaderFiles(null); + assertThatIllegalArgumentException().isThrownBy(() -> new ClassLoaderFiles(null)) + .withMessageContaining("ClassLoaderFiles must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java index 8b0241b5c8d..afa9ba94c0f 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/RestartClassLoaderTests.java @@ -32,7 +32,6 @@ import java.util.zip.ZipEntry; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile.Kind; @@ -40,6 +39,8 @@ import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link RestartClassLoader}. @@ -54,9 +55,6 @@ public class RestartClassLoaderTests { private static final String PACKAGE_PATH = PACKAGE.replace('.', '/'); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -95,16 +93,16 @@ public class RestartClassLoaderTests { @Test public void parentMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Parent must not be null"); - new RestartClassLoader(null, new URL[] {}); + assertThatIllegalArgumentException() + .isThrownBy(() -> new RestartClassLoader(null, new URL[] {})) + .withMessageContaining("Parent must not be null"); } @Test public void updatedFilesMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("UpdatedFiles must not be null"); - new RestartClassLoader(this.parentClassLoader, new URL[] {}, null); + assertThatIllegalArgumentException().isThrownBy( + () -> new RestartClassLoader(this.parentClassLoader, new URL[] {}, null)) + .withMessageContaining("UpdatedFiles must not be null"); } @Test @@ -185,16 +183,16 @@ public class RestartClassLoaderTests { public void getDeletedClass() throws Exception { String name = PACKAGE_PATH + "/Sample.class"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.DELETED, null)); - this.thrown.expect(ClassNotFoundException.class); - this.reloadClassLoader.loadClass(PACKAGE + ".Sample"); + assertThatExceptionOfType(ClassNotFoundException.class) + .isThrownBy(() -> this.reloadClassLoader.loadClass(PACKAGE + ".Sample")); } @Test public void getUpdatedClass() throws Exception { String name = PACKAGE_PATH + "/Sample.class"; this.updatedFiles.addFile(name, new ClassLoaderFile(Kind.MODIFIED, new byte[10])); - this.thrown.expect(ClassFormatError.class); - this.reloadClassLoader.loadClass(PACKAGE + ".Sample"); + assertThatExceptionOfType(ClassFormatError.class) + .isThrownBy(() -> this.reloadClassLoader.loadClass(PACKAGE + ".Sample")); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java index 43ec1713246..bbf192f6876 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,13 +16,12 @@ package org.springframework.boot.devtools.restart.server; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -33,14 +32,11 @@ import static org.mockito.Mockito.verify; */ public class HttpRestartServerHandlerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void serverMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Server must not be null"); - new HttpRestartServerHandler(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpRestartServerHandler(null)) + .withMessageContaining("Server must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java index 0ce748f0090..9dd37a92645 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/HttpRestartServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +21,7 @@ import java.io.IOException; import java.io.ObjectOutputStream; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -38,6 +36,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -48,9 +47,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ public class HttpRestartServerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private RestartServer delegate; @@ -67,16 +63,16 @@ public class HttpRestartServerTests { @Test public void sourceFolderUrlFilterMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("SourceFolderUrlFilter must not be null"); - new HttpRestartServer((SourceFolderUrlFilter) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpRestartServer((SourceFolderUrlFilter) null)) + .withMessageContaining("SourceFolderUrlFilter must not be null"); } @Test public void restartServerMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RestartServer must not be null"); - new HttpRestartServer((RestartServer) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpRestartServer((RestartServer) null)) + .withMessageContaining("RestartServer must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java index d6d2704d088..a1f589a2ed5 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/server/RestartServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -26,7 +26,6 @@ import java.util.Set; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.devtools.restart.classloader.ClassLoaderFile; @@ -35,6 +34,7 @@ import org.springframework.boot.devtools.restart.classloader.ClassLoaderFiles; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link RestartServer}. @@ -43,17 +43,14 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class RestartServerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void sourceFolderUrlFilterMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("SourceFolderUrlFilter must not be null"); - new RestartServer((SourceFolderUrlFilter) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new RestartServer((SourceFolderUrlFilter) null)) + .withMessageContaining("SourceFolderUrlFilter must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java index 4aa280bded9..a70edd734b4 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/HttpTunnelConnectionTests.java @@ -28,7 +28,6 @@ import java.util.concurrent.Executor; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -38,6 +37,7 @@ import org.springframework.boot.test.rule.OutputCapture; import org.springframework.http.HttpStatus; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -52,9 +52,6 @@ import static org.mockito.Mockito.verify; */ public class HttpTunnelConnectionTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public OutputCapture outputCapture = new OutputCapture(); @@ -79,30 +76,30 @@ public class HttpTunnelConnectionTests { @Test public void urlMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("URL must not be empty"); - new HttpTunnelConnection(null, this.requestFactory); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpTunnelConnection(null, this.requestFactory)) + .withMessageContaining("URL must not be empty"); } @Test public void urlMustNotBeEmpty() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("URL must not be empty"); - new HttpTunnelConnection("", this.requestFactory); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpTunnelConnection("", this.requestFactory)) + .withMessageContaining("URL must not be empty"); } @Test public void urlMustNotBeMalformed() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Malformed URL 'htttttp:///ttest'"); - new HttpTunnelConnection("htttttp:///ttest", this.requestFactory); + assertThatIllegalArgumentException().isThrownBy( + () -> new HttpTunnelConnection("htttttp:///ttest", this.requestFactory)) + .withMessageContaining("Malformed URL 'htttttp:///ttest'"); } @Test public void requestFactoryMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RequestFactory must not be null"); - new HttpTunnelConnection(this.url, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpTunnelConnection(this.url, null)) + .withMessageContaining("RequestFactory must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java index b9e292d1508..82375915a22 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/client/TunnelClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -25,11 +25,10 @@ import java.nio.channels.Channels; import java.nio.channels.SocketChannel; import java.nio.channels.WritableByteChannel; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -41,23 +40,19 @@ import static org.mockito.Mockito.verify; */ public class TunnelClientTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private MockTunnelConnection tunnelConnection = new MockTunnelConnection(); @Test public void listenPortMustNotBeNegative() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ListenPort must be greater than or equal to 0"); - new TunnelClient(-5, this.tunnelConnection); + assertThatIllegalArgumentException() + .isThrownBy(() -> new TunnelClient(-5, this.tunnelConnection)) + .withMessageContaining("ListenPort must be greater than or equal to 0"); } @Test public void tunnelConnectionMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TunnelConnection must not be null"); - new TunnelClient(1, null); + assertThatIllegalArgumentException().isThrownBy(() -> new TunnelClient(1, null)) + .withMessageContaining("TunnelConnection must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java index 9f43bca767f..4095261c5cb 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadForwarderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,11 +21,11 @@ import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link HttpTunnelPayloadForwarder}. @@ -34,14 +34,11 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class HttpTunnelPayloadForwarderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void targetChannelMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TargetChannel must not be null"); - new HttpTunnelPayloadForwarder(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpTunnelPayloadForwarder(null)) + .withMessageContaining("TargetChannel must not be null"); } @Test @@ -70,11 +67,11 @@ public class HttpTunnelPayloadForwarderTests { public void overflow() throws Exception { WritableByteChannel channel = Channels.newChannel(new ByteArrayOutputStream()); HttpTunnelPayloadForwarder forwarder = new HttpTunnelPayloadForwarder(channel); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Too many messages queued"); - for (int i = 2; i < 130; i++) { - forwarder.forward(payload(i, "data" + i)); - } + assertThatIllegalStateException().isThrownBy(() -> { + for (int i = 2; i < 130; i++) { + forwarder.forward(payload(i, "data" + i)); + } + }).withMessageContaining("Too many messages queued"); } private HttpTunnelPayload payload(long sequence, String data) { diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java index 26823629f9d..903907d9709 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/payload/HttpTunnelPayloadTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -25,9 +25,7 @@ import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; @@ -37,6 +35,8 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -48,21 +48,18 @@ import static org.mockito.Mockito.mock; */ public class HttpTunnelPayloadTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void sequenceMustBePositive() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Sequence must be positive"); - new HttpTunnelPayload(0, ByteBuffer.allocate(1)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpTunnelPayload(0, ByteBuffer.allocate(1))) + .withMessageContaining("Sequence must be positive"); } @Test public void dataMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Data must not be null"); - new HttpTunnelPayload(1, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpTunnelPayload(1, null)) + .withMessageContaining("Data must not be null"); } @Test @@ -102,9 +99,8 @@ public class HttpTunnelPayloadTests { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.setContent("hello".getBytes()); HttpInputMessage request = new ServletServerHttpRequest(servletRequest); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Missing sequence header"); - HttpTunnelPayload.get(request); + assertThatIllegalStateException().isThrownBy(() -> HttpTunnelPayload.get(request)) + .withMessageContaining("Missing sequence header"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java index 00023fe5ba1..66ce283fac2 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,13 +16,12 @@ package org.springframework.boot.devtools.tunnel.server; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -33,14 +32,11 @@ import static org.mockito.Mockito.verify; */ public class HttpTunnelServerHandlerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void serverMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Server must not be null"); - new HttpTunnelServerHandler(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new HttpTunnelServerHandler(null)) + .withMessageContaining("Server must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java index cb469e3c92f..91ce4e96e13 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/HttpTunnelServerTests.java @@ -28,9 +28,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -46,6 +44,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -66,9 +65,6 @@ public class HttpTunnelServerTests { private static final String SEQ_HEADER = "x-seq"; - @Rule - public ExpectedException thrown = ExpectedException.none(); - private HttpTunnelServer server; @Mock @@ -103,9 +99,8 @@ public class HttpTunnelServerTests { @Test public void serverConnectionIsRequired() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ServerConnection must not be null"); - new HttpTunnelServer(null); + assertThatIllegalArgumentException().isThrownBy(() -> new HttpTunnelServer(null)) + .withMessageContaining("ServerConnection must not be null"); } @Test @@ -124,9 +119,9 @@ public class HttpTunnelServerTests { @Test public void longPollTimeoutMustBePositiveValue() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("LongPollTimeout must be a positive value"); - this.server.setLongPollTimeout(0); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.server.setLongPollTimeout(0)) + .withMessageContaining("LongPollTimeout must be a positive value"); } @Test @@ -257,9 +252,9 @@ public class HttpTunnelServerTests { @Test public void disconnectTimeoutMustBePositive() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("DisconnectTimeout must be a positive value"); - this.server.setDisconnectTimeout(0); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.server.setDisconnectTimeout(0)) + .withMessageContaining("DisconnectTimeout must be a positive value"); } @Test diff --git a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java index bdf4bb146c7..023e640d58e 100644 --- a/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java +++ b/spring-boot-project/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/tunnel/server/StaticPortProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,11 +16,10 @@ package org.springframework.boot.devtools.tunnel.server; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link StaticPortProvider}. @@ -29,14 +28,10 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class StaticPortProviderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void portMustBePositive() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Port must be positive"); - new StaticPortProvider(0); + assertThatIllegalArgumentException().isThrownBy(() -> new StaticPortProvider(0)) + .withMessageContaining("Port must be positive"); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java index 79e977fa181..26153d32960 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/SpringBootDependencyInjectionTestExecutionListenerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,7 +18,6 @@ package org.springframework.boot.test.autoconfigure; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -32,7 +31,7 @@ import org.springframework.test.context.TestContext; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.hamcrest.Matchers.containsString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -47,9 +46,6 @@ public class SpringBootDependencyInjectionTestExecutionListenerTests { @Rule public OutputCapture out = new OutputCapture(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private SpringBootDependencyInjectionTestExecutionListener reportListener = new SpringBootDependencyInjectionTestExecutionListener(); @Test @@ -86,8 +82,9 @@ public class SpringBootDependencyInjectionTestExecutionListenerTests { SpringApplication application = new SpringApplication(Config.class); application.setWebApplicationType(WebApplicationType.NONE); given(testContext.getApplicationContext()).willThrow(new RuntimeException()); - this.thrown.expect(is(originalFailure)); - this.reportListener.prepareTestInstance(testContext); + assertThatIllegalStateException() + .isThrownBy(() -> this.reportListener.prepareTestInstance(testContext)) + .isEqualTo(originalFailure); } @Configuration diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java index 6ecdbff031c..96b5c05991d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/jdbc/DataJdbcTestIntegrationTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.test.autoconfigure.data.jdbc; import javax.sql.DataSource; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -33,6 +31,7 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.boot.test.autoconfigure.AutoConfigurationImportedCondition.importedAutoConfiguration; /** @@ -45,9 +44,6 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor @TestPropertySource(properties = "spring.datasource.schema=classpath:org/springframework/boot/test/autoconfigure/data/jdbc/schema.sql") public class DataJdbcTestIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private ExampleRepository repository; @@ -78,8 +74,8 @@ public class DataJdbcTestIntegrationTests { @Test public void didNotInjectExampleComponent() { - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.applicationContext.getBean(ExampleComponent.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( + () -> this.applicationContext.getBean(ExampleComponent.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java index 458525bf6fa..785c44be59e 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/ldap/DataLdapTestIntegrationTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.test.autoconfigure.data.ldap; import java.util.Optional; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -34,6 +32,7 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Sample test for {@link DataLdapTest @DataLdapTest} @@ -46,9 +45,6 @@ import static org.assertj.core.api.Assertions.assertThat; "spring.ldap.embedded.ldif=classpath:org/springframework/boot/test/autoconfigure/data/ldap/schema.ldif" }) public class DataLdapTestIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private LdapTemplate ldapTemplate; @@ -72,8 +68,8 @@ public class DataLdapTestIntegrationTests { @Test public void didNotInjectExampleService() { - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.applicationContext.getBean(ExampleService.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java index 3a3d12aadaf..6c395b4015e 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/mongo/DataMongoTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package org.springframework.boot.test.autoconfigure.data.mongo; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -28,6 +26,7 @@ import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Sample test for {@link DataMongoTest @DataMongoTest} @@ -38,9 +37,6 @@ import static org.assertj.core.api.Assertions.assertThat; @DataMongoTest public class DataMongoTestIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private MongoTemplate mongoTemplate; @@ -61,8 +57,8 @@ public class DataMongoTestIntegrationTests { @Test public void didNotInjectExampleService() { - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.applicationContext.getBean(ExampleService.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java index 8a82bcbb473..6dcd6f589c4 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/neo4j/DataNeo4jTestIntegrationTests.java @@ -17,9 +17,7 @@ package org.springframework.boot.test.autoconfigure.data.neo4j; import org.junit.ClassRule; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.neo4j.ogm.session.Session; @@ -34,6 +32,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration test for {@link DataNeo4jTest}. @@ -49,9 +48,6 @@ public class DataNeo4jTestIntegrationTests { @ClassRule public static Neo4jContainer neo4j = new Neo4jContainer(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private Session session; @@ -73,8 +69,8 @@ public class DataNeo4jTestIntegrationTests { @Test public void didNotInjectExampleService() { - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.applicationContext.getBean(ExampleService.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } static class Initializer diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java index b1795389db1..8bb6c26d278 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/data/redis/DataRedisTestIntegrationTests.java @@ -20,9 +20,7 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import org.junit.ClassRule; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -38,6 +36,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration test for {@link DataRedisTest}. @@ -52,9 +51,6 @@ public class DataRedisTestIntegrationTests { @ClassRule public static RedisContainer redis = new RedisContainer(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private RedisOperations operations; @@ -80,8 +76,8 @@ public class DataRedisTestIntegrationTests { @Test public void didNotInjectExampleService() { - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.applicationContext.getBean(ExampleService.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.applicationContext.getBean(ExampleService.class)); } static class Initializer diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java index 105ea806135..9e6d5631282 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jdbc/JdbcTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,9 +20,7 @@ import java.util.Collection; import javax.sql.DataSource; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -35,6 +33,7 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.boot.test.autoconfigure.AutoConfigurationImportedCondition.importedAutoConfiguration; /** @@ -47,9 +46,6 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor @TestPropertySource(properties = "spring.datasource.schema=classpath:org/springframework/boot/test/autoconfigure/jdbc/schema.sql") public class JdbcTestIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private JdbcTemplate jdbcTemplate; @@ -79,8 +75,8 @@ public class JdbcTestIntegrationTests { @Test public void didNotInjectExampleRepository() { - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.applicationContext.getBean(ExampleRepository.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( + () -> this.applicationContext.getBean(ExampleRepository.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java index a608cfd4731..75bd86fc008 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/jooq/JooqTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,9 +20,7 @@ import javax.sql.DataSource; import org.jooq.DSLContext; import org.jooq.SQLDialect; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -34,6 +32,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.boot.test.autoconfigure.AutoConfigurationImportedCondition.importedAutoConfiguration; /** @@ -45,9 +44,6 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor @JooqTest public class JooqTestIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private DSLContext dsl; @@ -73,8 +69,8 @@ public class JooqTestIntegrationTests { @Test public void didNotInjectExampleComponent() { - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.applicationContext.getBean(ExampleComponent.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( + () -> this.applicationContext.getBean(ExampleComponent.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java index 63a686304a3..22437307eaf 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTestIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,9 +18,7 @@ package org.springframework.boot.test.autoconfigure.orm.jpa; import javax.sql.DataSource; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -33,6 +31,7 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.boot.test.autoconfigure.AutoConfigurationImportedCondition.importedAutoConfiguration; /** @@ -46,9 +45,6 @@ import static org.springframework.boot.test.autoconfigure.AutoConfigurationImpor @TestPropertySource(properties = "spring.jpa.hibernate.use-new-id-generator-mappings=false") public class DataJpaTestIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private TestEntityManager entities; @@ -102,8 +98,8 @@ public class DataJpaTestIntegrationTests { @Test public void didNotInjectExampleComponent() { - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.applicationContext.getBean(ExampleComponent.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( + () -> this.applicationContext.getBean(ExampleComponent.class)); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java index a24ed8f72b1..8abec283b8d 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/orm/jpa/TestEntityManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +21,7 @@ import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnitUtil; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -31,6 +29,8 @@ import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @@ -41,9 +41,6 @@ import static org.mockito.Mockito.verify; */ public class TestEntityManagerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private EntityManagerFactory entityManagerFactory; @@ -65,9 +62,8 @@ public class TestEntityManagerTests { @Test public void createWhenEntityManagerIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("EntityManagerFactory must not be null"); - new TestEntityManager(null); + assertThatIllegalArgumentException().isThrownBy(() -> new TestEntityManager(null)) + .withMessageContaining("EntityManagerFactory must not be null"); } @Test @@ -191,9 +187,10 @@ public class TestEntityManagerTests { public void getIdForTypeWhenTypeIsWrongShouldThrowException() { TestEntity entity = new TestEntity(); given(this.persistenceUnitUtil.getIdentifier(entity)).willReturn(123); - this.thrown.expectMessage("ID mismatch: Object of class [java.lang.Integer] " - + "must be an instance of class java.lang.Long"); - this.testEntityManager.getId(entity, Long.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.testEntityManager.getId(entity, Long.class)) + .withMessageContaining("ID mismatch: Object of class [java.lang.Integer] " + + "must be an instance of class java.lang.Long"); } @Test @@ -213,9 +210,9 @@ public class TestEntityManagerTests { @Test public void getEntityManagerWhenNotSetShouldThrowException() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("No transactional EntityManager found"); - this.testEntityManager.getEntityManager(); + assertThatIllegalStateException() + .isThrownBy(this.testEntityManager::getEntityManager) + .withMessageContaining("No transactional EntityManager found"); } private void bindEntityManager() { diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java index ce9152e88c4..e4f999ca534 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/override/OverrideAutoConfigurationEnabledFalseIntegrationTests.java @@ -16,9 +16,7 @@ package org.springframework.boot.test.autoconfigure.override; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -33,6 +31,7 @@ import org.springframework.test.context.BootstrapWith; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration tests for {@link OverrideAutoConfiguration} when {@code enabled} is @@ -46,9 +45,6 @@ import static org.assertj.core.api.Assertions.assertThat; @ImportAutoConfiguration(ExampleTestConfig.class) public class OverrideAutoConfigurationEnabledFalseIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private ApplicationContext context; @@ -56,8 +52,8 @@ public class OverrideAutoConfigurationEnabledFalseIntegrationTests { public void disabledAutoConfiguration() { ApplicationContext context = this.context; assertThat(context.getBean(ExampleTestConfig.class)).isNotNull(); - this.thrown.expect(NoSuchBeanDefinitionException.class); - context.getBean(ConfigurationPropertiesBindingPostProcessor.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy( + () -> context.getBean(ConfigurationPropertiesBindingPostProcessor.class)); } } diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java index b7d7db3c156..77dcad3c14e 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/AnnotationsPropertySourceTests.java @@ -19,13 +19,12 @@ package org.springframework.boot.test.autoconfigure.properties; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.annotation.AliasFor; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link AnnotationsPropertySource}. @@ -35,14 +34,11 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class AnnotationsPropertySourceTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenSourceIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Property source must not be null"); - new AnnotationsPropertySource(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AnnotationsPropertySource(null)) + .withMessageContaining("Property source must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java index 3163747b2f6..a8a0db6a4ed 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/properties/PropertyMappingContextCustomizerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -19,9 +19,7 @@ package org.springframework.boot.test.autoconfigure.properties; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; @@ -32,6 +30,7 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.test.context.ContextCustomizer; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; @@ -43,9 +42,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ public class PropertyMappingContextCustomizerFactoryTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private PropertyMappingContextCustomizerFactory factory = new PropertyMappingContextCustomizerFactory(); @Test @@ -106,11 +102,11 @@ public class PropertyMappingContextCustomizerFactoryTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(ConfigMapping.class); customizer.customizeContext(context, null); - this.thrown.expect(BeanCreationException.class); - this.thrown.expectMessage("The @PropertyMapping annotation " - + "@PropertyMappingContextCustomizerFactoryTests.TypeMappingAnnotation " - + "cannot be used in combination with the @Component annotation @Configuration"); - context.refresh(); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(context::refresh) + .withMessageContaining("The @PropertyMapping annotation " + + "@PropertyMappingContextCustomizerFactoryTests.TypeMappingAnnotation " + + "cannot be used in combination with the @Component annotation @Configuration"); } @NoMappingAnnotation diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java index 6fa8e10c2ec..5822af0d6e1 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/client/RestClientTestTwoComponentsIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package org.springframework.boot.test.autoconfigure.web.client; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -28,6 +26,7 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; @@ -40,9 +39,6 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat @RestClientTest({ ExampleRestClient.class, AnotherExampleRestClient.class }) public class RestClientTestTwoComponentsIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private ExampleRestClient client1; @@ -57,10 +53,10 @@ public class RestClientTestTwoComponentsIntegrationTests { @Test public void serverShouldNotWork() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to use auto-configured"); - this.server.expect(requestTo("/test")) - .andRespond(withSuccess("hello", MediaType.TEXT_HTML)); + assertThatIllegalStateException() + .isThrownBy(() -> this.server.expect(requestTo("/test")) + .andRespond(withSuccess("hello", MediaType.TEXT_HTML))) + .withMessageContaining("Unable to use auto-configured"); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java index 24b1256eea5..b2b9da55ac2 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestAllControllersIntegrationTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; import javax.validation.ConstraintViolationException; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -29,9 +27,10 @@ import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.util.NestedServletException; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.isA; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -47,9 +46,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @WithMockUser public class WebMvcTestAllControllersIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private MockMvc mvc; @@ -82,8 +78,9 @@ public class WebMvcTestAllControllersIntegrationTests { @Test public void shouldRunValidationFailure() throws Exception { - this.thrown.expectCause(isA(ConstraintViolationException.class)); - this.mvc.perform(get("/three/invalid")); + assertThatExceptionOfType(NestedServletException.class) + .isThrownBy(() -> this.mvc.perform(get("/three/invalid"))) + .withCauseInstanceOf(ConstraintViolationException.class); } @Test diff --git a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java index 667cf7861e7..27bab31dcdc 100644 --- a/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java +++ b/spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/web/servlet/mockmvc/WebMvcTestWithAutoConfigureMockMvcIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -17,9 +17,7 @@ package org.springframework.boot.test.autoconfigure.web.servlet.mockmvc; import com.gargoylesoftware.htmlunit.WebClient; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; @@ -31,6 +29,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; @@ -45,9 +44,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @AutoConfigureMockMvc(addFilters = false, webClientEnabled = false, webDriverEnabled = false) public class WebMvcTestWithAutoConfigureMockMvcIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private ApplicationContext context; @@ -61,14 +57,14 @@ public class WebMvcTestWithAutoConfigureMockMvcIntegrationTests { @Test public void shouldNotHaveWebDriver() { - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(WebDriver.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(WebDriver.class)); } @Test public void shouldNotHaveWebClient() { - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(WebClient.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(WebClient.class)); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java index 2e8c0060080..48989d3713b 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotatedClassFinderTests.java @@ -16,15 +16,14 @@ package org.springframework.boot.test.context; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.example.ExampleConfig; import org.springframework.boot.test.context.example.scan.Example; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link AnnotatedClassFinder}. @@ -33,24 +32,21 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class AnnotatedClassFinderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private AnnotatedClassFinder finder = new AnnotatedClassFinder( SpringBootConfiguration.class); @Test public void findFromClassWhenSourceIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Source must not be null"); - this.finder.findFromClass((Class) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.finder.findFromClass((Class) null)) + .withMessageContaining("Source must not be null"); } @Test public void findFromPackageWhenSourceIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Source must not be null"); - this.finder.findFromPackage((String) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.finder.findFromPackage((String) null)) + .withMessageContaining("Source must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java index 027bc858814..1422f1e3a40 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/FilteredClassLoaderTests.java @@ -16,11 +16,10 @@ package org.springframework.boot.test.context; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link FilteredClassLoader}. @@ -29,25 +28,22 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class FilteredClassLoaderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void loadClassWhenFilteredOnPackageShouldThrowClassNotFound() throws Exception { - FilteredClassLoader classLoader = new FilteredClassLoader( - FilteredClassLoaderTests.class.getPackage().getName()); - this.thrown.expect(ClassNotFoundException.class); - classLoader.loadClass(getClass().getName()); - classLoader.close(); + try (FilteredClassLoader classLoader = new FilteredClassLoader( + FilteredClassLoaderTests.class.getPackage().getName())) { + assertThatExceptionOfType(ClassNotFoundException.class) + .isThrownBy(() -> classLoader.loadClass(getClass().getName())); + } } @Test public void loadClassWhenFilteredOnClassShouldThrowClassNotFound() throws Exception { try (FilteredClassLoader classLoader = new FilteredClassLoader( FilteredClassLoaderTests.class)) { - this.thrown.expect(ClassNotFoundException.class); - classLoader.loadClass(getClass().getName()); + assertThatExceptionOfType(ClassNotFoundException.class) + .isThrownBy(() -> classLoader.loadClass(getClass().getName())); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java index 2c8cf79c396..9762473a3e8 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/ImportsContextCustomizerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -19,9 +19,7 @@ package org.springframework.boot.test.context; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -31,6 +29,7 @@ import org.springframework.test.context.ContextCustomizer; import org.springframework.test.context.MergedContextConfiguration; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.Mockito.mock; /** @@ -41,9 +40,6 @@ import static org.mockito.Mockito.mock; */ public class ImportsContextCustomizerFactoryTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ImportsContextCustomizerFactory factory = new ImportsContextCustomizerFactory(); @Test @@ -86,9 +82,10 @@ public class ImportsContextCustomizerFactoryTests { @Test public void getContextCustomizerWhenClassHasBeanMethodsShouldThrowException() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Test classes cannot include @Bean methods"); - this.factory.createContextCustomizer(TestWithImportAndBeanMethod.class, null); + assertThatIllegalStateException() + .isThrownBy(() -> this.factory + .createContextCustomizer(TestWithImportAndBeanMethod.class, null)) + .withMessageContaining("Test classes cannot include @Bean methods"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java index 36c140123b6..08377c8a978 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithClassesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package org.springframework.boot.test.context; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -29,6 +27,7 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link SpringBootTest} configured with specific classes. @@ -40,17 +39,14 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = SpringBootTestWithClassesIntegrationTests.Config.class) public class SpringBootTestWithClassesIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private ApplicationContext context; @Test public void injectsOnlyConfig() { assertThat(this.context.getBean(Config.class)).isNotNull(); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(AdditionalConfig.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); } @Configuration diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java index d4f2e0c66d9..56f5f84b5ec 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootTestWithContextConfigurationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package org.springframework.boot.test.context; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -30,6 +28,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link SpringBootTest} configured with {@link ContextConfiguration}. @@ -42,17 +41,14 @@ import static org.assertj.core.api.Assertions.assertThat; @ContextConfiguration(classes = SpringBootTestWithContextConfigurationIntegrationTests.Config.class) public class SpringBootTestWithContextConfigurationIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private ApplicationContext context; @Test public void injectsOnlyConfig() { assertThat(this.context.getBean(Config.class)).isNotNull(); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(AdditionalConfig.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(AdditionalConfig.class)); } @Configuration diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java index 96497e1ed0b..0f35c416d6e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertProviderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -19,9 +19,7 @@ package org.springframework.boot.test.context.assertj; import java.util.function.Supplier; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -30,7 +28,8 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.StaticApplicationContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.equalTo; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.Mockito.verify; /** @@ -41,9 +40,6 @@ import static org.mockito.Mockito.verify; */ public class ApplicationContextAssertProviderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private ConfigurableApplicationContext mockContext; @@ -65,43 +61,45 @@ public class ApplicationContextAssertProviderTests { @Test public void getWhenTypeIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must not be null"); - ApplicationContextAssertProvider.get(null, ApplicationContext.class, - this.mockContextSupplier); + assertThatIllegalArgumentException() + .isThrownBy(() -> ApplicationContextAssertProvider.get(null, + ApplicationContext.class, this.mockContextSupplier)) + .withMessageContaining("Type must not be null"); } @Test public void getWhenTypeIsClassShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must not be null"); - ApplicationContextAssertProvider.get(null, ApplicationContext.class, - this.mockContextSupplier); + assertThatIllegalArgumentException() + .isThrownBy(() -> ApplicationContextAssertProvider.get(null, + ApplicationContext.class, this.mockContextSupplier)) + .withMessageContaining("Type must not be null"); } @Test public void getWhenContextTypeIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must be an interface"); - ApplicationContextAssertProvider.get( - TestAssertProviderApplicationContextClass.class, ApplicationContext.class, - this.mockContextSupplier); + assertThatIllegalArgumentException() + .isThrownBy(() -> ApplicationContextAssertProvider.get( + TestAssertProviderApplicationContextClass.class, + ApplicationContext.class, this.mockContextSupplier)) + .withMessageContaining("Type must be an interface"); } @Test public void getWhenContextTypeIsClassShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ContextType must not be null"); - ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, - null, this.mockContextSupplier); + assertThatIllegalArgumentException() + .isThrownBy(() -> ApplicationContextAssertProvider.get( + TestAssertProviderApplicationContext.class, null, + this.mockContextSupplier)) + .withMessageContaining("ContextType must not be null"); } @Test public void getWhenSupplierIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ContextType must be an interface"); - ApplicationContextAssertProvider.get(TestAssertProviderApplicationContext.class, - StaticApplicationContext.class, this.mockContextSupplier); + assertThatIllegalArgumentException() + .isThrownBy(() -> ApplicationContextAssertProvider.get( + TestAssertProviderApplicationContext.class, + StaticApplicationContext.class, this.mockContextSupplier)) + .withMessageContaining("ContextType must be an interface"); } @Test @@ -118,8 +116,8 @@ public class ApplicationContextAssertProviderTests { ApplicationContextAssertProvider context = get( this.startupFailureSupplier); assertThat((Object) context).isNotNull(); - expectStartupFailure(); - context.getBean("foo"); + assertThatIllegalStateException().isThrownBy(() -> context.getBean("foo")) + .withCause(this.startupFailure).withMessageContaining("failed to start"); } @Test @@ -133,8 +131,9 @@ public class ApplicationContextAssertProviderTests { public void getSourceContextWhenContextFailsShouldThrowException() { ApplicationContextAssertProvider context = get( this.startupFailureSupplier); - expectStartupFailure(); - context.getSourceApplicationContext(); + assertThatIllegalStateException() + .isThrownBy(() -> context.getSourceApplicationContext()) + .withCause(this.startupFailure).withMessageContaining("failed to start"); } @Test @@ -149,8 +148,9 @@ public class ApplicationContextAssertProviderTests { public void getSourceContextOfTypeWhenContextFailsToStartShouldThrowException() { ApplicationContextAssertProvider context = get( this.startupFailureSupplier); - expectStartupFailure(); - context.getSourceApplicationContext(ApplicationContext.class); + assertThatIllegalStateException().isThrownBy( + () -> context.getSourceApplicationContext(ApplicationContext.class)) + .withCause(this.startupFailure).withMessageContaining("failed to start"); } @Test @@ -213,12 +213,6 @@ public class ApplicationContextAssertProviderTests { verify(this.mockContext).close(); } - private void expectStartupFailure() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("failed to start"); - this.thrown.expectCause(equalTo(this.startupFailure)); - } - private ApplicationContextAssertProvider get( Supplier contextSupplier) { return ApplicationContextAssertProvider.get( diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java index 52090456697..b2bd3830ec6 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/assertj/ApplicationContextAssertTests.java @@ -18,15 +18,15 @@ package org.springframework.boot.test.context.assertj; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.test.context.assertj.ApplicationContextAssert.Scope; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.StaticApplicationContext; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ApplicationContextAssert}. @@ -36,9 +36,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ApplicationContextAssertTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private StaticApplicationContext parent; private StaticApplicationContext context; @@ -60,9 +57,9 @@ public class ApplicationContextAssertTests { @Test public void createWhenApplicationContextIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ApplicationContext must not be null"); - new ApplicationContextAssert<>(null, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ApplicationContextAssert<>(null, null)) + .withMessageContaining("ApplicationContext must not be null"); } @Test @@ -84,17 +81,17 @@ public class ApplicationContextAssertTests { @Test public void hasBeanWhenHasNoBeanShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("no such bean"); - assertThat(getAssert(this.context)).hasBean("foo"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).hasBean("foo")) + .withMessageContaining("no such bean"); } @Test public void hasBeanWhenNotStartedShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); - assertThat(getAssert(this.failure)).hasBean("foo"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.failure)).hasBean("foo")) + .withMessageContaining(String.format( + "but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -105,36 +102,36 @@ public class ApplicationContextAssertTests { @Test public void hasSingleBeanWhenHasNoBeansShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("to have a single bean of type"); - assertThat(getAssert(this.context)).hasSingleBean(Foo.class); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + .withMessageContaining("to have a single bean of type"); } @Test public void hasSingleBeanWhenHasMultipleShouldFail() { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("but found:"); - assertThat(getAssert(this.context)).hasSingleBean(Foo.class); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + .withMessageContaining("but found:"); } @Test public void hasSingleBeanWhenFailedToStartShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("to have a single bean of type"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); - assertThat(getAssert(this.failure)).hasSingleBean(Foo.class); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(getAssert(this.failure)).hasSingleBean(Foo.class)) + .withMessageContaining("to have a single bean of type") + .withMessageContaining(String.format( + "but context failed to start:%n java.lang.RuntimeException")); } @Test public void hasSingleBeanWhenInParentShouldFail() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("but found:"); - assertThat(getAssert(this.context)).hasSingleBean(Foo.class); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(getAssert(this.context)).hasSingleBean(Foo.class)) + .withMessageContaining("but found:"); } @Test @@ -151,27 +148,27 @@ public class ApplicationContextAssertTests { @Test public void doesNotHaveBeanOfTypeWhenHasBeanOfTypeShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("but found"); this.context.registerSingleton("foo", Foo.class); - assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) + .withMessageContaining("but found"); } @Test public void doesNotHaveBeanOfTypeWhenFailedToStartShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("not to have any beans of type"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); - assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(getAssert(this.failure)).doesNotHaveBean(Foo.class)) + .withMessageContaining("not to have any beans of type") + .withMessageContaining(String.format( + "but context failed to start:%n java.lang.RuntimeException")); } @Test public void doesNotHaveBeanOfTypeWhenInParentShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("but found"); this.parent.registerSingleton("foo", Foo.class); - assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(getAssert(this.context)).doesNotHaveBean(Foo.class)) + .withMessageContaining("but found"); } @Test @@ -188,18 +185,20 @@ public class ApplicationContextAssertTests { @Test public void doesNotHaveBeanOfNameWhenHasBeanOfTypeShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("but found"); this.context.registerSingleton("foo", Foo.class); - assertThat(getAssert(this.context)).doesNotHaveBean("foo"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy( + () -> assertThat(getAssert(this.context)).doesNotHaveBean("foo")) + .withMessageContaining("but found"); } @Test public void doesNotHaveBeanOfNameWhenFailedToStartShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("not to have any beans of name"); - this.thrown.expectMessage("failed to start"); - assertThat(getAssert(this.failure)).doesNotHaveBean("foo"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy( + () -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) + .withMessageContaining("not to have any beans of name") + .withMessageContaining("failed to start"); } @Test @@ -217,11 +216,12 @@ public class ApplicationContextAssertTests { @Test public void getBeanNamesWhenFailedToStartShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("not to have any beans of name"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); - assertThat(getAssert(this.failure)).doesNotHaveBean("foo"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy( + () -> assertThat(getAssert(this.failure)).doesNotHaveBean("foo")) + .withMessageContaining("not to have any beans of name") + .withMessageContaining(String.format( + "but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -239,18 +239,18 @@ public class ApplicationContextAssertTests { public void getBeanOfTypeWhenHasMultipleBeansShouldFail() { this.context.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("but found"); - assertThat(getAssert(this.context)).getBean(Foo.class); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).getBean(Foo.class)) + .withMessageContaining("but found"); } @Test public void getBeanOfTypeWhenFailedToStartShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("to contain bean of type"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); - assertThat(getAssert(this.failure)).getBean(Foo.class); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean(Foo.class)) + .withMessageContaining("to contain bean of type") + .withMessageContaining(String.format( + "but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -270,9 +270,9 @@ public class ApplicationContextAssertTests { public void getBeanOfTypeWhenHasMultipleBeansIncludingParentShouldFail() { this.parent.registerSingleton("foo", Foo.class); this.context.registerSingleton("bar", Foo.class); - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("but found"); - assertThat(getAssert(this.context)).getBean(Foo.class); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).getBean(Foo.class)) + .withMessageContaining("but found"); } @Test @@ -296,11 +296,11 @@ public class ApplicationContextAssertTests { @Test public void getBeanOfNameWhenFailedToStartShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("to contain a bean of name"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); - assertThat(getAssert(this.failure)).getBean("foo"); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo")) + .withMessageContaining("to contain a bean of name") + .withMessageContaining(String.format( + "but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -317,18 +317,19 @@ public class ApplicationContextAssertTests { @Test public void getBeanOfNameAndTypeWhenHasNoBeanOfNameButDifferentTypeShouldFail() { this.context.registerSingleton("foo", Foo.class); - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("of type"); - assertThat(getAssert(this.context)).getBean("foo", String.class); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(getAssert(this.context)).getBean("foo", String.class)) + .withMessageContaining("of type"); } @Test public void getBeanOfNameAndTypeWhenFailedToStartShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("to contain a bean of name"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); - assertThat(getAssert(this.failure)).getBean("foo", Foo.class); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBean("foo", + Foo.class)) + .withMessageContaining("to contain a bean of name") + .withMessageContaining(String.format( + "but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -346,11 +347,11 @@ public class ApplicationContextAssertTests { @Test public void getBeansWhenFailedToStartShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("to get beans of type"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); - assertThat(getAssert(this.failure)).getBeans(Foo.class); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.failure)).getBeans(Foo.class)) + .withMessageContaining("to get beans of type") + .withMessageContaining(String.format( + "but context failed to start:%n java.lang.RuntimeException")); } @Test @@ -376,9 +377,9 @@ public class ApplicationContextAssertTests { @Test public void getFailureWhenDidNotFailShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("context started"); - assertThat(getAssert(this.context)).getFailure(); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).getFailure()) + .withMessageContaining("context started"); } @Test @@ -388,18 +389,18 @@ public class ApplicationContextAssertTests { @Test public void hasFailedWhenNotFailedShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("to have failed"); - assertThat(getAssert(this.context)).hasFailed(); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.context)).hasFailed()) + .withMessageContaining("to have failed"); } @Test public void hasNotFailedWhenFailedShouldFail() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("to have not failed"); - this.thrown.expectMessage(String - .format("but context failed to start:%n java.lang.RuntimeException")); - assertThat(getAssert(this.failure)).hasNotFailed(); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(getAssert(this.failure)).hasNotFailed()) + .withMessageContaining("to have not failed") + .withMessageContaining(String.format( + "but context failed to start:%n java.lang.RuntimeException")); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java index 34f86b869e3..de43b603cd1 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/bootstrap/SpringBootTestContextBootstrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package org.springframework.boot.test.context.bootstrap; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -27,6 +25,7 @@ import org.springframework.test.context.BootstrapContext; import org.springframework.test.context.CacheAwareContextLoaderDelegate; import org.springframework.test.context.web.WebAppConfiguration; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -37,17 +36,15 @@ import static org.mockito.Mockito.mock; */ public class SpringBootTestContextBootstrapperTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void springBootTestWithANonMockWebEnvironmentAndWebAppConfigurationFailsFast() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("@WebAppConfiguration should only be used with " - + "@SpringBootTest when @SpringBootTest is configured with a mock web " - + "environment. Please remove @WebAppConfiguration or reconfigure " - + "@SpringBootTest."); - buildTestContext(SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class); + assertThatIllegalStateException() + .isThrownBy(() -> buildTestContext( + SpringBootTestNonMockWebEnvironmentAndWebAppConfiguration.class)) + .withMessageContaining("@WebAppConfiguration should only be used with " + + "@SpringBootTest when @SpringBootTest is configured with a mock web " + + "environment. Please remove @WebAppConfiguration or reconfigure " + + "@SpringBootTest."); } @Test 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 0af53a03bb9..3dbe4e9c28c 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 @@ -21,9 +21,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import com.google.gson.Gson; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.context.annotation.UserConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; @@ -39,6 +37,7 @@ 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.assertThatIOException; import static org.junit.Assert.fail; /** @@ -52,9 +51,6 @@ import static org.junit.Assert.fail; */ public abstract class AbstractApplicationContextRunnerTests, C extends ConfigurableApplicationContext, A extends ApplicationContextAssertProvider> { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void runWithInitializerShouldInitialize() { AtomicBoolean called = new AtomicBoolean(); @@ -178,11 +174,9 @@ public abstract class AbstractApplicationContextRunnerTests { - this.thrown.expect(IOException.class); - this.thrown.expectMessage("Expected message"); - throwCheckedException("Expected message"); - }); + get().run((context) -> assertThatIOException() + .isThrownBy(() -> throwCheckedException("Expected message")) + .withMessageContaining("Expected message")); } protected abstract T get(); diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java index 84c2f324ef0..21a8381a35e 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/AbstractJsonMarshalTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -29,7 +29,6 @@ import java.util.Map; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.core.ResolvableType; @@ -39,6 +38,7 @@ import org.springframework.util.FileCopyUtils; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link AbstractJsonMarshalTester}. @@ -58,9 +58,6 @@ public abstract class AbstractJsonMarshalTesterTests { private static final ResolvableType TYPE = ResolvableType .forClass(ExampleObject.class); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -97,16 +94,16 @@ public abstract class AbstractJsonMarshalTesterTests { @Test public void createWhenResourceLoadClassIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ResourceLoadClass must not be null"); - createTester(null, ResolvableType.forClass(ExampleObject.class)); + assertThatIllegalArgumentException().isThrownBy( + () -> createTester(null, ResolvableType.forClass(ExampleObject.class))) + .withMessageContaining("ResourceLoadClass must not be null"); } @Test public void createWhenTypeIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must not be null"); - createTester(getClass(), null); + assertThatIllegalArgumentException() + .isThrownBy(() -> createTester(getClass(), null)) + .withMessageContaining("Type must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java index a34907f748a..b2605913363 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/BasicJsonTesterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -22,7 +22,6 @@ import java.io.InputStream; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.core.io.ByteArrayResource; @@ -30,6 +29,7 @@ import org.springframework.core.io.Resource; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link BasicJsonTester}. @@ -40,9 +40,6 @@ public class BasicJsonTesterTests { private static final String JSON = "{\"spring\":[\"boot\",\"framework\"]}"; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @@ -50,9 +47,8 @@ public class BasicJsonTesterTests { @Test public void createWhenResourceLoadClassIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ResourceLoadClass must not be null"); - new BasicJsonTester(null); + assertThatIllegalArgumentException().isThrownBy(() -> new BasicJsonTester(null)) + .withMessageContaining("ResourceLoadClass must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java index 7ba91fadf74..d783927eb9f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/GsonTesterTests.java @@ -25,6 +25,7 @@ import org.junit.Test; import org.springframework.core.ResolvableType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link GsonTester}. @@ -35,16 +36,16 @@ public class GsonTesterTests extends AbstractJsonMarshalTesterTests { @Test public void initFieldsWhenTestIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TestInstance must not be null"); - GsonTester.initFields(null, new GsonBuilder().create()); + assertThatIllegalArgumentException() + .isThrownBy(() -> GsonTester.initFields(null, new GsonBuilder().create())) + .withMessageContaining("TestInstance must not be null"); } @Test public void initFieldsWhenMarshallerIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Marshaller must not be null"); - GsonTester.initFields(new InitFieldsTestClass(), (Gson) null); + assertThatIllegalArgumentException().isThrownBy( + () -> GsonTester.initFields(new InitFieldsTestClass(), (Gson) null)) + .withMessageContaining("Marshaller must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java index 09e7d1ad9a6..c574dfcbc60 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JacksonTesterTests.java @@ -24,6 +24,7 @@ import org.junit.Test; import org.springframework.core.ResolvableType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link JacksonTester}. @@ -34,16 +35,17 @@ public class JacksonTesterTests extends AbstractJsonMarshalTesterTests { @Test public void initFieldsWhenTestIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TestInstance must not be null"); - JacksonTester.initFields(null, new ObjectMapper()); + assertThatIllegalArgumentException() + .isThrownBy(() -> JacksonTester.initFields(null, new ObjectMapper())) + .withMessageContaining("TestInstance must not be null"); } @Test public void initFieldsWhenMarshallerIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Marshaller must not be null"); - JacksonTester.initFields(new InitFieldsTestClass(), (ObjectMapper) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> JacksonTester.initFields(new InitFieldsTestClass(), + (ObjectMapper) null)) + .withMessageContaining("Marshaller must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java index 66d59c589fa..321424980ee 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentAssertTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -24,7 +24,6 @@ import java.io.InputStream; import org.assertj.core.api.AssertProvider; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.skyscreamer.jsonassert.JSONCompareMode; import org.skyscreamer.jsonassert.comparator.DefaultComparator; @@ -37,6 +36,7 @@ import org.springframework.test.util.JsonPathExpectationsHelper; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.entry; /** @@ -60,9 +60,6 @@ public class JsonContentAssertTests { private static JSONComparator COMPARATOR = new DefaultComparator( JSONCompareMode.LENIENT); - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @@ -840,9 +837,10 @@ public class JsonContentAssertTests { @Test public void hasJsonPathValueForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("No value at JSON path \"" + expression + "\""); - assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy( + () -> assertThat(forJson(SIMPSONS)).hasJsonPathValue(expression)) + .withMessageContaining("No value at JSON path \"" + expression + "\""); } @Test @@ -853,28 +851,28 @@ public class JsonContentAssertTests { @Test public void doesNotHaveJsonPathValueForAnEmptyArray() { String expression = "$.emptyArray"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected no value at JSON path \"" + expression + "\" but found: []"); - assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining("Expected no value at JSON path \"" + expression + + "\" but found: []"); } @Test public void doesNotHaveJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected no value at JSON path \"" + expression + "\" but found: {}"); - assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(TYPES)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining("Expected no value at JSON path \"" + expression + + "\" but found: {}"); } @Test public void doesNotHaveJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected no value at JSON path \"" + expression - + "\" but found: [{\"name\":\"Bart\"}]"); - assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SIMPSONS)).doesNotHaveJsonPathValue(expression)) + .withMessageContaining("Expected no value at JSON path \"" + expression + + "\" but found: [{\"name\":\"Bart\"}]"); } @Test @@ -907,19 +905,19 @@ public class JsonContentAssertTests { @Test public void hasEmptyJsonPathValueForIndefinitePathWithResults() { String expression = "$.familyMembers[?(@.name == 'Bart')]"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression - + "\" but found: [{\"name\":\"Bart\"}]"); - assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(SIMPSONS)).hasEmptyJsonPathValue(expression)) + .withMessageContaining("Expected an empty value at JSON path \"" + + expression + "\" but found: [{\"name\":\"Bart\"}]"); } @Test public void hasEmptyJsonPathValueForWhitespace() { String expression = "$.whitespace"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected an empty value at JSON path \"" + expression - + "\" but found: ' '"); - assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(TYPES)).hasEmptyJsonPathValue(expression)) + .withMessageContaining("Expected an empty value at JSON path \"" + + expression + "\" but found: ' '"); } @Test @@ -956,37 +954,41 @@ public class JsonContentAssertTests { @Test public void doesNotHaveEmptyJsonPathValueForIndefinitePathWithEmptyResults() { String expression = "$.familyMembers[?(@.name == 'Dilbert')]"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: []"); - assertThat(forJson(SIMPSONS)).doesNotHaveEmptyJsonPathValue(expression); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(SIMPSONS)) + .doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + + expression + "\" but found: []"); } @Test public void doesNotHaveEmptyJsonPathValueForAnEmptyString() { String expression = "$.emptyString"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: ''"); - assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)) + .doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + + expression + "\" but found: ''"); } @Test public void doesNotHaveEmptyJsonPathValueForForAnEmptyArray() { String expression = "$.emptyArray"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: []"); - assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)) + .doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + + expression + "\" but found: []"); } @Test public void doesNotHaveEmptyJsonPathValueForAnEmptyMap() { String expression = "$.emptyMap"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a non-empty value at JSON path \"" - + expression + "\" but found: {}"); - assertThat(forJson(TYPES)).doesNotHaveEmptyJsonPathValue(expression); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)) + .doesNotHaveEmptyJsonPathValue(expression)) + .withMessageContaining("Expected a non-empty value at JSON path \"" + + expression + "\" but found: {}"); } @Test @@ -1002,10 +1004,10 @@ public class JsonContentAssertTests { @Test public void hasJsonPathStringValueForNonString() { String expression = "$.bool"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a string at JSON path \"" + expression + "\" but found: true"); - assertThat(forJson(TYPES)).hasJsonPathStringValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(TYPES)).hasJsonPathStringValue(expression)) + .withMessageContaining("Expected a string at JSON path \"" + expression + + "\" but found: true"); } @Test @@ -1016,10 +1018,10 @@ public class JsonContentAssertTests { @Test public void hasJsonPathNumberValueForNonNumber() { String expression = "$.bool"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a number at JSON path \"" + expression + "\" but found: true"); - assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(TYPES)).hasJsonPathNumberValue(expression)) + .withMessageContaining("Expected a number at JSON path \"" + expression + + "\" but found: true"); } @Test @@ -1030,10 +1032,10 @@ public class JsonContentAssertTests { @Test public void hasJsonPathBooleanValueForNonBoolean() { String expression = "$.num"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a boolean at JSON path \"" + expression + "\" but found: 5"); - assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(TYPES)).hasJsonPathBooleanValue(expression)) + .withMessageContaining("Expected a boolean at JSON path \"" + expression + + "\" but found: 5"); } @Test @@ -1049,10 +1051,10 @@ public class JsonContentAssertTests { @Test public void hasJsonPathArrayValueForNonArray() { String expression = "$.str"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); - assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(TYPES)).hasJsonPathArrayValue(expression)) + .withMessageContaining("Expected an array at JSON path \"" + expression + + "\" but found: 'foo'"); } @Test @@ -1068,10 +1070,11 @@ public class JsonContentAssertTests { @Test public void hasJsonPathMapValueForNonMap() { String expression = "$.str"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); - assertThat(forJson(TYPES)).hasJsonPathMapValue(expression); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy( + () -> assertThat(forJson(TYPES)).hasJsonPathMapValue(expression)) + .withMessageContaining("Expected a map at JSON path \"" + expression + + "\" but found: 'foo'"); } @Test @@ -1104,10 +1107,11 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathStringValueForWrongType() { String expression = "$.num"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a string at JSON path \"" + expression + "\" but found: 5"); - assertThat(forJson(TYPES)).extractingJsonPathStringValue(expression); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)) + .extractingJsonPathStringValue(expression)) + .withMessageContaining("Expected a string at JSON path \"" + expression + + "\" but found: 5"); } @Test @@ -1123,10 +1127,11 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathNumberValueForWrongType() { String expression = "$.str"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a number at JSON path \"" + expression + "\" but found: 'foo'"); - assertThat(forJson(TYPES)).extractingJsonPathNumberValue(expression); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)) + .extractingJsonPathNumberValue(expression)) + .withMessageContaining("Expected a number at JSON path \"" + expression + + "\" but found: 'foo'"); } @Test @@ -1142,10 +1147,11 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathBooleanValueForWrongType() { String expression = "$.str"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Expected a boolean at JSON path \"" + expression - + "\" but found: 'foo'"); - assertThat(forJson(TYPES)).extractingJsonPathBooleanValue(expression); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat(forJson(TYPES)) + .extractingJsonPathBooleanValue(expression)) + .withMessageContaining("Expected a boolean at JSON path \"" + expression + + "\" but found: 'foo'"); } @Test @@ -1167,10 +1173,10 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathArrayValueForWrongType() { String expression = "$.str"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected an array at JSON path \"" + expression + "\" but found: 'foo'"); - assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(TYPES)).extractingJsonPathArrayValue(expression)) + .withMessageContaining("Expected an array at JSON path \"" + expression + + "\" but found: 'foo'"); } @Test @@ -1192,10 +1198,10 @@ public class JsonContentAssertTests { @Test public void extractingJsonPathMapValueForWrongType() { String expression = "$.str"; - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "Expected a map at JSON path \"" + expression + "\" but found: 'foo'"); - assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> assertThat(forJson(TYPES)).extractingJsonPathMapValue(expression)) + .withMessageContaining("Expected a map at JSON path \"" + expression + + "\" but found: 'foo'"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java index 2f25c53a44c..99036650f77 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,13 +16,12 @@ package org.springframework.boot.test.json; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.ResolvableType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link JsonContent}. @@ -36,21 +35,18 @@ public class JsonContentTests { private static final ResolvableType TYPE = ResolvableType .forClass(ExampleObject.class); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenResourceLoadClassIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ResourceLoadClass must not be null"); - new JsonContent(null, TYPE, JSON); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JsonContent(null, TYPE, JSON)) + .withMessageContaining("ResourceLoadClass must not be null"); } @Test public void createWhenJsonIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("JSON must not be null"); - new JsonContent(getClass(), TYPE, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JsonContent(getClass(), TYPE, null)) + .withMessageContaining("JSON must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java index 9e2495c9e3b..6975fff5e1f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/JsonbTesterTests.java @@ -26,6 +26,7 @@ import org.junit.Test; import org.springframework.core.ResolvableType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link JsonbTester}. @@ -36,16 +37,16 @@ public class JsonbTesterTests extends AbstractJsonMarshalTesterTests { @Test public void initFieldsWhenTestIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TestInstance must not be null"); - JsonbTester.initFields(null, JsonbBuilder.create()); + assertThatIllegalArgumentException() + .isThrownBy(() -> JsonbTester.initFields(null, JsonbBuilder.create())) + .withMessageContaining("TestInstance must not be null"); } @Test public void initFieldsWhenMarshallerIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Marshaller must not be null"); - JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null); + assertThatIllegalArgumentException().isThrownBy( + () -> JsonbTester.initFields(new InitFieldsTestClass(), (Jsonb) null)) + .withMessageContaining("Marshaller must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java index 551ee502d95..d0b6c3c078d 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/json/ObjectContentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,13 +16,12 @@ package org.springframework.boot.test.json; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.ResolvableType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ObjectContent}. @@ -36,14 +35,11 @@ public class ObjectContentTests { private static final ResolvableType TYPE = ResolvableType .forClass(ExampleObject.class); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenObjectIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Object must not be null"); - new ObjectContent(TYPE, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ObjectContent(TYPE, null)) + .withMessageContaining("Object must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java index b0f96f2f456..235c1550dfc 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.test.mock.mockito; import java.util.ArrayList; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Answers; import org.springframework.beans.factory.annotation.Qualifier; @@ -32,6 +30,7 @@ import org.springframework.boot.test.mock.mockito.example.RealExampleService; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link DefinitionsParser}. @@ -40,9 +39,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class DefinitionsParserTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private DefinitionsParser parser = new DefinitionsParser(); @Test @@ -104,9 +100,9 @@ public class DefinitionsParserTests { @Test public void parseMockBeanMissingClassToMock() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to deduce type to mock"); - this.parser.parse(MockBeanMissingClassToMock.class); + assertThatIllegalStateException() + .isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class)) + .withMessageContaining("Unable to deduce type to mock"); } @Test @@ -121,10 +117,11 @@ public class DefinitionsParserTests { @Test public void parseMockBeanMultipleClassesWithName() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The name attribute can only be used when mocking a single class"); - this.parser.parse(MockBeanMultipleClassesWithName.class); + assertThatIllegalStateException() + .isThrownBy( + () -> this.parser.parse(MockBeanMultipleClassesWithName.class)) + .withMessageContaining( + "The name attribute can only be used when mocking a single class"); } @Test @@ -183,9 +180,9 @@ public class DefinitionsParserTests { @Test public void parseSpyBeanMissingClassToMock() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to deduce type to spy"); - this.parser.parse(SpyBeanMissingClassToMock.class); + assertThatIllegalStateException() + .isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class)) + .withMessageContaining("Unable to deduce type to spy"); } @Test @@ -200,10 +197,10 @@ public class DefinitionsParserTests { @Test public void parseSpyBeanMultipleClassesWithName() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The name attribute can only be used when spying a single class"); - this.parser.parse(SpyBeanMultipleClassesWithName.class); + assertThatIllegalStateException() + .isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class)) + .withMessageContaining( + "The name attribute can only be used when spying a single class"); } private MockDefinition getMockDefinition(int index) { diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java index dd9a51d2df1..04f31b9c679 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockDefinitionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package org.springframework.boot.test.mock.mockito; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Answers; import org.mockito.Mockito; import org.mockito.mock.MockCreationSettings; @@ -28,6 +26,7 @@ import org.springframework.boot.test.mock.mockito.example.ExampleService; import org.springframework.core.ResolvableType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -40,14 +39,11 @@ public class MockDefinitionTests { private static final ResolvableType EXAMPLE_SERVICE_TYPE = ResolvableType .forClass(ExampleService.class); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void classToMockMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TypeToMock must not be null"); - new MockDefinition(null, null, null, null, false, null, null); + assertThatIllegalArgumentException().isThrownBy( + () -> new MockDefinition(null, null, null, null, false, null, null)) + .withMessageContaining("TypeToMock must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java index da7a76a1e3d..e0c9aabe521 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/MockitoPostProcessorTests.java @@ -16,9 +16,7 @@ package org.springframework.boot.test.mock.mockito; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.springframework.beans.factory.FactoryBean; @@ -33,6 +31,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Test for {@link MockitoPostProcessor}. See also the integration tests. @@ -43,20 +42,16 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class MockitoPostProcessorTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void cannotMockMultipleBeans() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); context.register(MultipleBeans.class); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace " - + "but found [example1, example2]"); - context.refresh(); + assertThatIllegalStateException().isThrownBy(context::refresh) + .withMessageContaining( + "Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace " + + "but found [example1, example2]"); } @Test @@ -64,12 +59,11 @@ public class MockitoPostProcessorTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); MockitoPostProcessor.register(context); context.register(MultipleQualifiedBeans.class); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Unable to register mock bean " + ExampleService.class.getName() - + " expected a single matching bean to replace " - + "but found [example1, example3]"); - context.refresh(); + assertThatIllegalStateException().isThrownBy(context::refresh) + .withMessageContaining( + "Unable to register mock bean " + ExampleService.class.getName() + + " expected a single matching bean to replace " + + "but found [example1, example3]"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java index d76a4d5219d..2b546a01e7f 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/SpyDefinitionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package org.springframework.boot.test.mock.mockito; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Answers; import org.mockito.Mockito; import org.mockito.mock.MockCreationSettings; @@ -29,6 +27,7 @@ import org.springframework.boot.test.mock.mockito.example.RealExampleService; import org.springframework.core.ResolvableType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -41,14 +40,11 @@ public class SpyDefinitionTests { private static final ResolvableType REAL_SERVICE_TYPE = ResolvableType .forClass(RealExampleService.class); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void classToSpyMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TypeToSpy must not be null"); - new SpyDefinition(null, null, null, true, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SpyDefinition(null, null, null, true, null)) + .withMessageContaining("TypeToSpy must not be null"); } @Test @@ -91,18 +87,17 @@ public class SpyDefinitionTests { public void createSpyWhenNullInstanceShouldThrowException() { SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Instance must not be null"); - definition.createSpy(null); + assertThatIllegalArgumentException().isThrownBy(() -> definition.createSpy(null)) + .withMessageContaining("Instance must not be null"); } @Test public void createSpyWhenWrongInstanceShouldThrowException() { SpyDefinition definition = new SpyDefinition("name", REAL_SERVICE_TYPE, MockReset.BEFORE, true, null); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("must be an instance of"); - definition.createSpy(new ExampleServiceCaller(null)); + assertThatIllegalArgumentException() + .isThrownBy(() -> definition.createSpy(new ExampleServiceCaller(null))) + .withMessageContaining("must be an instance of"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java index 78658b9ad3c..05eb4a6e5ef 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/LocalHostUriTemplateHandlerTests.java @@ -20,14 +20,13 @@ import java.net.URI; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.mock.env.MockEnvironment; import org.springframework.web.util.UriTemplateHandler; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -41,28 +40,26 @@ import static org.mockito.Mockito.verify; */ public class LocalHostUriTemplateHandlerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenEnvironmentIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Environment must not be null"); - new LocalHostUriTemplateHandler(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new LocalHostUriTemplateHandler(null)) + .withMessageContaining("Environment must not be null"); } @Test public void createWhenSchemeIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Scheme must not be null"); - new LocalHostUriTemplateHandler(new MockEnvironment(), null); + assertThatIllegalArgumentException().isThrownBy( + () -> new LocalHostUriTemplateHandler(new MockEnvironment(), null)) + .withMessageContaining("Scheme must not be null"); } @Test public void createWhenHandlerIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Handler must not be null"); - new LocalHostUriTemplateHandler(new MockEnvironment(), "http", null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new LocalHostUriTemplateHandler(new MockEnvironment(), + "http", null)) + .withMessageContaining("Handler must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java index 2e2166ff916..7c349f2d7e3 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/MockServerRestTemplateCustomizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -17,9 +17,7 @@ package org.springframework.boot.test.web.client; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.test.web.client.RequestExpectationManager; @@ -28,6 +26,8 @@ import org.springframework.test.web.client.UnorderedRequestExpectationManager; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; @@ -40,9 +40,6 @@ public class MockServerRestTemplateCustomizerTests { private MockServerRestTemplateCustomizer customizer; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Before public void setup() { this.customizer = new MockServerRestTemplateCustomizer(); @@ -58,9 +55,9 @@ public class MockServerRestTemplateCustomizerTests { @Test public void createWhenExpectationManagerClassIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ExpectationManager must not be null"); - new MockServerRestTemplateCustomizer(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new MockServerRestTemplateCustomizer(null)) + .withMessageContaining("ExpectationManager must not be null"); } @Test @@ -102,20 +99,20 @@ public class MockServerRestTemplateCustomizerTests { @Test public void getServerWhenNoServersAreBoundShouldThrowException() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has not been bound to a RestTemplate"); - this.customizer.getServer(); + assertThatIllegalStateException().isThrownBy(this.customizer::getServer) + .withMessageContaining( + "Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has not been bound to a RestTemplate"); } @Test public void getServerWhenMultipleServersAreBoundShouldThrowException() { this.customizer.customize(new RestTemplate()); this.customizer.customize(new RestTemplate()); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to return a single MockRestServiceServer since " - + "MockServerRestTemplateCustomizer has been bound to more than one RestTemplate"); - this.customizer.getServer(); + assertThatIllegalStateException().isThrownBy(this.customizer::getServer) + .withMessageContaining( + "Unable to return a single MockRestServiceServer since " + + "MockServerRestTemplateCustomizer has been bound to more than one RestTemplate"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java index e850d8312f0..f29041db177 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/client/RootUriRequestExpectationManagerTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.test.web.client; import java.net.URI; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; @@ -37,6 +35,8 @@ import org.springframework.test.web.client.RequestMatcher; import org.springframework.web.client.RestTemplate; 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.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -51,9 +51,6 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat */ public class RootUriRequestExpectationManagerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private String uri = "http://example.com"; @Mock @@ -72,16 +69,17 @@ public class RootUriRequestExpectationManagerTests { @Test public void createWhenRootUriIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RootUri must not be null"); - new RootUriRequestExpectationManager(null, this.delegate); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new RootUriRequestExpectationManager(null, this.delegate)) + .withMessageContaining("RootUri must not be null"); } @Test public void createWhenExpectationManagerIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ExpectationManager must not be null"); - new RootUriRequestExpectationManager(this.uri, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new RootUriRequestExpectationManager(this.uri, null)) + .withMessageContaining("ExpectationManager must not be null"); } @Test @@ -121,9 +119,9 @@ public class RootUriRequestExpectationManagerTests { given(this.delegate.validateRequest(any(ClientHttpRequest.class))) .willThrow(new AssertionError( "Request URI expected: was:")); - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("Request URI expected:"); - this.manager.validateRequest(request); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> this.manager.validateRequest(request)) + .withMessageContaining("Request URI expected:"); } @Test @@ -182,10 +180,10 @@ public class RootUriRequestExpectationManagerTests { MockRestServiceServer server = RootUriRequestExpectationManager .bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage( - "expected: but was:"); - restTemplate.getForEntity("http://spring.io/hello", String.class); + assertThatExceptionOfType(AssertionError.class).isThrownBy( + () -> restTemplate.getForEntity("http://spring.io/hello", String.class)) + .withMessageContaining( + "expected: but was:"); } } diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java index 5886e3a792d..0f8ec5ea245 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/LocalHostWebClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -24,9 +24,7 @@ import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebConnection; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebResponse; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; @@ -34,6 +32,7 @@ import org.mockito.MockitoAnnotations; import org.springframework.mock.env.MockEnvironment; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -47,9 +46,6 @@ import static org.mockito.Mockito.verify; @SuppressWarnings("resource") public class LocalHostWebClientTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Captor private ArgumentCaptor requestCaptor; @@ -59,9 +55,9 @@ public class LocalHostWebClientTests { @Test public void createWhenEnvironmentIsNullWillThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Environment must not be null"); - new LocalHostWebClient(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new LocalHostWebClient(null)) + .withMessageContaining("Environment must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java index 22a8285e97b..c0c759ebd27 100644 --- a/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java +++ b/spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/web/htmlunit/webdriver/LocalHostWebConnectionHtmlUnitDriverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +23,7 @@ import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebClientOptions; import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebWindow; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -34,6 +32,7 @@ import org.openqa.selenium.Capabilities; import org.springframework.core.env.Environment; import org.springframework.mock.env.MockEnvironment; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.BDDMockito.given; @@ -47,9 +46,6 @@ import static org.mockito.Mockito.verify; */ public class LocalHostWebConnectionHtmlUnitDriverTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private WebClient webClient; @@ -60,33 +56,34 @@ public class LocalHostWebConnectionHtmlUnitDriverTests { @Test public void createWhenEnvironmentIsNullWillThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Environment must not be null"); - new LocalHostWebConnectionHtmlUnitDriver(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null)) + .withMessageContaining("Environment must not be null"); } @Test public void createWithJavascriptFlagWhenEnvironmentIsNullWillThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Environment must not be null"); - new LocalHostWebConnectionHtmlUnitDriver(null, true); + assertThatIllegalArgumentException() + .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, true)) + .withMessageContaining("Environment must not be null"); } @Test public void createWithBrowserVersionWhenEnvironmentIsNullWillThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Environment must not be null"); - new LocalHostWebConnectionHtmlUnitDriver(null, BrowserVersion.CHROME); + assertThatIllegalArgumentException() + .isThrownBy(() -> new LocalHostWebConnectionHtmlUnitDriver(null, + BrowserVersion.CHROME)) + .withMessageContaining("Environment must not be null"); } @Test public void createWithCapabilitiesWhenEnvironmentIsNullWillThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Environment must not be null"); Capabilities capabilities = mock(Capabilities.class); given(capabilities.getBrowserName()).willReturn("htmlunit"); given(capabilities.getVersion()).willReturn("chrome"); - new LocalHostWebConnectionHtmlUnitDriver(null, capabilities); + assertThatIllegalArgumentException().isThrownBy( + () -> new LocalHostWebConnectionHtmlUnitDriver(null, capabilities)) + .withMessageContaining("Environment must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java index a3cd8bb1f31..15bff6e494c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/AbstractConfigurationMetadataTests.java @@ -19,9 +19,6 @@ package org.springframework.boot.configurationmetadata; import java.io.IOException; import java.io.InputStream; -import org.junit.Rule; -import org.junit.rules.ExpectedException; - import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; @@ -34,9 +31,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public abstract class AbstractConfigurationMetadataTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - protected void assertSource(ConfigurationMetadataSource actual, String groupId, String type, String sourceType) { assertThat(actual).isNotNull(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java index 61ea9a8b281..ebfa82cfd67 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,6 +23,7 @@ import java.util.Map; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ConfigurationMetadataRepository}. @@ -34,8 +35,9 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests @Test public void nullResource() throws IOException { - this.thrown.expect(IllegalArgumentException.class); - ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create() + .withJsonResource(null)); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java index c6ce7db9a76..bac17534140 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-metadata/src/test/java/org/springframework/boot/configurationmetadata/JsonReaderTests.java @@ -21,11 +21,11 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; -import org.hamcrest.CoreMatchers; import org.json.JSONException; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link JsonReader}. @@ -47,8 +47,8 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests { @Test public void invalidMetadata() throws IOException { - this.thrown.expectCause(CoreMatchers.instanceOf(JSONException.class)); - readFor("invalid"); + assertThatIllegalStateException().isThrownBy(() -> readFor("invalid")) + .withCauseInstanceOf(JSONException.class); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java index 613b6db9267..001e11a8d19 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java @@ -28,7 +28,6 @@ import java.util.stream.Collectors; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.configurationprocessor.json.JSONArray; @@ -95,6 +94,7 @@ import org.springframework.boot.testsupport.compiler.TestCompiler; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link ConfigurationMetadataAnnotationProcessor}. @@ -110,9 +110,6 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private TestCompiler compiler; @Before @@ -502,9 +499,9 @@ public class ConfigurationMetadataAnnotationProcessorTests { @Test public void invalidDoubleRegistration() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Compilation failed"); - compile(InvalidDoubleRegistrationProperties.class); + assertThatIllegalStateException() + .isThrownBy(() -> compile(InvalidDoubleRegistrationProperties.class)) + .withMessageContaining("Compilation failed"); } @Test @@ -904,10 +901,9 @@ public class ConfigurationMetadataAnnotationProcessorTests { public void mergeOfInvalidAdditionalMetadata() throws IOException { File additionalMetadataFile = createAdditionalMetadataFile(); FileCopyUtils.copy("Hello World", new FileWriter(additionalMetadataFile)); - - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Compilation failed"); - compile(SimpleProperties.class); + assertThatIllegalStateException() + .isThrownBy(() -> compile(SimpleProperties.class)) + .withMessage("Compilation failed"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java index 59380972ecf..e8efd58eeb9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/LayoutsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,11 +18,10 @@ package org.springframework.boot.loader.tools; import java.io.File; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link Layouts}. @@ -32,9 +31,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class LayoutsTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void jarFile() { assertThat(Layouts.forFile(new File("test.jar"))).isInstanceOf(Layouts.Jar.class); @@ -55,9 +51,9 @@ public class LayoutsTests { @Test public void unknownFile() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to deduce layout for 'test.txt'"); - Layouts.forFile(new File("test.txt")); + assertThatIllegalStateException() + .isThrownBy(() -> Layouts.forFile(new File("test.txt"))) + .withMessageContaining("Unable to deduce layout for 'test.txt'"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java index 81ab7a17740..28a64df26af 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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 java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.loader.tools.MainClassFinder.MainClass; @@ -33,6 +32,7 @@ import org.springframework.boot.loader.tools.sample.ClassWithMainMethod; import org.springframework.boot.loader.tools.sample.ClassWithoutMainMethod; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link MainClassFinder}. @@ -44,9 +44,6 @@ public class MainClassFinderTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private TestJarFile testJarFile; @Before @@ -83,10 +80,11 @@ public class MainClassFinderTests { public void findSingleJarSearch() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find a single main class " - + "from the following candidates [a.B, a.b.c.E]"); - MainClassFinder.findSingleMainClass(this.testJarFile.getJarFile(), ""); + assertThatIllegalStateException() + .isThrownBy(() -> MainClassFinder + .findSingleMainClass(this.testJarFile.getJarFile(), "")) + .withMessageContaining("Unable to find a single main class " + + "from the following candidates [a.B, a.b.c.E]"); } @Test @@ -138,10 +136,11 @@ public class MainClassFinderTests { public void findSingleFolderSearch() throws Exception { this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find a single main class " - + "from the following candidates [a.B, a.b.c.E]"); - MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource()); + assertThatIllegalStateException() + .isThrownBy(() -> MainClassFinder + .findSingleMainClass(this.testJarFile.getJarSource())) + .withMessageContaining("Unable to find a single main class " + + "from the following candidates [a.B, a.b.c.E]"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java index be35e8bb9b3..0937e36968c 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/RepackagerTests.java @@ -40,7 +40,6 @@ import org.apache.commons.compress.archivers.zip.ZipFile; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.zeroturnaround.zip.ZipUtil; @@ -49,6 +48,8 @@ import org.springframework.boot.loader.tools.sample.ClassWithoutMainMethod; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -81,9 +82,6 @@ public class RepackagerTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private TestJarFile testJarFile; @Before @@ -93,20 +91,19 @@ public class RepackagerTests { @Test public void nullSource() { - this.thrown.expect(IllegalArgumentException.class); - new Repackager(null); + assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(null)); } @Test public void missingSource() { - this.thrown.expect(IllegalArgumentException.class); - new Repackager(new File("missing")); + assertThatIllegalArgumentException() + .isThrownBy(() -> new Repackager(new File("missing"))); } @Test public void directorySource() { - this.thrown.expect(IllegalArgumentException.class); - new Repackager(this.temporaryFolder.getRoot()); + assertThatIllegalArgumentException() + .isThrownBy(() -> new Repackager(this.temporaryFolder.getRoot())); } @Test @@ -177,18 +174,18 @@ public class RepackagerTests { this.testJarFile.addClass("a/b/D.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find a single main class " - + "from the following candidates [a.b.C, a.b.D]"); - repackager.repackage(NO_LIBRARIES); + assertThatIllegalStateException() + .isThrownBy(() -> repackager.repackage(NO_LIBRARIES)) + .withMessageContaining("Unable to find a single main class " + + "from the following candidates [a.b.C, a.b.D]"); } @Test public void noMainClass() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Unable to find main class"); - new Repackager(this.testJarFile.getFile()).repackage(NO_LIBRARIES); + assertThatIllegalStateException().isThrownBy( + () -> new Repackager(this.testJarFile.getFile()).repackage(NO_LIBRARIES)) + .withMessageContaining("Unable to find main class"); } @Test @@ -255,18 +252,18 @@ public class RepackagerTests { public void nullDestination() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = new Repackager(this.testJarFile.getFile()); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Invalid destination"); - repackager.repackage(null, NO_LIBRARIES); + assertThatIllegalArgumentException() + .isThrownBy(() -> repackager.repackage(null, NO_LIBRARIES)) + .withMessageContaining("Invalid destination"); } @Test public void destinationIsDirectory() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); Repackager repackager = new Repackager(this.testJarFile.getFile()); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Invalid destination"); - repackager.repackage(this.temporaryFolder.getRoot(), NO_LIBRARIES); + assertThatIllegalArgumentException().isThrownBy( + () -> repackager.repackage(this.temporaryFolder.getRoot(), NO_LIBRARIES)) + .withMessageContaining("Invalid destination"); } @Test @@ -284,9 +281,9 @@ public class RepackagerTests { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Libraries must not be null"); - repackager.repackage(file, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> repackager.repackage(file, null)) + .withMessageContaining("Libraries must not be null"); } @Test @@ -327,12 +324,13 @@ public class RepackagerTests { this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); File file = this.testJarFile.getFile(); Repackager repackager = new Repackager(file); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Duplicate library"); - repackager.repackage((callback) -> { - callback.library(new Library(libJarFile, LibraryScope.COMPILE, false)); - callback.library(new Library(libJarFile, LibraryScope.COMPILE, false)); - }); + assertThatIllegalStateException() + .isThrownBy(() -> repackager.repackage((callback) -> { + callback.library( + new Library(libJarFile, LibraryScope.COMPILE, false)); + callback.library( + new Library(libJarFile, LibraryScope.COMPILE, false)); + })).withMessageContaining("Duplicate library"); } @Test @@ -421,9 +419,8 @@ public class RepackagerTests { public void nullCustomLayout() throws Exception { this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class); Repackager repackager = new Repackager(this.testJarFile.getFile()); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Layout must not be null"); - repackager.setLayout(null); + assertThatIllegalArgumentException().isThrownBy(() -> repackager.setLayout(null)) + .withMessageContaining("Layout must not be null"); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java index dc40aab9adf..bfeab15bbb2 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/PropertiesLauncherTests.java @@ -32,7 +32,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.loader.archive.Archive; @@ -43,6 +42,7 @@ import org.springframework.core.io.FileSystemResource; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link PropertiesLauncher}. @@ -55,9 +55,6 @@ public class PropertiesLauncherTests { @Rule public OutputCapture output = new OutputCapture(); - @Rule - public ExpectedException expected = ExpectedException.none(); - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -102,10 +99,9 @@ public class PropertiesLauncherTests { @Test public void testNonExistentHome() { System.setProperty("loader.home", "src/test/resources/nonexistent"); - this.expected.expectMessage("Invalid source folder"); - PropertiesLauncher launcher = new PropertiesLauncher(); - assertThat(launcher.getHomeDirectory()) - .isNotEqualTo(new File(System.getProperty("loader.home"))); + assertThatIllegalStateException().isThrownBy(PropertiesLauncher::new) + .withMessageContaining("Invalid source folder") + .withCauseInstanceOf(IllegalArgumentException.class); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java index 32079a780a2..cd173de51cf 100755 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java @@ -31,7 +31,6 @@ import java.util.zip.ZipEntry; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.loader.TestJarCreator; @@ -39,7 +38,7 @@ import org.springframework.boot.loader.archive.Archive.Entry; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.equalTo; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link JarFileArchive}. @@ -52,9 +51,6 @@ public class JarFileArchiveTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private File rootJarFile; private JarFileArchive archive; @@ -135,8 +131,8 @@ public class JarFileArchiveTests { public void zip64ArchivesAreHandledGracefully() throws IOException { File file = this.temporaryFolder.newFile("test.jar"); FileCopyUtils.copy(writeZip64Jar(), file); - this.thrown.expectMessage(equalTo("Zip64 archives are not supported")); - new JarFileArchive(file); + assertThatIllegalStateException().isThrownBy(() -> new JarFileArchive(file)) + .withMessageContaining("Zip64 archives are not supported"); } @Test @@ -156,10 +152,11 @@ public class JarFileArchiveTests { output.closeEntry(); output.close(); JarFileArchive jarFileArchive = new JarFileArchive(file); - this.thrown.expectMessage( - equalTo("Failed to get nested archive for entry nested/zip64.jar")); - jarFileArchive - .getNestedArchive(getEntriesMap(jarFileArchive).get("nested/zip64.jar")); + assertThatIllegalStateException() + .isThrownBy(() -> jarFileArchive.getNestedArchive( + getEntriesMap(jarFileArchive).get("nested/zip64.jar"))) + .withMessageContaining( + "Failed to get nested archive for entry nested/zip64.jar"); } private byte[] writeZip64Jar() throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java index b47b2f09567..c7a43dd68e7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/data/RandomAccessDataFileTests.java @@ -31,10 +31,12 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; 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.assertThatNullPointerException; /** * Tests for {@link RandomAccessDataFile}. @@ -53,9 +55,6 @@ public class RandomAccessDataFileTests { } } - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -83,18 +82,17 @@ public class RandomAccessDataFileTests { @Test public void fileNotNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("File must not be null"); - new RandomAccessDataFile(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new RandomAccessDataFile(null)) + .withMessageContaining("File must not be null"); } @Test public void fileExists() { File file = new File("/does/not/exist"); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage( - String.format("File %s must exist", file.getAbsolutePath())); - new RandomAccessDataFile(file); + assertThatIllegalArgumentException() + .isThrownBy(() -> new RandomAccessDataFile(file)).withMessageContaining( + String.format("File %s must exist", file.getAbsolutePath())); } @Test @@ -105,31 +103,31 @@ public class RandomAccessDataFileTests { @Test public void readWhenOffsetIsBeyondEOFShouldThrowException() throws Exception { - this.thrown.expect(IndexOutOfBoundsException.class); - this.file.read(257, 0); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> this.file.read(257, 0)); } @Test public void readWhenOffsetIsBeyondEndOfSubsectionShouldThrowException() throws Exception { - this.thrown.expect(IndexOutOfBoundsException.class); RandomAccessData subsection = this.file.getSubsection(0, 10); - subsection.read(11, 0); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> subsection.read(11, 0)); } @Test public void readWhenOffsetPlusLengthGreaterThanEOFShouldThrowException() throws Exception { - this.thrown.expect(EOFException.class); - this.file.read(256, 1); + assertThatExceptionOfType(EOFException.class) + .isThrownBy(() -> this.file.read(256, 1)); } @Test public void readWhenOffsetPlusLengthGreaterThanEndOfSubsectionShouldThrowException() throws Exception { - this.thrown.expect(EOFException.class); RandomAccessData subsection = this.file.getSubsection(0, 10); - subsection.read(10, 1); + assertThatExceptionOfType(EOFException.class) + .isThrownBy(() -> subsection.read(10, 1)); } @Test @@ -141,16 +139,15 @@ public class RandomAccessDataFileTests { @Test public void inputStreamReadNullBytes() throws Exception { - this.thrown.expect(NullPointerException.class); - this.thrown.expectMessage("Bytes must not be null"); - this.inputStream.read(null); + assertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null)) + .withMessage("Bytes must not be null"); } @Test public void inputStreamReadNullBytesWithOffset() throws Exception { - this.thrown.expect(NullPointerException.class); - this.thrown.expectMessage("Bytes must not be null"); - this.inputStream.read(null, 0, 1); + assertThatNullPointerException() + .isThrownBy(() -> this.inputStream.read(null, 0, 1)) + .withMessage("Bytes must not be null"); } @Test @@ -218,14 +215,14 @@ public class RandomAccessDataFileTests { @Test public void subsectionNegativeOffset() { - this.thrown.expect(IndexOutOfBoundsException.class); - this.file.getSubsection(-1, 1); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> this.file.getSubsection(-1, 1)); } @Test public void subsectionNegativeLength() { - this.thrown.expect(IndexOutOfBoundsException.class); - this.file.getSubsection(0, -1); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> this.file.getSubsection(0, -1)); } @Test @@ -237,15 +234,15 @@ public class RandomAccessDataFileTests { @Test public void subsectionTooBig() { this.file.getSubsection(0, 256); - this.thrown.expect(IndexOutOfBoundsException.class); - this.file.getSubsection(0, 257); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> this.file.getSubsection(0, 257)); } @Test public void subsectionTooBigWithOffset() { this.file.getSubsection(1, 255); - this.thrown.expect(IndexOutOfBoundsException.class); - this.file.getSubsection(1, 256); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> this.file.getSubsection(1, 256)); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java index ec90aaee501..9d759af16df 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/AsciiBytesTests.java @@ -16,11 +16,10 @@ package org.springframework.boot.loader.jar; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link AsciiBytes}. @@ -32,9 +31,6 @@ public class AsciiBytesTests { private static final char NO_SUFFIX = 0; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createFromBytes() { AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66 }); @@ -93,8 +89,8 @@ public class AsciiBytesTests { assertThat(abcd.substring(2).toString()).isEqualTo("CD"); assertThat(abcd.substring(3).toString()).isEqualTo("D"); assertThat(abcd.substring(4).toString()).isEqualTo(""); - this.thrown.expect(IndexOutOfBoundsException.class); - abcd.substring(5); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> abcd.substring(5)); } @Test @@ -104,8 +100,8 @@ public class AsciiBytesTests { assertThat(abcd.substring(1, 3).toString()).isEqualTo("BC"); assertThat(abcd.substring(3, 4).toString()).isEqualTo("D"); assertThat(abcd.substring(3, 3).toString()).isEqualTo(""); - this.thrown.expect(IndexOutOfBoundsException.class); - abcd.substring(3, 5); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> abcd.substring(3, 5)); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java index facab4b4b68..bdf57d00e9f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarFileTests.java @@ -21,7 +21,6 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilePermission; -import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; @@ -36,7 +35,6 @@ import java.util.zip.ZipFile; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.loader.TestJarCreator; @@ -45,6 +43,8 @@ import org.springframework.util.FileCopyUtils; import org.springframework.util.StreamUtils; 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.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -61,9 +61,6 @@ public class JarFileTests { private static final String HANDLERS_PACKAGE = "org.springframework.boot.loader"; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -231,16 +228,15 @@ public class JarFileTests { URL url = new URL(this.jarFile.getUrl(), "missing.dat"); assertThat(url.toString()) .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat"); - this.thrown.expect(FileNotFoundException.class); - ((JarURLConnection) url.openConnection()).getJarEntry(); + assertThatExceptionOfType(FileNotFoundException.class) + .isThrownBy(((JarURLConnection) url.openConnection())::getJarEntry); } @Test public void getUrlStream() throws Exception { URL url = this.jarFile.getUrl(); url.openConnection(); - this.thrown.expect(IOException.class); - url.openStream(); + assertThatIOException().isThrownBy(url::openStream); } @Test @@ -432,8 +428,8 @@ public class JarFileTests { .getNestedJarFile(this.jarFile.getEntry("nested.jar")); URL nestedUrl = nestedJarFile.getUrl(); URL url = new URL(nestedUrl, nestedJarFile.getUrl() + "missing.jar!/3.dat"); - this.thrown.expect(FileNotFoundException.class); - url.openConnection().getInputStream(); + assertThatExceptionOfType(FileNotFoundException.class) + .isThrownBy(url.openConnection()::getInputStream); } @Test @@ -494,9 +490,9 @@ public class JarFileTests { URL context = nested.getUrl(); new URL(context, "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat") .openConnection().getInputStream().close(); - this.thrown.expect(FileNotFoundException.class); - new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat") - .openConnection().getInputStream(); + assertThatExceptionOfType(FileNotFoundException.class).isThrownBy( + new URL(context, "jar:" + this.rootJarFile.toURI() + "!/no.dat") + .openConnection()::getInputStream); } finally { JarURLConnection.setUseFastExceptions(false); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java index 65f0261c8da..b14f0ffdf11 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/JarURLConnectionTests.java @@ -24,13 +24,13 @@ import java.net.URL; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.jar.JarURLConnection.JarEntryName; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link JarURLConnection}. @@ -44,9 +44,6 @@ public class JarURLConnectionTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("target")); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private File rootJarFile; private JarFile jarFile; @@ -160,8 +157,8 @@ public class JarURLConnectionTests { URL url = new URL("jar:file:" + getAbsolutePath() + "!/w.jar!/3.dat"); JarFile nested = this.jarFile .getNestedJarFile(this.jarFile.getEntry("nested.jar")); - this.thrown.expect(FileNotFoundException.class); - JarURLConnection.get(url, nested).getInputStream(); + assertThatExceptionOfType(FileNotFoundException.class) + .isThrownBy(JarURLConnection.get(url, nested)::getInputStream); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java index d9d2d48ece4..b3a9b113d93 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/StringSequenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,11 +16,11 @@ package org.springframework.boot.loader.jar; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatNullPointerException; /** * Tests for {@link StringSequence}. @@ -29,33 +29,28 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class StringSequenceTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenSourceIsNullShouldThrowException() { - this.thrown.expect(NullPointerException.class); - this.thrown.expectMessage("Source must not be null"); - new StringSequence(null); + assertThatNullPointerException().isThrownBy(() -> new StringSequence(null)) + .withMessage("Source must not be null"); } @Test public void createWithIndexWhenSourceIsNullShouldThrowException() { - this.thrown.expect(NullPointerException.class); - this.thrown.expectMessage("Source must not be null"); - new StringSequence(null, 0, 0); + assertThatNullPointerException().isThrownBy(() -> new StringSequence(null, 0, 0)) + .withMessage("Source must not be null"); } @Test public void createWhenStartIsLessThanZeroShouldThrowException() { - this.thrown.expect(StringIndexOutOfBoundsException.class); - new StringSequence("x", -1, 0); + assertThatExceptionOfType(StringIndexOutOfBoundsException.class) + .isThrownBy(() -> new StringSequence("x", -1, 0)); } @Test public void createWhenEndIsGreaterThanLengthShouldThrowException() { - this.thrown.expect(StringIndexOutOfBoundsException.class); - new StringSequence("x", 0, 2); + assertThatExceptionOfType(StringIndexOutOfBoundsException.class) + .isThrownBy(() -> new StringSequence("x", 0, 2)); } @Test @@ -88,8 +83,8 @@ public class StringSequenceTests { StringSequence sequence = new StringSequence("abcde").subSequence(1, 4); assertThat(sequence.toString()).isEqualTo("bcd"); assertThat(sequence.subSequence(2, 3).toString()).isEqualTo("d"); - this.thrown.expect(IndexOutOfBoundsException.class); - sequence.subSequence(3, 4); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> sequence.subSequence(3, 4)); } @Test @@ -97,8 +92,8 @@ public class StringSequenceTests { StringSequence sequence = new StringSequence("abcde").subSequence(1, 4); assertThat(sequence.toString()).isEqualTo("bcd"); assertThat(sequence.subSequence(2, 3).toString()).isEqualTo("d"); - this.thrown.expect(IndexOutOfBoundsException.class); - sequence.subSequence(4, 3); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> sequence.subSequence(4, 3)); } @Test diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/assertj/MatchedTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/assertj/MatchedTests.java index 171e287b1c1..a435deaf7af 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/assertj/MatchedTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/assertj/MatchedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,11 +16,10 @@ package org.springframework.boot.testsupport.assertj; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.startsWith; /** @@ -30,9 +29,6 @@ import static org.hamcrest.Matchers.startsWith; */ public class MatchedTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void byMatcherMatches() { assertThat("1234").is(Matched.by(startsWith("12"))); @@ -40,9 +36,9 @@ public class MatchedTests { @Test public void byMatcherDoesNotMatch() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("a string starting with \"23\""); - assertThat("1234").is(Matched.by(startsWith("23"))); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat("1234").is(Matched.by(startsWith("23")))) + .withMessageContaining("a string starting with \"23\""); } @Test @@ -52,9 +48,9 @@ public class MatchedTests { @Test public void whenMatcherDoesNotMatch() { - this.thrown.expect(AssertionError.class); - this.thrown.expectMessage("a string starting with \"23\""); - assertThat("1234").is(Matched.when(startsWith("23"))); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> assertThat("1234").is(Matched.when(startsWith("23")))) + .withMessageContaining("a string starting with \"23\""); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java index 2b793dfe4a2..9f940bb6dd7 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/test/java/org/springframework/boot/testsupport/runner/classpath/ModifiedClassPathRunnerExclusionsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,8 @@ package org.springframework.boot.testsupport.runner.classpath; -import org.junit.Rule; +import org.hamcrest.Matcher; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; @@ -36,9 +35,6 @@ public class ModifiedClassPathRunnerExclusionsTests { private static final String EXCLUDED_RESOURCE = "META-INF/services/" + "javax.validation.spi.ValidationProvider"; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void entriesAreFilteredFromTestClassClassLoader() { assertThat(getClass().getClassLoader().getResource(EXCLUDED_RESOURCE)).isNull(); @@ -52,8 +48,8 @@ public class ModifiedClassPathRunnerExclusionsTests { @Test public void testsThatUseHamcrestWorkCorrectly() { - this.thrown.expect(isA(IllegalStateException.class)); - throw new IllegalStateException(); + Matcher matcher = isA(IllegalStateException.class); + assertThat(matcher.matches(new IllegalStateException())).isTrue(); } } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java index 5fe8050c98f..81d28d31775 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactory.java @@ -307,7 +307,7 @@ public class UndertowServletWebServerFactory extends AbstractServletWebServerFac EventListener listener = new AccessLogShutdownListener(worker, accessLogReceiver); deploymentInfo.addListener(new ListenerInfo(AccessLogShutdownListener.class, - new ImmediateInstanceFactory(listener))); + new ImmediateInstanceFactory<>(listener))); deploymentInfo.addInitialHandlerChainWrapper( (handler) -> createAccessLogHandler(handler, accessLogReceiver)); } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java index 0920e59c0d9..93ae9997b8f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/DefaultApplicationArgumentsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,11 +20,10 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultApplicationArguments}. @@ -36,14 +35,11 @@ public class DefaultApplicationArgumentsTests { private static final String[] ARGS = new String[] { "--foo=bar", "--foo=baz", "--debug", "spring", "boot" }; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void argumentsMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Args must not be null"); - new DefaultApplicationArguments(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DefaultApplicationArguments(null)) + .withMessageContaining("Args must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java index 685b67dbf6a..48d59bb0e09 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/ExitCodeGeneratorsTests.java @@ -19,11 +19,10 @@ package org.springframework.boot; import java.io.IOException; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -34,22 +33,19 @@ import static org.mockito.Mockito.mock; */ public class ExitCodeGeneratorsTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void addAllWhenGeneratorsIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Generators must not be null"); - List generators = null; - new ExitCodeGenerators().addAll(generators); + assertThatIllegalArgumentException().isThrownBy(() -> { + List generators = null; + new ExitCodeGenerators().addAll(generators); + }).withMessageContaining("Generators must not be null"); } @Test public void addWhenGeneratorIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Generator must not be null"); - new ExitCodeGenerators().add(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ExitCodeGenerators().add(null)) + .withMessageContaining("Generator must not be null"); } @Test 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 b249eed191b..275298cd6e4 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 @@ -34,7 +34,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.InOrder; @@ -103,7 +102,9 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StandardServletEnvironment; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.equalTo; +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; @@ -132,9 +133,6 @@ public class SpringApplicationTests { private String headlessProperty; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public OutputCapture output = new OutputCapture(); @@ -174,23 +172,23 @@ public class SpringApplicationTests { @Test public void sourcesMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("PrimarySources must not be null"); - new SpringApplication((Class[]) null).run(); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SpringApplication((Class[]) null).run()) + .withMessageContaining("PrimarySources must not be null"); } @Test public void sourcesMustNotBeEmpty() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Sources must not be empty"); - new SpringApplication().run(); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SpringApplication().run()) + .withMessageContaining("Sources must not be empty"); } @Test public void sourcesMustBeAccessible() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Cannot load configuration"); - new SpringApplication(InaccessibleConfiguration.class).run(); + assertThatIllegalStateException().isThrownBy( + () -> new SpringApplication(InaccessibleConfiguration.class).run()) + .withMessageContaining("Cannot load configuration"); } @Test @@ -696,16 +694,10 @@ public class SpringApplicationTests { willThrow(failure).given(runner).run(isA(ApplicationArguments.class)); application.addInitializers((context) -> context.getBeanFactory() .registerSingleton("runner", runner)); - this.thrown.expectCause(equalTo(failure)); - try { - application.run(); - } - finally { - verify(listener).onApplicationEvent(isA(ApplicationStartedEvent.class)); - verify(listener).onApplicationEvent(isA(ApplicationFailedEvent.class)); - verify(listener, never()) - .onApplicationEvent(isA(ApplicationReadyEvent.class)); - } + assertThatIllegalStateException().isThrownBy(application::run).withCause(failure); + verify(listener).onApplicationEvent(isA(ApplicationStartedEvent.class)); + verify(listener).onApplicationEvent(isA(ApplicationFailedEvent.class)); + verify(listener, never()).onApplicationEvent(isA(ApplicationReadyEvent.class)); } @Test @@ -722,16 +714,10 @@ public class SpringApplicationTests { willThrow(failure).given(runner).run(); application.addInitializers((context) -> context.getBeanFactory() .registerSingleton("runner", runner)); - this.thrown.expectCause(equalTo(failure)); - try { - application.run(); - } - finally { - verify(listener).onApplicationEvent(isA(ApplicationStartedEvent.class)); - verify(listener).onApplicationEvent(isA(ApplicationFailedEvent.class)); - verify(listener, never()) - .onApplicationEvent(isA(ApplicationReadyEvent.class)); - } + assertThatIllegalStateException().isThrownBy(application::run).withCause(failure); + verify(listener).onApplicationEvent(isA(ApplicationStartedEvent.class)); + verify(listener).onApplicationEvent(isA(ApplicationFailedEvent.class)); + verify(listener, never()).onApplicationEvent(isA(ApplicationReadyEvent.class)); } @Test @@ -745,15 +731,10 @@ public class SpringApplicationTests { RuntimeException failure = new RuntimeException(); willThrow(failure).given(listener) .onApplicationEvent(isA(ApplicationReadyEvent.class)); - this.thrown.expect(equalTo(failure)); - try { - application.run(); - } - finally { - verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); - verify(listener, never()) - .onApplicationEvent(isA(ApplicationFailedEvent.class)); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(application::run) + .isEqualTo(failure); + verify(listener).onApplicationEvent(isA(ApplicationReadyEvent.class)); + verify(listener, never()).onApplicationEvent(isA(ApplicationFailedEvent.class)); } @Test @@ -1199,8 +1180,9 @@ public class SpringApplicationTests { @Test public void beanDefinitionOverridingIsDisabledByDefault() { - this.thrown.expect(BeanDefinitionOverrideException.class); - new SpringApplication(ExampleConfig.class, OverrideConfig.class).run(); + assertThatExceptionOfType(BeanDefinitionOverrideException.class).isThrownBy( + () -> new SpringApplication(ExampleConfig.class, OverrideConfig.class) + .run()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java index d487b94dfee..6045864c806 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/admin/SpringApplicationAdminMXBeanRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -25,9 +25,7 @@ import javax.management.ObjectName; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -39,6 +37,7 @@ import org.springframework.context.event.ContextRefreshedEvent; 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.mockito.Mockito.mock; /** @@ -51,9 +50,6 @@ public class SpringApplicationAdminMXBeanRegistrarTests { private static final String OBJECT_NAME = "org.springframework.boot:type=Test,name=SpringApplication"; - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private MBeanServer mBeanServer; private ConfigurableApplicationContext context; @@ -129,8 +125,9 @@ public class SpringApplicationAdminMXBeanRegistrarTests { assertThat(this.context.isRunning()).isTrue(); invokeShutdown(objectName); assertThat(this.context.isRunning()).isFalse(); - this.thrown.expect(InstanceNotFoundException.class); // JMX cleanup - this.mBeanServer.getObjectInstance(objectName); + // JMX cleanup + assertThatExceptionOfType(InstanceNotFoundException.class) + .isThrownBy(() -> this.mBeanServer.getObjectInstance(objectName)); } private Boolean isApplicationReady(ObjectName objectName) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java index 3ff1760dbfb..746be3994e5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/ApplicationPidFileWriterTests.java @@ -23,7 +23,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.boot.SpringApplication; @@ -39,6 +38,7 @@ import org.springframework.mock.env.MockPropertySource; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -59,9 +59,6 @@ public class ApplicationPidFileWriterTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Rule - public ExpectedException exception = ExpectedException.none(); - @Before @After public void resetListener() { @@ -150,9 +147,9 @@ public class ApplicationPidFileWriterTests { file.setReadOnly(); System.setProperty("PID_FAIL_ON_WRITE_ERROR", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); - this.exception.expect(IllegalStateException.class); - this.exception.expectMessage("Cannot create pid file"); - listener.onApplicationEvent(EVENT); + assertThatIllegalStateException() + .isThrownBy(() -> listener.onApplicationEvent(EVENT)) + .withMessageContaining("Cannot create pid file"); } @Test @@ -162,9 +159,9 @@ public class ApplicationPidFileWriterTests { SpringApplicationEvent event = createPreparedEvent( "spring.pid.fail-on-write-error", "true"); ApplicationPidFileWriter listener = new ApplicationPidFileWriter(file); - this.exception.expect(IllegalStateException.class); - this.exception.expectMessage("Cannot create pid file"); - listener.onApplicationEvent(event); + assertThatIllegalStateException() + .isThrownBy(() -> listener.onApplicationEvent(event)) + .withMessageContaining("Cannot create pid file"); } private SpringApplicationEvent createEnvironmentPreparedEvent(String propName, diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java index a586e4b5822..7a2b1bdd56d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/TypeExcludeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -17,9 +17,7 @@ package org.springframework.boot.context; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.context.filtersample.ExampleComponent; @@ -32,6 +30,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link TypeExcludeFilter}. @@ -40,9 +39,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class TypeExcludeFilterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private AnnotationConfigApplicationContext context; @After @@ -62,8 +58,8 @@ public class TypeExcludeFilterTests { this.context.register(Config.class); this.context.refresh(); assertThat(this.context.getBean(ExampleComponent.class)).isNotNull(); - this.thrown.expect(NoSuchBeanDefinitionException.class); - this.context.getBean(ExampleFilteredComponent.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> this.context.getBean(ExampleFilteredComponent.class)); } @Configuration diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java index dbbcbdd2225..3cf240b0eab 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/annotation/ConfigurationsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -24,15 +24,14 @@ import java.util.Collection; import java.util.Comparator; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link Configurations}. @@ -41,14 +40,11 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ConfigurationsTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenClassesIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Classes must not be null"); - new TestConfigurations(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new TestConfigurations(null)) + .withMessageContaining("Classes must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java index 1637c3c3184..53d241826cf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigFileApplicationListenerTests.java @@ -37,7 +37,6 @@ import org.assertj.core.api.Condition; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -80,9 +79,6 @@ public class ConfigFileApplicationListenerTests { private final ConfigFileApplicationListener initializer = new ConfigFileApplicationListener(); - @Rule - public ExpectedException expected = ExpectedException.none(); - @Rule public OutputCapture out = new OutputCapture(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java index 77cde1d0f21..8973a5c609a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/config/DelegatingApplicationContextInitializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package org.springframework.boot.context.config; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.context.ApplicationContextException; import org.springframework.context.ApplicationContextInitializer; @@ -30,6 +28,8 @@ import org.springframework.test.context.support.TestPropertySourceUtils; import org.springframework.web.context.ConfigurableWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DelegatingApplicationContextInitializer}. @@ -38,9 +38,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class DelegatingApplicationContextInitializerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final DelegatingApplicationContextInitializer initializer = new DelegatingApplicationContextInitializer(); @Test @@ -73,8 +70,8 @@ public class DelegatingApplicationContextInitializerTests { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=missing.madeup.class"); - this.thrown.expect(ApplicationContextException.class); - this.initializer.initialize(context); + assertThatExceptionOfType(ApplicationContextException.class) + .isThrownBy(() -> this.initializer.initialize(context)); } @Test @@ -82,8 +79,8 @@ public class DelegatingApplicationContextInitializerTests { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=" + Object.class.getName()); - this.thrown.expect(IllegalArgumentException.class); - this.initializer.initialize(context); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.initializer.initialize(context)); } @Test @@ -91,9 +88,9 @@ public class DelegatingApplicationContextInitializerTests { StaticApplicationContext context = new StaticApplicationContext(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, "context.initializer.classes=" + NotSuitableInit.class.getName()); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("generic parameter"); - this.initializer.initialize(context); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.initializer.initialize(context)) + .withMessageContaining("generic parameter"); } @Order(Ordered.HIGHEST_PRECEDENCE) diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java index 8a7e683655d..58fbba16de5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerTests.java @@ -33,7 +33,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.slf4j.bridge.SLF4JBridgeHandler; @@ -65,6 +64,7 @@ import org.springframework.test.context.support.TestPropertySourceUtils; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; @@ -84,9 +84,6 @@ public class LoggingApplicationListenerTests { private static final String[] NO_ARGS = {}; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public OutputCapture outputCapture = new OutputCapture(); @@ -167,11 +164,12 @@ public class LoggingApplicationListenerTests { public void overrideConfigDoesNotExist() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.config=doesnotexist.xml"); - this.thrown.expect(IllegalStateException.class); - this.outputCapture.expect(containsString( - "Logging system failed to initialize using configuration from 'doesnotexist.xml'")); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + assertThatIllegalStateException().isThrownBy(() -> { + this.outputCapture.expect(containsString( + "Logging system failed to initialize using configuration from 'doesnotexist.xml'")); + this.initializer.initialize(this.context.getEnvironment(), + this.context.getClassLoader()); + }); } @Test @@ -202,12 +200,13 @@ public class LoggingApplicationListenerTests { public void overrideConfigBroken() { TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.context, "logging.config=classpath:logback-broken.xml"); - this.thrown.expect(IllegalStateException.class); - this.outputCapture.expect(containsString( - "Logging system failed to initialize using configuration from 'classpath:logback-broken.xml'")); - this.outputCapture.expect(containsString("ConsolAppender")); - this.initializer.initialize(this.context.getEnvironment(), - this.context.getClassLoader()); + assertThatIllegalStateException().isThrownBy(() -> { + this.outputCapture.expect(containsString( + "Logging system failed to initialize using configuration from 'classpath:logback-broken.xml'")); + this.outputCapture.expect(containsString("ConsolAppender")); + this.initializer.initialize(this.context.getEnvironment(), + this.context.getClassLoader()); + }); } @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 5957c0ade6f..c9ad5430230 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 @@ -33,11 +33,9 @@ import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; -import org.hamcrest.Matchers; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; @@ -81,8 +79,9 @@ import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; 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.hamcrest.Matchers.instanceOf; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -108,9 +107,6 @@ public class ConfigurationPropertiesTests { private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public OutputCapture output = new OutputCapture(); @@ -170,8 +166,10 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenHasIgnoreUnknownFieldsFalseAndUnknownFieldsShouldFail() { removeSystemProperties(); - this.thrown.expectCause(Matchers.instanceOf(BindException.class)); - load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz"); + assertThatExceptionOfType(ConfigurationPropertiesBindException.class) + .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, + "name=foo", "bar=baz")) + .withCauseInstanceOf(BindException.class); } @Test @@ -225,9 +223,10 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenBindingWithoutAndAnnotationShouldFail() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("No ConfigurationProperties annotation found"); - load(WithoutAndAnnotationConfiguration.class, "name:foo"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> load(WithoutAndAnnotationConfiguration.class, "name:foo")) + .withMessageContaining("No ConfigurationProperties annotation found"); } @Test @@ -501,26 +500,32 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenJsr303ConstraintDoesNotMatchShouldFail() { - this.thrown.expectCause(Matchers.instanceOf(BindException.class)); - load(ValidatedJsr303Configuration.class, "description="); + assertThatExceptionOfType(ConfigurationPropertiesBindException.class) + .isThrownBy( + () -> load(ValidatedJsr303Configuration.class, "description=")) + .withCauseInstanceOf(BindException.class); } @Test public void loadValidatedOnBeanMethodAndJsr303ConstraintDoesNotMatchShouldFail() { - this.thrown.expectCause(Matchers.instanceOf(BindException.class)); - load(ValidatedOnBeanJsr303Configuration.class, "description="); + assertThatExceptionOfType(ConfigurationPropertiesBindException.class).isThrownBy( + () -> load(ValidatedOnBeanJsr303Configuration.class, "description=")) + .withCauseInstanceOf(BindException.class); } @Test public void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedShouldFail() { - this.thrown.expectCause(Matchers.instanceOf(BindException.class)); - load(ValidatedNestedJsr303Properties.class, "properties.description="); + assertThatExceptionOfType(ConfigurationPropertiesBindException.class) + .isThrownBy(() -> load(ValidatedNestedJsr303Properties.class, + "properties.description=")) + .withCauseInstanceOf(BindException.class); } @Test public void loadWhenJsr303ConstraintDoesNotMatchOnNestedThatIsNotDirectlyAnnotatedButIsValidShouldFail() { - this.thrown.expectCause(Matchers.instanceOf(BindException.class)); - load(ValidatedValidNestedJsr303Properties.class); + assertThatExceptionOfType(ConfigurationPropertiesBindException.class) + .isThrownBy(() -> load(ValidatedValidNestedJsr303Properties.class)) + .withCauseInstanceOf(BindException.class); } @Test @@ -659,10 +664,10 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenConfigurationConverterIsNotQualifiedShouldNotConvert() { - this.thrown.expect(BeanCreationException.class); - this.thrown.expectCause(instanceOf(BindException.class)); - prepareConverterContext(NonQualifiedConverterConfiguration.class, - PersonProperties.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> prepareConverterContext( + NonQualifiedConverterConfiguration.class, PersonProperties.class)) + .withCauseInstanceOf(BindException.class); } @Test @@ -676,10 +681,11 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenGenericConfigurationConverterIsNotQualifiedShouldNotConvert() { - this.thrown.expect(BeanCreationException.class); - this.thrown.expectCause(instanceOf(BindException.class)); - prepareConverterContext(NonQualifiedGenericConverterConfiguration.class, - PersonProperties.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> prepareConverterContext( + NonQualifiedGenericConverterConfiguration.class, + PersonProperties.class)) + .withCauseInstanceOf(BindException.class); } @Test @@ -730,18 +736,21 @@ public class ConfigurationPropertiesTests { @Test public void loadWhenSetterThrowsValidationExceptionShouldFail() { - this.thrown.expect(BeanCreationException.class); - this.thrown.expectCause(instanceOf(BindException.class)); - load(WithSetterThatThrowsValidationExceptionProperties.class, "test.foo=spam"); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + () -> load(WithSetterThatThrowsValidationExceptionProperties.class, + "test.foo=spam")) + .withCauseInstanceOf(BindException.class); } @Test public void loadWhenFailsShouldIncludeAnnotationDetails() { removeSystemProperties(); - this.thrown.expectMessage("Could not bind properties to " - + "'ConfigurationPropertiesTests.IgnoreUnknownFieldsFalseProperties' : " - + "prefix=, ignoreInvalidFields=false, ignoreUnknownFields=false;"); - load(IgnoreUnknownFieldsFalseConfiguration.class, "name=foo", "bar=baz"); + assertThatExceptionOfType(ConfigurationPropertiesBindException.class) + .isThrownBy(() -> load(IgnoreUnknownFieldsFalseConfiguration.class, + "name=foo", "bar=baz")) + .withMessageContaining("Could not bind properties to " + + "'ConfigurationPropertiesTests.IgnoreUnknownFieldsFalseProperties' : " + + "prefix=, ignoreInvalidFields=false, ignoreUnknownFields=false;"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java index d0d1760e45c..c50077a28a8 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/PropertyMapperTests.java @@ -19,11 +19,10 @@ package org.springframework.boot.context.properties; import java.util.function.Supplier; import org.junit.Assert; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link PropertyMapper}. @@ -34,9 +33,6 @@ public class PropertyMapperTests { private PropertyMapper map = PropertyMapper.get(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void fromNullValue() { ExampleDest dest = new ExampleDest(); @@ -65,16 +61,16 @@ public class PropertyMapperTests { @Test public void fromWhenSupplierIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Supplier must not be null"); - this.map.from((Supplier) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.map.from((Supplier) null)) + .withMessageContaining("Supplier must not be null"); } @Test public void toWhenConsumerIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Consumer must not be null"); - this.map.from(() -> "").to(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.map.from(() -> "").to(null)) + .withMessageContaining("Consumer must not be null"); } @Test @@ -94,9 +90,9 @@ public class PropertyMapperTests { @Test public void asWhenAdapterIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Adapter must not be null"); - this.map.from(() -> "").as(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.map.from(() -> "").as(null)) + .withMessageContaining("Adapter must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java index 07cf1889b5a..a906aa9ccba 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindConverterTests.java @@ -23,9 +23,7 @@ import java.util.List; import java.util.function.Consumer; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -39,6 +37,8 @@ import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.GenericConversionService; 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.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; @@ -50,9 +50,6 @@ import static org.mockito.Mockito.verify; */ public class BindConverterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private Consumer propertyEditorInitializer; @@ -63,9 +60,9 @@ public class BindConverterTests { @Test public void createWhenConversionServiceIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ConversionService must not be null"); - BindConverter.get(null, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> BindConverter.get(null, null)) + .withMessageContaining("ConversionService must not be null"); } @Test @@ -191,8 +188,9 @@ public class BindConverterTests { public void convertWhenNotPropertyEditorAndConversionServiceCannotConvertShouldThrowException() { BindConverter bindConverter = BindConverter .get(ApplicationConversionService.getSharedInstance(), null); - this.thrown.expect(ConverterNotFoundException.class); - bindConverter.convert("test", ResolvableType.forClass(SampleType.class)); + assertThatExceptionOfType(ConverterNotFoundException.class) + .isThrownBy(() -> bindConverter.convert("test", + ResolvableType.forClass(SampleType.class))); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java index c81a38372c9..5b142c38b4c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindResultTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,13 +23,14 @@ import java.util.function.Function; import java.util.function.Supplier; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; 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.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -42,9 +43,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ public class BindResultTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private Consumer consumer; @@ -68,9 +66,8 @@ public class BindResultTests { @Test public void getWhenHasNoValueShouldThrowException() { BindResult result = BindResult.of(null); - this.thrown.expect(NoSuchElementException.class); - this.thrown.expectMessage("No value bound"); - result.get(); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> result.get()).withMessageContaining("No value bound"); } @Test @@ -88,9 +85,8 @@ public class BindResultTests { @Test public void ifBoundWhenConsumerIsNullShouldThrowException() { BindResult result = BindResult.of("foo"); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Consumer must not be null"); - result.ifBound(null); + assertThatIllegalArgumentException().isThrownBy(() -> result.ifBound(null)) + .withMessageContaining("Consumer must not be null"); } @Test @@ -110,9 +106,8 @@ public class BindResultTests { @Test public void mapWhenMapperIsNullShouldThrowException() { BindResult result = BindResult.of("foo"); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Mapper must not be null"); - result.map(null); + assertThatIllegalArgumentException().isThrownBy(() -> result.map(null)) + .withMessageContaining("Mapper must not be null"); } @Test @@ -158,9 +153,8 @@ public class BindResultTests { @Test public void orElseCreateWhenTypeIsNullShouldThrowException() { BindResult result = BindResult.of("foo"); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must not be null"); - result.orElseCreate(null); + assertThatIllegalArgumentException().isThrownBy(() -> result.orElseCreate(null)) + .withMessageContaining("Type must not be null"); } @Test @@ -184,8 +178,7 @@ public class BindResultTests { @Test public void orElseThrowWhenHasNoValueShouldThrowException() throws Exception { BindResult result = BindResult.of(null); - this.thrown.expect(IOException.class); - result.orElseThrow(IOException::new); + assertThatIOException().isThrownBy(() -> result.orElseThrow(IOException::new)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java index 798551c76b4..b258ea8b6f7 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BindableTests.java @@ -20,15 +20,14 @@ import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.context.annotation.Bean; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AnnotationUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -39,21 +38,18 @@ import static org.mockito.Mockito.mock; */ public class BindableTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void ofClassWhenTypeIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must not be null"); - Bindable.of((Class) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> Bindable.of((Class) null)) + .withMessageContaining("Type must not be null"); } @Test public void ofTypeWhenTypeIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must not be null"); - Bindable.of((ResolvableType) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> Bindable.of((ResolvableType) null)) + .withMessageContaining("Type must not be null"); } @Test @@ -90,10 +86,11 @@ public class BindableTests { @Test public void ofTypeWhenExistingValueIsNotInstanceOfTypeShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage( - "ExistingValue must be an instance of " + String.class.getName()); - Bindable.of(ResolvableType.forClass(String.class)).withExistingValue(123); + assertThatIllegalArgumentException() + .isThrownBy(() -> Bindable.of(ResolvableType.forClass(String.class)) + .withExistingValue(123)) + .withMessageContaining( + "ExistingValue must be an instance of " + String.class.getName()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java index 853b4d6ac51..f7efc74312c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/BinderTests.java @@ -26,11 +26,8 @@ import java.util.Map; import javax.validation.Validation; -import org.assertj.core.matcher.AssertionMatcher; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Answers; import org.mockito.InOrder; @@ -52,7 +49,8 @@ import org.springframework.validation.annotation.Validated; import org.springframework.validation.beanvalidation.SpringValidatorAdapter; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; @@ -68,9 +66,6 @@ import static org.mockito.Mockito.withSettings; */ public class BinderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private List sources = new ArrayList<>(); private Binder binder; @@ -82,24 +77,26 @@ public class BinderTests { @Test public void createWhenSourcesIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Sources must not be null"); - new Binder((Iterable) null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new Binder((Iterable) null)) + .withMessageContaining("Sources must not be null"); } @Test public void bindWhenNameIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Name must not be null"); - this.binder.bind((ConfigurationPropertyName) null, Bindable.of(String.class), - BindHandler.DEFAULT); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.binder.bind((ConfigurationPropertyName) null, + Bindable.of(String.class), BindHandler.DEFAULT)) + .withMessageContaining("Name must not be null"); } @Test public void bindWhenTargetIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Target must not be null"); - this.binder.bind(ConfigurationPropertyName.of("foo"), null, BindHandler.DEFAULT); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.binder.bind(ConfigurationPropertyName.of("foo"), + null, BindHandler.DEFAULT)) + .withMessageContaining("Target must not be null"); } @Test @@ -226,10 +223,11 @@ public class BinderTests { @Test public void bindWhenHasMalformedDateShouldThrowException() { - this.thrown.expectCause(instanceOf(ConversionFailedException.class)); this.sources.add(new MockConfigurationPropertySource("foo", "2014-04-01T01:30:00.000-05:00")); - this.binder.bind("foo", Bindable.of(LocalDate.class)); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("foo", Bindable.of(LocalDate.class))) + .withCauseInstanceOf(ConversionFailedException.class); } @Test @@ -252,18 +250,15 @@ public class BinderTests { source.put("foo.items", "bar,baz"); this.sources.add(source); Bindable target = Bindable.of(JavaBean.class); - this.thrown.expect(BindException.class); - this.thrown.expect(new AssertionMatcher() { + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("foo", target)) + .satisfies(this::noItemsSetterRequirements); + } - @Override - public void assertion(BindException ex) throws AssertionError { - assertThat(ex.getCause().getMessage()) - .isEqualTo("No setter found for property: items"); - assertThat(ex.getProperty()).isNull(); - } - - }); - this.binder.bind("foo", target); + private void noItemsSetterRequirements(BindException ex) { + assertThat(ex.getCause().getMessage()) + .isEqualTo("No setter found for property: items"); + assertThat(ex.getProperty()).isNull(); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java index a22baa07d57..4a41f908da5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/JavaBeanBinderTests.java @@ -25,11 +25,8 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.hamcrest.Matchers; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.context.properties.bind.handler.IgnoreErrorsBindHandler; import org.springframework.boot.context.properties.source.ConfigurationPropertyName; @@ -39,6 +36,7 @@ import org.springframework.boot.convert.Delimiter; import org.springframework.format.annotation.DateTimeFormat; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.entry; /** @@ -49,9 +47,6 @@ import static org.assertj.core.api.Assertions.entry; */ public class JavaBeanBinderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private List sources = new ArrayList<>(); private Binder binder; @@ -181,10 +176,10 @@ public class JavaBeanBinderTests { source.put("foo.list[0]", "foo-bar"); source.put("foo.list[2]", "bar-baz"); this.sources.add(source); - this.thrown.expect(BindException.class); - this.thrown.expectCause( - Matchers.instanceOf(UnboundConfigurationPropertiesException.class)); - this.binder.bind("foo", Bindable.of(ExampleListBean.class)); + assertThatExceptionOfType(BindException.class) + .isThrownBy( + () -> this.binder.bind("foo", Bindable.of(ExampleListBean.class))) + .withCauseInstanceOf(UnboundConfigurationPropertiesException.class); } @Test @@ -326,9 +321,8 @@ public class JavaBeanBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo.nested.foo", "bar"); this.sources.add(source); - this.thrown.expect(BindException.class); - this.binder.bind("foo", - Bindable.of(ExampleImmutableNestedBeanWithoutSetter.class)); + assertThatExceptionOfType(BindException.class).isThrownBy(() -> this.binder + .bind("foo", Bindable.of(ExampleImmutableNestedBeanWithoutSetter.class))); } @Test @@ -392,8 +386,8 @@ public class JavaBeanBinderTests { @Test public void bindToClassWhenPropertyCannotBeConvertedShouldThrowException() { this.sources.add(new MockConfigurationPropertySource("foo.int-value", "foo")); - this.thrown.expect(BindException.class); - this.binder.bind("foo", Bindable.of(ExampleValueBean.class)); + assertThatExceptionOfType(BindException.class).isThrownBy( + () -> this.binder.bind("foo", Bindable.of(ExampleValueBean.class))); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java index 074d18ef609..0f38befe519 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/MapBinderTests.java @@ -26,9 +26,7 @@ import java.util.Properties; import java.util.stream.Collectors; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Answers; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; @@ -47,6 +45,7 @@ import org.springframework.test.context.support.TestPropertySourceUtils; import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -78,9 +77,6 @@ public class MapBinderTests { private static final Bindable> STRING_ARRAY_MAP = Bindable .mapOf(String.class, String[].class); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private List sources = new ArrayList<>(); private Binder binder; @@ -566,8 +562,8 @@ public class MapBinderTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("foo", "a,b"); this.sources.add(source); - this.thrown.expect(BindException.class); - this.binder.bind("foo", STRING_STRING_MAP); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("foo", STRING_STRING_MAP)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java index 90d5253b244..6407d6c8d26 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolverTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.context.properties.bind; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; @@ -30,6 +28,7 @@ import org.springframework.core.env.PropertySources; import org.springframework.util.PropertyPlaceholderHelper; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link PropertySourcesPlaceholdersResolver}. @@ -41,14 +40,12 @@ public class PropertySourcesPlaceholdersResolverTests { private PropertySourcesPlaceholdersResolver resolver; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void placeholderResolverIfEnvironmentNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Environment must not be null"); - new PropertySourcesPlaceholdersResolver((Environment) null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new PropertySourcesPlaceholdersResolver((Environment) null)) + .withMessageContaining("Environment must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java index 24afe5503c4..332feac9b78 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,9 +20,7 @@ import java.util.ArrayList; import java.util.List; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.context.properties.bind.BindException; import org.springframework.boot.context.properties.bind.Bindable; @@ -31,6 +29,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.assertThatExceptionOfType; /** * Tests for {@link IgnoreErrorsBindHandler}. @@ -40,9 +39,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class IgnoreErrorsBindHandlerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private List sources = new ArrayList<>(); private Binder binder; @@ -57,8 +53,8 @@ public class IgnoreErrorsBindHandlerTests { @Test public void bindWhenNotIgnoringErrorsShouldFail() { - this.thrown.expect(BindException.class); - this.binder.bind("example", Bindable.of(Example.class)); + assertThatExceptionOfType(BindException.class).isThrownBy( + () -> this.binder.bind("example", Bindable.of(Example.class))); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java index cdf9e5e407f..97582ca0c3c 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/handler/IgnoreTopLevelConverterNotFoundBindHandlerTests.java @@ -21,9 +21,7 @@ import java.util.List; import java.util.Map; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.context.properties.bind.BindException; import org.springframework.boot.context.properties.bind.Bindable; @@ -32,7 +30,7 @@ import org.springframework.boot.context.properties.source.ConfigurationPropertyS import org.springframework.boot.context.properties.source.MockConfigurationPropertySource; import org.springframework.core.convert.ConverterNotFoundException; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link IgnoreTopLevelConverterNotFoundBindHandler}. @@ -41,9 +39,6 @@ import static org.hamcrest.Matchers.instanceOf; */ public class IgnoreTopLevelConverterNotFoundBindHandlerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private List sources = new ArrayList<>(); private Binder binder; @@ -58,8 +53,9 @@ public class IgnoreTopLevelConverterNotFoundBindHandlerTests { @Test public void bindWhenHandlerNotPresentShouldFail() { - this.thrown.expectCause(instanceOf(ConverterNotFoundException.class)); - this.binder.bind("example", Bindable.of(Example.class)); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class))) + .withCauseInstanceOf(ConverterNotFoundException.class); } @Test @@ -73,9 +69,10 @@ public class IgnoreTopLevelConverterNotFoundBindHandlerTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.foo", "1"); this.sources.add(source); - this.thrown.expectCause(instanceOf(IllegalStateException.class)); - this.binder.bind("example", Bindable.of(Example.class), - new IgnoreTopLevelConverterNotFoundBindHandler()); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), + new IgnoreTopLevelConverterNotFoundBindHandler())) + .withCauseInstanceOf(IllegalStateException.class); } @Test @@ -83,10 +80,10 @@ public class IgnoreTopLevelConverterNotFoundBindHandlerTests { MockConfigurationPropertySource source = new MockConfigurationPropertySource(); source.put("example.map", "hello"); this.sources.add(source); - this.thrown.expect(BindException.class); - this.thrown.expectCause(instanceOf(ConverterNotFoundException.class)); - this.binder.bind("example", Bindable.of(Example.class), - new IgnoreTopLevelConverterNotFoundBindHandler()); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("example", Bindable.of(Example.class), + new IgnoreTopLevelConverterNotFoundBindHandler())) + .withCauseInstanceOf(ConverterNotFoundException.class); } public static class Example { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java index 8abe06e9984..59868943370 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/BindValidationExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,11 +16,10 @@ package org.springframework.boot.context.properties.bind.validation; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -31,14 +30,11 @@ import static org.mockito.Mockito.mock; */ public class BindValidationExceptionTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenValidationErrorsIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ValidationErrors must not be null"); - new BindValidationException(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new BindValidationException(null)) + .withMessageContaining("ValidationErrors must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java index 1c27f804e78..db5780e98f6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationBindHandlerTests.java @@ -25,9 +25,7 @@ import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.context.properties.bind.BindException; import org.springframework.boot.context.properties.bind.Bindable; @@ -43,7 +41,7 @@ import org.springframework.validation.annotation.Validated; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link ValidationBindHandler}. @@ -53,9 +51,6 @@ import static org.hamcrest.Matchers.instanceOf; */ public class ValidationBindHandlerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private List sources = new ArrayList<>(); private ValidationBindHandler handler; @@ -81,18 +76,19 @@ public class ValidationBindHandlerTests { @Test public void bindShouldFailWithHandler() { this.sources.add(new MockConfigurationPropertySource("foo.age", 4)); - this.thrown.expect(BindException.class); - this.thrown.expectCause(instanceOf(BindValidationException.class)); - this.binder.bind("foo", Bindable.of(ExampleValidatedBean.class), this.handler); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("foo", + Bindable.of(ExampleValidatedBean.class), this.handler)) + .withCauseInstanceOf(BindValidationException.class); } @Test public void bindShouldValidateNestedProperties() { this.sources.add(new MockConfigurationPropertySource("foo.nested.age", 4)); - this.thrown.expect(BindException.class); - this.thrown.expectCause(instanceOf(BindValidationException.class)); - this.binder.bind("foo", Bindable.of(ExampleValidatedWithNestedBean.class), - this.handler); + assertThatExceptionOfType(BindException.class) + .isThrownBy(() -> this.binder.bind("foo", + Bindable.of(ExampleValidatedWithNestedBean.class), this.handler)) + .withCauseInstanceOf(BindValidationException.class); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java index 699069e7a4e..28643775916 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/validation/ValidationErrorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -22,9 +22,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.context.properties.source.ConfigurationProperty; import org.springframework.boot.context.properties.source.ConfigurationPropertyName; @@ -34,6 +32,7 @@ import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ValidationErrors}. @@ -46,28 +45,28 @@ public class ValidationErrorsTests { private static final ConfigurationPropertyName NAME = ConfigurationPropertyName .of("foo"); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenNameIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Name must not be null"); - new ValidationErrors(null, Collections.emptySet(), Collections.emptyList()); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ValidationErrors(null, Collections.emptySet(), + Collections.emptyList())) + .withMessageContaining("Name must not be null"); } @Test public void createWhenBoundPropertiesIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("BoundProperties must not be null"); - new ValidationErrors(NAME, null, Collections.emptyList()); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new ValidationErrors(NAME, null, Collections.emptyList())) + .withMessageContaining("BoundProperties must not be null"); } @Test public void createWhenErrorsIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Errors must not be null"); - new ValidationErrors(NAME, Collections.emptySet(), null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new ValidationErrors(NAME, Collections.emptySet(), null)) + .withMessageContaining("Errors must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java index e7a41d7a3db..718436aceae 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameAliasesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,11 +16,10 @@ package org.springframework.boot.context.properties.source; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ConfigurationPropertyNameAliases}. @@ -30,14 +29,11 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ConfigurationPropertyNameAliasesTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWithStringWhenNullNameShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Name must not be null"); - new ConfigurationPropertyNameAliases((String) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ConfigurationPropertyNameAliases((String) null)) + .withMessageContaining("Name must not be null"); } @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 576acc4904e..acf1bcd69d6 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 @@ -21,13 +21,13 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.context.properties.source.ConfigurationPropertyName.Form; 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; /** @@ -39,42 +39,39 @@ import static org.assertj.core.api.Assertions.fail; */ public class ConfigurationPropertyNameTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void ofNameShouldNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Name must not be null"); - ConfigurationPropertyName.of(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> ConfigurationPropertyName.of(null)) + .withMessageContaining("Name must not be null"); } @Test public void ofNameShouldNotStartWithDash() { - this.thrown.expect(InvalidConfigurationPropertyNameException.class); - this.thrown.expectMessage("is not valid"); - ConfigurationPropertyName.of("-foo"); + assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) + .isThrownBy(() -> ConfigurationPropertyName.of("-foo")) + .withMessageContaining("is not valid"); } @Test public void ofNameShouldNotStartWithDot() { - this.thrown.expect(InvalidConfigurationPropertyNameException.class); - this.thrown.expectMessage("is not valid"); - ConfigurationPropertyName.of(".foo"); + assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) + .isThrownBy(() -> ConfigurationPropertyName.of(".foo")) + .withMessageContaining("is not valid"); } @Test public void ofNameShouldNotEndWithDot() { - this.thrown.expect(InvalidConfigurationPropertyNameException.class); - this.thrown.expectMessage("is not valid"); - ConfigurationPropertyName.of("foo."); + assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) + .isThrownBy(() -> ConfigurationPropertyName.of("foo.")) + .withMessageContaining("is not valid"); } @Test public void ofNameShouldNotContainUppercase() { - this.thrown.expect(InvalidConfigurationPropertyNameException.class); - this.thrown.expectMessage("is not valid"); - ConfigurationPropertyName.of("fOo"); + assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) + .isThrownBy(() -> ConfigurationPropertyName.of("fOo")) + .withMessageContaining("is not valid"); } @Test @@ -165,23 +162,23 @@ public class ConfigurationPropertyNameTests { @Test public void ofNameWhenMissingCloseBracket() { - this.thrown.expect(InvalidConfigurationPropertyNameException.class); - this.thrown.expectMessage("is not valid"); - ConfigurationPropertyName.of("[bar"); + assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) + .isThrownBy(() -> ConfigurationPropertyName.of("[bar")) + .withMessageContaining("is not valid"); } @Test public void ofNameWhenMissingOpenBracket() { - this.thrown.expect(InvalidConfigurationPropertyNameException.class); - this.thrown.expectMessage("is not valid"); - ConfigurationPropertyName.of("bar]"); + assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) + .isThrownBy(() -> ConfigurationPropertyName.of("bar]")) + .withMessageContaining("is not valid"); } @Test public void ofNameWhenMultipleMismatchedBrackets() { - this.thrown.expect(InvalidConfigurationPropertyNameException.class); - this.thrown.expectMessage("is not valid"); - ConfigurationPropertyName.of("[a[[[b]ar]"); + assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) + .isThrownBy(() -> ConfigurationPropertyName.of("[a[[[b]ar]")) + .withMessageContaining("is not valid"); } @Test @@ -194,9 +191,9 @@ public class ConfigurationPropertyNameTests { @Test public void ofNameWithWhitespaceInName() { - this.thrown.expect(InvalidConfigurationPropertyNameException.class); - this.thrown.expectMessage("is not valid"); - ConfigurationPropertyName.of("foo. bar"); + assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) + .isThrownBy(() -> ConfigurationPropertyName.of("foo. bar")) + .withMessageContaining("is not valid"); } @Test @@ -228,9 +225,9 @@ public class ConfigurationPropertyNameTests { @Test public void adaptWhenNameIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Name must not be null"); - ConfigurationPropertyName.adapt(null, '.'); + assertThatIllegalArgumentException() + .isThrownBy(() -> ConfigurationPropertyName.adapt(null, '.')) + .withMessageContaining("Name must not be null"); } @Test @@ -427,16 +424,16 @@ public class ConfigurationPropertyNameTests { @Test public void appendWhenElementNameIsNotValidShouldThrowException() { - this.thrown.expect(InvalidConfigurationPropertyNameException.class); - this.thrown.expectMessage("Configuration property name '-bar' is not valid"); - ConfigurationPropertyName.of("foo").append("-bar"); + assertThatExceptionOfType(InvalidConfigurationPropertyNameException.class) + .isThrownBy(() -> ConfigurationPropertyName.of("foo").append("-bar")) + .withMessageContaining("Configuration property name '-bar' is not valid"); } @Test public void appendWhenElementNameMultiDotShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Element value 'bar.baz' must be a single item"); - ConfigurationPropertyName.of("foo").append("bar.baz"); + assertThatIllegalArgumentException() + .isThrownBy(() -> ConfigurationPropertyName.of("foo").append("bar.baz")) + .withMessageContaining("Element value 'bar.baz' must be a single item"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java index bbaaa71656c..5fa0a8cab55 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyStateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -20,11 +20,10 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ConfigurationPropertyState}. @@ -33,21 +32,18 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ConfigurationPropertyStateTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void searchWhenIterableIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Source must not be null"); - ConfigurationPropertyState.search(null, (e) -> true); + assertThatIllegalArgumentException() + .isThrownBy(() -> ConfigurationPropertyState.search(null, (e) -> true)) + .withMessageContaining("Source must not be null"); } @Test public void searchWhenPredicateIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Predicate must not be null"); - ConfigurationPropertyState.search(Collections.emptyList(), null); + assertThatIllegalArgumentException().isThrownBy( + () -> ConfigurationPropertyState.search(Collections.emptyList(), null)) + .withMessageContaining("Predicate must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java index 9732d1518a0..cf4262c0c10 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -16,14 +16,13 @@ package org.springframework.boot.context.properties.source; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.origin.Origin; import org.springframework.boot.origin.OriginProvider; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -37,21 +36,18 @@ public class ConfigurationPropertyTests { private static final ConfigurationPropertyName NAME = ConfigurationPropertyName .of("foo"); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenNameIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Name must not be null"); - new ConfigurationProperty(null, "bar", null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ConfigurationProperty(null, "bar", null)) + .withMessageContaining("Name must not be null"); } @Test public void createWhenValueIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Value must not be null"); - new ConfigurationProperty(NAME, null, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ConfigurationProperty(NAME, null, null)) + .withMessageContaining("Value must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java index 62bff37b4b8..51e2b57f59d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/FilteredConfigurationPropertiesSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,12 +18,11 @@ package org.springframework.boot.context.properties.source; import java.util.Objects; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Answers; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings; @@ -36,22 +35,19 @@ import static org.mockito.Mockito.withSettings; */ public class FilteredConfigurationPropertiesSourceTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenSourceIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Source must not be null"); - new FilteredConfigurationPropertiesSource(null, Objects::nonNull); + assertThatIllegalArgumentException().isThrownBy( + () -> new FilteredConfigurationPropertiesSource(null, Objects::nonNull)) + .withMessageContaining("Source must not be null"); } @Test public void createWhenFilterIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Filter must not be null"); - new FilteredConfigurationPropertiesSource(new MockConfigurationPropertySource(), - null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new FilteredConfigurationPropertiesSource( + new MockConfigurationPropertySource(), null)) + .withMessageContaining("Filter must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java index 7f171f5f7b3..7bc05a938e0 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/MapConfigurationPropertySourceTests.java @@ -19,11 +19,10 @@ package org.springframework.boot.context.properties.source; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link MapConfigurationPropertySource}. @@ -33,14 +32,11 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class MapConfigurationPropertySourceTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenMapIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Map must not be null"); - new MapConfigurationPropertySource(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new MapConfigurationPropertySource(null)) + .withMessageContaining("Map must not be null"); } @Test @@ -55,10 +51,9 @@ public class MapConfigurationPropertySourceTests { @Test public void putAllWhenMapIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Map must not be null"); MapConfigurationPropertySource source = new MapConfigurationPropertySource(); - source.putAll(null); + assertThatIllegalArgumentException().isThrownBy(() -> source.putAll(null)) + .withMessageContaining("Map must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java index 02d4cbcde28..7e112dc8174 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourceTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.context.properties.source; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.origin.Origin; import org.springframework.boot.origin.OriginLookup; @@ -29,6 +27,7 @@ import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -39,21 +38,20 @@ import static org.mockito.Mockito.mock; */ public class SpringConfigurationPropertySourceTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenPropertySourceIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("PropertySource must not be null"); - new SpringConfigurationPropertySource(null, mock(PropertyMapper.class), null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SpringConfigurationPropertySource(null, + mock(PropertyMapper.class), null)) + .withMessageContaining("PropertySource must not be null"); } @Test public void createWhenMapperIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Mapper must not be null"); - new SpringConfigurationPropertySource(mock(PropertySource.class), null, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SpringConfigurationPropertySource( + mock(PropertySource.class), null, null)) + .withMessageContaining("Mapper must not be null"); } @Test @@ -113,9 +111,9 @@ public class SpringConfigurationPropertySourceTests { @Test public void fromWhenPropertySourceIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Source must not be null"); - SpringConfigurationPropertySource.from(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> SpringConfigurationPropertySource.from(null)) + .withMessageContaining("Source must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java index b1586b537a2..6890a35753d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySourcesTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.context.properties.source; import java.util.Collections; import java.util.Iterator; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; @@ -31,6 +29,7 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.core.env.SystemEnvironmentPropertySource; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link SpringConfigurationPropertySources}. @@ -40,14 +39,11 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class SpringConfigurationPropertySourcesTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenPropertySourcesIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Sources must not be null"); - new SpringConfigurationPropertySources(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SpringConfigurationPropertySources(null)) + .withMessageContaining("Sources must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java index f75fe647f4a..f4fc744b345 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SpringIterableConfigurationPropertySourceTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.context.properties.source; import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.origin.Origin; import org.springframework.boot.origin.OriginLookup; @@ -30,6 +28,7 @@ import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -41,22 +40,20 @@ import static org.mockito.Mockito.mock; */ public class SpringIterableConfigurationPropertySourceTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenPropertySourceIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("PropertySource must not be null"); - new SpringIterableConfigurationPropertySource(null, mock(PropertyMapper.class)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SpringIterableConfigurationPropertySource(null, + mock(PropertyMapper.class))) + .withMessageContaining("PropertySource must not be null"); } @Test public void createWhenMapperIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Mapper must not be null"); - new SpringIterableConfigurationPropertySource( - mock(EnumerablePropertySource.class), null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SpringIterableConfigurationPropertySource( + mock(EnumerablePropertySource.class), null)) + .withMessageContaining("Mapper must not be null"); } @Test 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 eb3b2bfc3b9..200db849f96 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 @@ -19,11 +19,10 @@ package org.springframework.boot.convert; import java.time.Duration; import java.time.temporal.ChronoUnit; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.fail; /** @@ -33,14 +32,11 @@ import static org.junit.Assert.fail; */ public class DurationStyleTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void detectAndParseWhenValueIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Value must not be null"); - DurationStyle.detectAndParse(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> DurationStyle.detectAndParse(null)) + .withMessageContaining("Value must not be null"); } @Test @@ -148,9 +144,9 @@ public class DurationStyleTests { @Test public void detectAndParseWhenBadFormatShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("'10foo' is not a valid duration"); - DurationStyle.detectAndParse("10foo"); + assertThatIllegalArgumentException() + .isThrownBy(() -> DurationStyle.detectAndParse("10foo")) + .withMessageContaining("'10foo' is not a valid duration"); } @Test @@ -183,9 +179,8 @@ public class DurationStyleTests { @Test public void detectWhenUnknownShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("'bad' is not a valid duration"); - DurationStyle.detect("bad"); + assertThatIllegalArgumentException().isThrownBy(() -> DurationStyle.detect("bad")) + .withMessageContaining("'bad' is not a valid duration"); } @Test @@ -228,9 +223,9 @@ public class DurationStyleTests { @Test public void parseIso8601WhenSimpleShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("'10d' is not a valid ISO-8601 duration"); - DurationStyle.ISO8601.parse("10d"); + assertThatIllegalArgumentException() + .isThrownBy(() -> DurationStyle.ISO8601.parse("10d")) + .withMessageContaining("'10d' is not a valid ISO-8601 duration"); } @Test @@ -259,9 +254,9 @@ public class DurationStyleTests { @Test public void parseSimpleWhenIso8601ShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("'PT10H' is not a valid simple duration"); - DurationStyle.SIMPLE.parse("PT10H"); + assertThatIllegalArgumentException() + .isThrownBy(() -> DurationStyle.SIMPLE.parse("PT10H")) + .withMessageContaining("'PT10H' is not a valid simple duration"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java index 434b57f6872..7f37d80b8fd 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/InetAddressFormatterTests.java @@ -20,9 +20,7 @@ import java.net.InetAddress; import java.net.UnknownHostException; import org.junit.AssumptionViolatedException; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @@ -31,6 +29,7 @@ import org.springframework.core.convert.ConversionFailedException; import org.springframework.core.convert.ConversionService; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link InetAddressFormatter}. @@ -40,9 +39,6 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class InetAddressFormatterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final ConversionService conversionService; public InetAddressFormatterTests(String name, ConversionService conversionService) { @@ -70,8 +66,8 @@ public class InetAddressFormatterTests { public void convertFromStringToInetAddressWhenHostDoesNotExistShouldThrowException() { String missingDomain = "ireallydontexist.example.com"; assumeResolves(missingDomain, false); - this.thrown.expect(ConversionFailedException.class); - this.conversionService.convert(missingDomain, InetAddress.class); + assertThatExceptionOfType(ConversionFailedException.class).isThrownBy( + () -> this.conversionService.convert(missingDomain, InetAddress.class)); } private void assumeResolves(String host, boolean expectedToResolve) { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java index 52b11d6b208..d3ecd7487e2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDataSizeConverterTests.java @@ -16,9 +16,7 @@ package org.springframework.boot.convert; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @@ -30,6 +28,7 @@ import org.springframework.util.unit.DataSize; import org.springframework.util.unit.DataUnit; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link StringToDataSizeConverter}. @@ -39,9 +38,6 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class StringToDataSizeConverterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final ConversionService conversionService; public StringToDataSizeConverterTests(String name, @@ -102,9 +98,9 @@ public class StringToDataSizeConverterTests { @Test public void convertWhenBadFormatShouldThrowException() { - this.thrown.expect(ConversionFailedException.class); - this.thrown.expectMessage("'10WB' is not a valid data size"); - convert("10WB"); + assertThatExceptionOfType(ConversionFailedException.class) + .isThrownBy(() -> convert("10WB")) + .withMessageContaining("'10WB' is not a valid data size"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java index c6bb5ddf8a1..a290343528a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/convert/StringToDurationConverterTests.java @@ -19,9 +19,7 @@ package org.springframework.boot.convert; import java.time.Duration; import java.time.temporal.ChronoUnit; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @@ -31,6 +29,7 @@ import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link StringToDurationConverter}. @@ -40,9 +39,6 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class StringToDurationConverterTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final ConversionService conversionService; public StringToDurationConverterTests(String name, @@ -137,15 +133,15 @@ public class StringToDurationConverterTests { @Test public void convertWhenBadFormatShouldThrowException() { - this.thrown.expect(ConversionFailedException.class); - this.thrown.expectMessage("'10foo' is not a valid duration"); - convert("10foo"); + assertThatExceptionOfType(ConversionFailedException.class) + .isThrownBy(() -> convert("10foo")) + .withMessageContaining("'10foo' is not a valid duration"); } @Test public void convertWhenStyleMismatchShouldThrowException() { - this.thrown.expect(ConversionFailedException.class); - convert("10s", null, DurationStyle.ISO8601); + assertThatExceptionOfType(ConversionFailedException.class) + .isThrownBy(() -> convert("10s", null, DurationStyle.ISO8601)); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java index ecab68d95fe..65eca9c4eac 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/NoSnakeYamlPropertySourceLoaderTests.java @@ -16,15 +16,15 @@ package org.springframework.boot.env; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import org.springframework.core.io.ByteArrayResource; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; + /** * Tests for {@link YamlPropertySourceLoader} when snakeyaml is not available. * @@ -34,19 +34,16 @@ import org.springframework.core.io.ByteArrayResource; @ClassPathExclusions("snakeyaml-*.jar") public class NoSnakeYamlPropertySourceLoaderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); @Test public void load() throws Exception { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "Attempted to load resource but snakeyaml was not found on the classpath"); ByteArrayResource resource = new ByteArrayResource( "foo:\n bar: spam".getBytes()); - this.loader.load("resource", resource); + assertThatIllegalStateException() + .isThrownBy(() -> this.loader.load("resource", resource)) + .withMessageContaining( + "Attempted to load resource but snakeyaml was not found on the classpath"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java index 74dadf8761c..253dc439d9d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/OriginTrackedPropertiesLoaderTests.java @@ -20,9 +20,7 @@ import java.util.Map; import java.util.Properties; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.origin.OriginTrackedValue; import org.springframework.boot.origin.TextResourceOrigin; @@ -30,6 +28,7 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link OriginTrackedPropertiesLoader}. @@ -39,9 +38,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class OriginTrackedPropertiesLoaderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ClassPathResource resource; private Map properties; @@ -93,10 +89,11 @@ public class OriginTrackedPropertiesLoaderTests { @Test public void getMalformedUnicodeProperty() throws Exception { // gh-12716 - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Malformed \\uxxxx encoding"); - new OriginTrackedPropertiesLoader(new ClassPathResource( - "test-properties-malformed-unicode.properties", getClass())).load(); + ClassPathResource resource = new ClassPathResource( + "test-properties-malformed-unicode.properties", getClass()); + assertThatIllegalStateException() + .isThrownBy(() -> new OriginTrackedPropertiesLoader(resource).load()) + .withMessageContaining("Malformed \\uxxxx encoding"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java index e19cca9c70f..64ec70fe998 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/env/SpringApplicationJsonEnvironmentPostProcessorTests.java @@ -16,9 +16,7 @@ package org.springframework.boot.env; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.json.JsonParseException; import org.springframework.boot.origin.PropertySourceOrigin; @@ -28,6 +26,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.assertThatExceptionOfType; /** * Tests for {@link SpringApplicationJsonEnvironmentPostProcessor}. @@ -39,21 +38,18 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class SpringApplicationJsonEnvironmentPostProcessorTests { - @Rule - public ExpectedException expected = ExpectedException.none(); - private SpringApplicationJsonEnvironmentPostProcessor processor = new SpringApplicationJsonEnvironmentPostProcessor(); private ConfigurableEnvironment environment = new StandardEnvironment(); @Test public void error() { - this.expected.expect(JsonParseException.class); - this.expected.expectMessage("Cannot parse JSON"); assertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty(); TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json=foo:bar"); - this.processor.postProcessEnvironment(this.environment, null); + assertThatExceptionOfType(JsonParseException.class).isThrownBy( + () -> this.processor.postProcessEnvironment(this.environment, null)) + .withMessageContaining("Cannot parse JSON"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java index ba4e7606ef5..ae2183ae6eb 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/info/InfoPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,13 +18,12 @@ package org.springframework.boot.info; import java.util.Properties; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.env.PropertySource; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link InfoProperties}. @@ -33,9 +32,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class InfoPropertiesTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void inputIsImmutable() { Properties p = new Properties(); @@ -64,9 +60,8 @@ public class InfoPropertiesTests { Properties p = new Properties(); p.put("foo", "bar"); InfoProperties infoProperties = new InfoProperties(p); - - this.thrown.expect(UnsupportedOperationException.class); - infoProperties.iterator().remove(); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(infoProperties.iterator()::remove); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java index e4ce9eb62a5..f353667b3c3 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonObjectDeserializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,13 +27,13 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.node.NullNode; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.jackson.NameAndAgeJsonComponent.Deserializer; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -44,9 +44,6 @@ import static org.mockito.Mockito.mock; */ public class JsonObjectDeserializerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private TestJsonObjectDeserializer testDeserializer = new TestJsonObjectDeserializer<>(); @Test @@ -70,9 +67,9 @@ public class JsonObjectDeserializerTests { @Test public void nullSafeValueWhenClassIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Type must not be null"); - this.testDeserializer.testNullSafeValue(mock(JsonNode.class), null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.testDeserializer.testNullSafeValue(mock(JsonNode.class), null)) + .withMessageContaining("Type must not be null"); } @Test @@ -151,35 +148,36 @@ public class JsonObjectDeserializerTests { @Test public void nullSafeValueWhenClassIsUnknownShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Unsupported value type java.io.InputStream"); - this.testDeserializer.testNullSafeValue(mock(JsonNode.class), InputStream.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.testDeserializer + .testNullSafeValue(mock(JsonNode.class), InputStream.class)) + .withMessageContaining("Unsupported value type java.io.InputStream"); } @Test public void getRequiredNodeWhenTreeIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Tree must not be null"); - this.testDeserializer.testGetRequiredNode(null, "test"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.testDeserializer.testGetRequiredNode(null, "test")) + .withMessageContaining("Tree must not be null"); } @Test public void getRequiredNodeWhenNodeIsNullShouldThrowException() { JsonNode tree = mock(JsonNode.class); given(tree.get("test")).willReturn(null); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Missing JSON field 'test'"); - this.testDeserializer.testGetRequiredNode(tree, "test"); + assertThatIllegalStateException() + .isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) + .withMessageContaining("Missing JSON field 'test'"); } @Test public void getRequiredNodeWhenNodeIsNullNodeShouldThrowException() { JsonNode tree = mock(JsonNode.class); given(tree.get("test")).willReturn(NullNode.instance); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Missing JSON field 'test'"); - this.testDeserializer.testGetRequiredNode(tree, "test"); + assertThatIllegalStateException() + .isThrownBy(() -> this.testDeserializer.testGetRequiredNode(tree, "test")) + .withMessageContaining("Missing JSON field 'test'"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java index edd85a708b4..08c6d8767f2 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DatabaseDriverTests.java @@ -16,11 +16,10 @@ package org.springframework.boot.jdbc; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DatabaseDriver}. @@ -31,9 +30,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class DatabaseDriverTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void classNameForKnownDatabase() { String driverClassName = DatabaseDriver @@ -56,9 +52,9 @@ public class DatabaseDriverTests { @Test public void failureOnMalformedJdbcUrl() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("URL must start with"); - DatabaseDriver.fromJdbcUrl("malformed:url"); + assertThatIllegalArgumentException() + .isThrownBy(() -> DatabaseDriver.fromJdbcUrl("malformed:url")) + .withMessageContaining("URL must start with"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java index 73c9996c6bd..9e6d03f072f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnectionTests.java @@ -16,11 +16,10 @@ package org.springframework.boot.jdbc; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link EmbeddedDatabaseConnection}. @@ -29,9 +28,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class EmbeddedDatabaseConnectionTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - @Test public void h2CustomDatabaseName() { assertThat(EmbeddedDatabaseConnection.H2.getUrl("mydb")) @@ -52,16 +48,16 @@ public class EmbeddedDatabaseConnectionTests { @Test public void getUrlWithNullDatabaseName() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("DatabaseName must not be empty"); - EmbeddedDatabaseConnection.HSQL.getUrl(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> EmbeddedDatabaseConnection.HSQL.getUrl(null)) + .withMessageContaining("DatabaseName must not be empty"); } @Test public void getUrlWithEmptyDatabaseName() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("DatabaseName must not be empty"); - EmbeddedDatabaseConnection.HSQL.getUrl(" "); + assertThatIllegalArgumentException() + .isThrownBy(() -> EmbeddedDatabaseConnection.HSQL.getUrl(" ")) + .withMessageContaining("DatabaseName must not be empty"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java index e43d45369bc..78a2b993eed 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/AbstractJsonParserTests.java @@ -19,11 +19,10 @@ package org.springframework.boot.json; import java.util.List; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Base for {@link JsonParser} tests. @@ -34,9 +33,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public abstract class AbstractJsonParserTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final JsonParser parser = getParser(); protected abstract JsonParser getParser(); @@ -110,38 +106,38 @@ public abstract class AbstractJsonParserTests { @Test public void mapWithNullThrowsARuntimeException() { - this.thrown.expect(RuntimeException.class); - this.parser.parseMap(null); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.parser.parseMap(null)); } @Test public void listWithNullThrowsARuntimeException() { - this.thrown.expect(RuntimeException.class); - this.parser.parseList(null); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.parser.parseList(null)); } @Test public void mapWithEmptyStringThrowsARuntimeException() { - this.thrown.expect(RuntimeException.class); - this.parser.parseMap(""); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.parser.parseMap("")); } @Test public void listWithEmptyStringThrowsARuntimeException() { - this.thrown.expect(RuntimeException.class); - this.parser.parseList(""); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.parser.parseList("")); } @Test public void mapWithListThrowsARuntimeException() { - this.thrown.expect(RuntimeException.class); - this.parser.parseMap("[]"); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.parser.parseMap("[]")); } @Test public void listWithMapThrowsARuntimeException() { - this.thrown.expect(RuntimeException.class); - this.parser.parseList("{}"); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.parser.parseList("{}")); } @Test @@ -160,14 +156,14 @@ public abstract class AbstractJsonParserTests { @Test public void mapWithLeadingWhitespaceListThrowsARuntimeException() { - this.thrown.expect(RuntimeException.class); - this.parser.parseMap("\n\t[]"); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.parser.parseMap("\n\t[]")); } @Test public void listWithLeadingWhitespaceMapThrowsARuntimeException() { - this.thrown.expect(RuntimeException.class); - this.parser.parseList("\n\t{}"); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.parser.parseList("\n\t{}")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java index 96ca83a5b05..2b80993ea7e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/logging/logback/SpringProfileActionTests.java @@ -67,7 +67,7 @@ public class SpringProfileActionTests { this.action.begin(this.interpretationContext, null, this.attributes); ArgumentCaptor profiles = ArgumentCaptor.forClass(Profiles.class); verify(this.environment).acceptsProfiles(profiles.capture()); - List profileNames = new ArrayList(); + List profileNames = new ArrayList<>(); profiles.getValue().matches((profile) -> { profileNames.add(profile); return false; @@ -82,7 +82,7 @@ public class SpringProfileActionTests { this.action.begin(this.interpretationContext, null, this.attributes); ArgumentCaptor profiles = ArgumentCaptor.forClass(Profiles.class); verify(this.environment).acceptsProfiles(profiles.capture()); - List profileNames = new ArrayList(); + List profileNames = new ArrayList<>(); profiles.getValue().matches((profile) -> { profileNames.add(profile); return false; @@ -98,7 +98,7 @@ public class SpringProfileActionTests { this.action.begin(this.interpretationContext, null, this.attributes); ArgumentCaptor profiles = ArgumentCaptor.forClass(Profiles.class); verify(this.environment).acceptsProfiles(profiles.capture()); - List profileNames = new ArrayList(); + List profileNames = new ArrayList<>(); profiles.getValue().matches((profile) -> { profileNames.add(profile); return false; @@ -116,7 +116,7 @@ public class SpringProfileActionTests { this.action.begin(this.interpretationContext, null, this.attributes); ArgumentCaptor profiles = ArgumentCaptor.forClass(Profiles.class); verify(this.environment).acceptsProfiles(profiles.capture()); - List profileNames = new ArrayList(); + List profileNames = new ArrayList<>(); profiles.getValue().matches((profile) -> { profileNames.add(profile); return false; diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java index c7fada14ef6..e6d3836bca9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/PropertySourceOriginTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -18,14 +18,13 @@ package org.springframework.boot.origin; import java.util.HashMap; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings; @@ -37,28 +36,27 @@ import static org.mockito.Mockito.withSettings; */ public class PropertySourceOriginTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenPropertySourceIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("PropertySource must not be null"); - new PropertySourceOrigin(null, "name"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PropertySourceOrigin(null, "name")) + .withMessageContaining("PropertySource must not be null"); } @Test public void createWhenPropertyNameIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("PropertyName must not be empty"); - new PropertySourceOrigin(mock(PropertySource.class), null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new PropertySourceOrigin(mock(PropertySource.class), null)) + .withMessageContaining("PropertyName must not be empty"); } @Test public void createWhenPropertyNameIsEmptyShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("PropertyName must not be empty"); - new PropertySourceOrigin(mock(PropertySource.class), ""); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new PropertySourceOrigin(mock(PropertySource.class), "")) + .withMessageContaining("PropertyName must not be empty"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java index 07e7ed40899..728899df98b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/origin/SystemEnvironmentOriginTests.java @@ -16,11 +16,10 @@ package org.springframework.boot.origin; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link SystemEnvironmentOrigin}. @@ -29,19 +28,16 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class SystemEnvironmentOriginTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenPropertyIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - new SystemEnvironmentOrigin(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SystemEnvironmentOrigin(null)); } @Test public void createWhenPropertyNameIsEmptyShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - new SystemEnvironmentOrigin(""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new SystemEnvironmentOrigin("")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java index f436e867517..ac10ad61d6d 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/reactive/ApplicationContextServerWebExchangeMatcherTests.java @@ -18,9 +18,7 @@ package org.springframework.boot.security.reactive; import java.util.function.Supplier; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import reactor.core.publisher.Mono; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -36,6 +34,9 @@ import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.HttpWebHandlerAdapter; 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.mockito.Mockito.mock; /** @@ -45,14 +46,12 @@ import static org.mockito.Mockito.mock; */ public class ApplicationContextServerWebExchangeMatcherTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenContextClassIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Context class must not be null"); - new TestApplicationContextServerWebExchangeMatcher<>(null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new TestApplicationContextServerWebExchangeMatcher<>(null)) + .withMessageContaining("Context class must not be null"); } @Test @@ -82,18 +81,19 @@ public class ApplicationContextServerWebExchangeMatcherTests { ServerWebExchange exchange = createExchange(); Supplier supplier = new TestApplicationContextServerWebExchangeMatcher<>( ExistingBean.class).callMatchesAndReturnProvidedContext(exchange); - this.thrown.expect(NoSuchBeanDefinitionException.class); - supplier.get(); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(supplier::get); } @Test public void matchesWhenContextIsNull() { MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/path").build()); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("No ApplicationContext found on ServerWebExchange."); - new TestApplicationContextServerWebExchangeMatcher<>(ExistingBean.class) - .callMatchesAndReturnProvidedContext(exchange); + assertThatIllegalStateException() + .isThrownBy(() -> new TestApplicationContextServerWebExchangeMatcher<>( + ExistingBean.class).callMatchesAndReturnProvidedContext(exchange)) + .withMessageContaining( + "No ApplicationContext found on ServerWebExchange."); } private ServerWebExchange createExchange() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java index 0660594ebaf..df4d369bf4f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/security/servlet/ApplicationContextRequestMatcherTests.java @@ -20,9 +20,7 @@ import java.util.function.Supplier; import javax.servlet.http.HttpServletRequest; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; @@ -32,6 +30,8 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StaticWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ApplicationContextRequestMatcher}. @@ -40,14 +40,11 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ApplicationContextRequestMatcherTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenContextClassIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Context class must not be null"); - new TestApplicationContextRequestMatcher<>(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new TestApplicationContextRequestMatcher<>(null)) + .withMessageContaining("Context class must not be null"); } @Test @@ -71,8 +68,8 @@ public class ApplicationContextRequestMatcherTests { StaticWebApplicationContext context = createWebApplicationContext(); Supplier supplier = new TestApplicationContextRequestMatcher<>( ExistingBean.class).callMatchesAndReturnProvidedContext(context); - this.thrown.expect(NoSuchBeanDefinitionException.class); - supplier.get(); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(supplier::get); } private StaticWebApplicationContext createWebApplicationContext() { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java index 28aaf711611..e0e42a5b751 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/system/ApplicationPidTests.java @@ -21,12 +21,12 @@ import java.io.FileReader; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link ApplicationPid}. @@ -35,9 +35,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class ApplicationPidTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -54,9 +51,9 @@ public class ApplicationPidTests { @Test public void throwIllegalStateWritingMissingPid() throws Exception { ApplicationPid pid = new ApplicationPid(null); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("No PID available"); - pid.write(this.temporaryFolder.newFile()); + assertThatIllegalStateException() + .isThrownBy(() -> pid.write(this.temporaryFolder.newFile())) + .withMessageContaining("No PID available"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java index b373c8b811c..59b6f2a2992 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskExecutorBuilderTests.java @@ -20,9 +20,7 @@ import java.time.Duration; import java.util.Collections; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.DirectFieldAccessor; import org.springframework.core.task.TaskDecorator; @@ -30,6 +28,7 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -42,9 +41,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ public class TaskExecutorBuilderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private TaskExecutorBuilder builder = new TaskExecutorBuilder(); @Test @@ -77,16 +73,17 @@ public class TaskExecutorBuilderTests { @Test public void customizersWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.customizers((TaskExecutorCustomizer[]) null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> this.builder.customizers((TaskExecutorCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.customizers((Set) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.customizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -127,16 +124,17 @@ public class TaskExecutorBuilderTests { @Test public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.additionalCustomizers((TaskExecutorCustomizer[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.additionalCustomizers((TaskExecutorCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.additionalCustomizers((Set) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .additionalCustomizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java index 8ae498b207d..68db1188e03 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/task/TaskSchedulerBuilderTests.java @@ -19,13 +19,12 @@ package org.springframework.boot.task; import java.util.Collections; import java.util.Set; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -38,9 +37,6 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ public class TaskSchedulerBuilderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private TaskSchedulerBuilder builder = new TaskSchedulerBuilder(); @Test @@ -58,16 +54,17 @@ public class TaskSchedulerBuilderTests { @Test public void customizersWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.customizers((TaskSchedulerCustomizer[]) null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> this.builder.customizers((TaskSchedulerCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.customizers((Set) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.customizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -100,16 +97,18 @@ public class TaskSchedulerBuilderTests { @Test public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.additionalCustomizers((TaskSchedulerCustomizer[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .additionalCustomizers((TaskSchedulerCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.additionalCustomizers((Set) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .additionalCustomizers((Set) null)) + .withMessageContaining("Customizers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java index a452a55f336..9a044989b7e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/util/LambdaSafeTests.java @@ -22,14 +22,13 @@ import java.util.List; import java.util.stream.Stream; import org.apache.commons.logging.Log; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.boot.util.LambdaSafe.Filter; import org.springframework.boot.util.LambdaSafe.InvocationResult; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.contains; @@ -45,21 +44,18 @@ import static org.mockito.Mockito.verifyZeroInteractions; */ public class LambdaSafeTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void callbackWhenCallbackTypeIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("CallbackType must not be null"); - LambdaSafe.callback(null, new Object(), null); + assertThatIllegalArgumentException() + .isThrownBy(() -> LambdaSafe.callback(null, new Object(), null)) + .withMessageContaining("CallbackType must not be null"); } @Test public void callbackWhenCallbackInstanceIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("CallbackInstance must not be null"); - LambdaSafe.callback(Object.class, null, null); + assertThatIllegalArgumentException() + .isThrownBy(() -> LambdaSafe.callback(Object.class, null, null)) + .withMessageContaining("CallbackInstance must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java index c6073245376..8601466840a 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,15 +21,14 @@ import javax.validation.Validation; import javax.validation.ValidationException; import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions; import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration tests for {@link MessageInterpolatorFactory} without EL. @@ -40,15 +39,12 @@ import static org.assertj.core.api.Assertions.assertThat; @ClassPathExclusions("tomcat-embed-el-*.jar") public class MessageInterpolatorFactoryWithoutElIntegrationTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void defaultMessageInterpolatorShouldFail() { // Sanity test - this.thrown.expect(ValidationException.class); - this.thrown.expectMessage("javax.el.ExpressionFactory"); - Validation.byDefaultProvider().configure().getDefaultMessageInterpolator(); + assertThatExceptionOfType(ValidationException.class).isThrownBy( + Validation.byDefaultProvider().configure()::getDefaultMessageInterpolator) + .withMessageContaining("javax.el.ExpressionFactory"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java index 5e0f08f8f88..47cfd04d6bc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RestTemplateBuilderTests.java @@ -23,9 +23,7 @@ import java.util.function.Supplier; import org.apache.http.client.config.RequestConfig; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -47,6 +45,7 @@ import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriTemplateHandler; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -65,9 +64,6 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat */ public class RestTemplateBuilderTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private RestTemplateBuilder builder = new RestTemplateBuilder(); @Mock @@ -83,10 +79,10 @@ public class RestTemplateBuilderTests { @Test public void createWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); RestTemplateCustomizer[] customizers = null; - new RestTemplateBuilder(customizers); + assertThatIllegalArgumentException() + .isThrownBy(() -> new RestTemplateBuilder(customizers)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -132,16 +128,16 @@ public class RestTemplateBuilderTests { @Test public void messageConvertersWhenConvertersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("MessageConverters must not be null"); - this.builder.messageConverters((HttpMessageConverter[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.messageConverters((HttpMessageConverter[]) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test public void messageConvertersCollectionWhenConvertersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("MessageConverters must not be null"); - this.builder.messageConverters((Set>) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.messageConverters((Set>) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test @@ -161,16 +157,18 @@ public class RestTemplateBuilderTests { @Test public void additionalMessageConvertersWhenConvertersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("MessageConverters must not be null"); - this.builder.additionalMessageConverters((HttpMessageConverter[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .additionalMessageConverters((HttpMessageConverter[]) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test public void additionalMessageConvertersCollectionWhenConvertersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("MessageConverters must not be null"); - this.builder.additionalMessageConverters((Set>) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .additionalMessageConverters((Set>) null)) + .withMessageContaining("MessageConverters must not be null"); } @Test @@ -203,16 +201,16 @@ public class RestTemplateBuilderTests { @Test public void interceptorsWhenInterceptorsAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("interceptors must not be null"); - this.builder.interceptors((ClientHttpRequestInterceptor[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.interceptors((ClientHttpRequestInterceptor[]) null)) + .withMessageContaining("interceptors must not be null"); } @Test public void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("interceptors must not be null"); - this.builder.interceptors((Set) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.interceptors((Set) null)) + .withMessageContaining("interceptors must not be null"); } @Test @@ -231,16 +229,18 @@ public class RestTemplateBuilderTests { @Test public void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("interceptors must not be null"); - this.builder.additionalInterceptors((ClientHttpRequestInterceptor[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .additionalInterceptors((ClientHttpRequestInterceptor[]) null)) + .withMessageContaining("interceptors must not be null"); } @Test public void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("interceptors must not be null"); - this.builder.additionalInterceptors((Set) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .additionalInterceptors((Set) null)) + .withMessageContaining("interceptors must not be null"); } @Test @@ -255,9 +255,9 @@ public class RestTemplateBuilderTests { @Test public void requestFactoryClassWhenFactoryIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RequestFactory must not be null"); - this.builder.requestFactory((Class) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.requestFactory((Class) null)) + .withMessageContaining("RequestFactory must not be null"); } @Test @@ -278,9 +278,10 @@ public class RestTemplateBuilderTests { @Test public void requestFactoryWhenSupplierIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RequestFactory Supplier must not be null"); - this.builder.requestFactory((Supplier) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .requestFactory((Supplier) null)) + .withMessageContaining("RequestFactory Supplier must not be null"); } @Test @@ -292,9 +293,9 @@ public class RestTemplateBuilderTests { @Test public void uriTemplateHandlerWhenHandlerIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("UriTemplateHandler must not be null"); - this.builder.uriTemplateHandler(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.uriTemplateHandler(null)) + .withMessageContaining("UriTemplateHandler must not be null"); } @Test @@ -307,9 +308,9 @@ public class RestTemplateBuilderTests { @Test public void errorHandlerWhenHandlerIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ErrorHandler must not be null"); - this.builder.errorHandler(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.errorHandler(null)) + .withMessageContaining("ErrorHandler must not be null"); } @Test @@ -330,16 +331,17 @@ public class RestTemplateBuilderTests { @Test public void customizersWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RestTemplateCustomizers must not be null"); - this.builder.customizers((RestTemplateCustomizer[]) null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> this.builder.customizers((RestTemplateCustomizer[]) null)) + .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RestTemplateCustomizers must not be null"); - this.builder.customizers((Set) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.customizers((Set) null)) + .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test @@ -369,16 +371,17 @@ public class RestTemplateBuilderTests { @Test public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RestTemplateCustomizers must not be null"); - this.builder.additionalCustomizers((RestTemplateCustomizer[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.additionalCustomizers((RestTemplateCustomizer[]) null)) + .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RestTemplateCustomizers must not be null"); - this.builder.additionalCustomizers((Set) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .additionalCustomizers((Set) null)) + .withMessageContaining("RestTemplateCustomizers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java index 32da0826624..ef698504e0f 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/client/RootUriTemplateHandlerTests.java @@ -22,9 +22,7 @@ import java.util.HashMap; import java.util.Map; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -32,6 +30,7 @@ import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriTemplateHandler; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -44,9 +43,6 @@ import static org.mockito.Mockito.verify; */ public class RootUriTemplateHandlerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private URI uri; @Mock @@ -67,16 +63,16 @@ public class RootUriTemplateHandlerTests { @Test public void createWithNullRootUriShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("RootUri must not be null"); - new RootUriTemplateHandler((String) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new RootUriTemplateHandler((String) null)) + .withMessageContaining("RootUri must not be null"); } @Test public void createWithNullHandlerShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Handler must not be null"); - new RootUriTemplateHandler("http://example.com", null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new RootUriTemplateHandler("http://example.com", null)) + .withMessageContaining("Handler must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java index adf6ebecf25..93a2618ac14 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyReactiveWebServerFactoryTests.java @@ -29,6 +29,7 @@ import org.springframework.boot.web.reactive.server.AbstractReactiveWebServerFac import org.springframework.http.server.reactive.HttpHandler; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -50,17 +51,17 @@ public class JettyReactiveWebServerFactoryTests @Test public void setNullServerCustomizersShouldThrowException() { JettyReactiveWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - factory.setServerCustomizers(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.setServerCustomizers(null)) + .withMessageContaining("Customizers must not be null"); } @Test public void addNullServerCustomizersShouldThrowException() { JettyReactiveWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - factory.addServerCustomizers((JettyServerCustomizer[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> factory.addServerCustomizers((JettyServerCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java index 2162c0be1f1..315643faadc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/jetty/JettyServletWebServerFactoryTests.java @@ -50,7 +50,7 @@ import org.springframework.boot.web.servlet.server.AbstractServletWebServerFacto import org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.isA; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -262,8 +262,9 @@ public class JettyServletWebServerFactoryTests threadPool.setMaxThreads(2); threadPool.setMinThreads(2); }); - this.thrown.expectCause(isA(IllegalStateException.class)); - factory.getWebServer().start(); + assertThatExceptionOfType(WebServerException.class) + .isThrownBy(factory.getWebServer()::start) + .withCauseInstanceOf(IllegalStateException.class); } @Test @@ -314,23 +315,23 @@ public class JettyServletWebServerFactoryTests @Override public void contextDestroyed(ServletContextEvent sce) { - } }); } }); - this.thrown.expect(WebServerException.class); - JettyWebServer jettyWebServer = (JettyWebServer) factory.getWebServer(); - try { - jettyWebServer.start(); - } - finally { - QueuedThreadPool threadPool = (QueuedThreadPool) jettyWebServer.getServer() - .getThreadPool(); - assertThat(threadPool.isRunning()).isFalse(); - } + assertThatExceptionOfType(WebServerException.class).isThrownBy(() -> { + JettyWebServer jettyWebServer = (JettyWebServer) factory.getWebServer(); + try { + jettyWebServer.start(); + } + finally { + QueuedThreadPool threadPool = (QueuedThreadPool) jettyWebServer + .getServer().getThreadPool(); + assertThat(threadPool.isRunning()).isFalse(); + } + }); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java index fb642a3d93c..a3bb5e8ee6b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/netty/NettyReactiveWebServerFactoryTests.java @@ -18,7 +18,6 @@ package org.springframework.boot.web.embedded.netty; import java.util.Arrays; -import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.InOrder; import reactor.netty.http.server.HttpServer; @@ -27,6 +26,8 @@ import org.springframework.boot.web.reactive.server.AbstractReactiveWebServerFac import org.springframework.boot.web.reactive.server.AbstractReactiveWebServerFactoryTests; import org.springframework.boot.web.server.PortInUseException; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.inOrder; @@ -52,10 +53,13 @@ public class NettyReactiveWebServerFactoryTests this.webServer = factory.getWebServer(new EchoHandler()); this.webServer.start(); factory.setPort(this.webServer.getPort()); - this.thrown.expect(PortInUseException.class); - this.thrown.expect( - Matchers.hasProperty("port", Matchers.equalTo(this.webServer.getPort()))); - factory.getWebServer(new EchoHandler()).start(); + assertThatExceptionOfType(PortInUseException.class) + .isThrownBy(factory.getWebServer(new EchoHandler())::start) + .satisfies(this::portMatchesRequirement); + } + + private void portMatchesRequirement(PortInUseException exception) { + assertThat(exception.getPort()).isEqualTo(this.webServer.getPort()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java index 66c94a9094c..342e7de0a03 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/tomcat/TomcatReactiveWebServerFactoryTests.java @@ -32,6 +32,7 @@ import org.springframework.boot.web.reactive.server.AbstractReactiveWebServerFac import org.springframework.http.server.reactive.HttpHandler; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -100,17 +101,17 @@ public class TomcatReactiveWebServerFactoryTests @Test public void setNullConnectorCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - factory.setTomcatConnectorCustomizers(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) + .withMessageContaining("Customizers must not be null"); } @Test public void addNullAddConnectorCustomizersShouldThrowException() { TomcatReactiveWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test 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 f4cd32506d0..50385b0237b 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 @@ -61,6 +61,8 @@ import org.springframework.boot.web.servlet.server.AbstractServletWebServerFacto 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; @@ -185,9 +187,10 @@ public class TomcatServletWebServerFactoryTests @Test public void addNullAdditionalConnectorThrows() { TomcatServletWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Connectors must not be null"); - factory.addAdditionalTomcatConnectors((Connector[]) null); + assertThatIllegalArgumentException() + .isThrownBy( + () -> factory.addAdditionalTomcatConnectors((Connector[]) null)) + .withMessageContaining("Connectors must not be null"); } @Test @@ -223,33 +226,33 @@ public class TomcatServletWebServerFactoryTests @Test public void setNullTomcatContextCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TomcatContextCustomizers must not be null"); - factory.setTomcatContextCustomizers(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.setTomcatContextCustomizers(null)) + .withMessageContaining("TomcatContextCustomizers must not be null"); } @Test public void addNullContextCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TomcatContextCustomizers must not be null"); - factory.addContextCustomizers((TomcatContextCustomizer[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> factory.addContextCustomizers((TomcatContextCustomizer[]) null)) + .withMessageContaining("TomcatContextCustomizers must not be null"); } @Test public void setNullTomcatConnectorCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TomcatConnectorCustomizers must not be null"); - factory.setTomcatConnectorCustomizers(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.setTomcatConnectorCustomizers(null)) + .withMessageContaining("TomcatConnectorCustomizers must not be null"); } @Test public void addNullConnectorCustomizersThrows() { TomcatServletWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TomcatConnectorCustomizers must not be null"); - factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> factory.addConnectorCustomizers((TomcatConnectorCustomizer[]) null)) + .withMessageContaining("TomcatConnectorCustomizers must not be null"); } @Test @@ -362,8 +365,8 @@ public class TomcatServletWebServerFactoryTests // and avoid a leak this.webServer.start(); // Lookups should no longer be possible - this.thrown.expect(NamingException.class); - new InitialContext().lookup("java:comp/env"); + assertThatExceptionOfType(NamingException.class) + .isThrownBy(() -> new InitialContext().lookup("java:comp/env")); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java index da323af23e2..3df4ed3b6cf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowReactiveWebServerFactoryTests.java @@ -35,6 +35,7 @@ import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -59,17 +60,17 @@ public class UndertowReactiveWebServerFactoryTests @Test public void setNullBuilderCustomizersShouldThrowException() { UndertowReactiveWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - factory.setBuilderCustomizers(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.setBuilderCustomizers(null)) + .withMessageContaining("Customizers must not be null"); } @Test public void addNullBuilderCustomizersShouldThrowException() { UndertowReactiveWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java index 028b6c82b72..5beb916cb82 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/embedded/undertow/UndertowServletWebServerFactoryTests.java @@ -51,8 +51,8 @@ import org.springframework.http.HttpStatus; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.anyOf; -import static org.hamcrest.CoreMatchers.instanceOf; +import static org.assertj.core.api.Assertions.assertThatIOException; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -85,17 +85,17 @@ public class UndertowServletWebServerFactoryTests @Test public void setNullBuilderCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - factory.setBuilderCustomizers(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.setBuilderCustomizers(null)) + .withMessageContaining("Customizers must not be null"); } @Test public void addNullAddBuilderCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> factory.addBuilderCustomizers((UndertowBuilderCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -115,17 +115,18 @@ public class UndertowServletWebServerFactoryTests @Test public void setNullDeploymentInfoCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - factory.setDeploymentInfoCustomizers(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.setDeploymentInfoCustomizers(null)) + .withMessageContaining("Customizers must not be null"); } @Test public void addNullAddDeploymentInfoCustomizersThrows() { UndertowServletWebServerFactory factory = getFactory(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - factory.addDeploymentInfoCustomizers((UndertowDeploymentInfoCustomizer[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> factory.addDeploymentInfoCustomizers( + (UndertowDeploymentInfoCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -209,18 +210,20 @@ public class UndertowServletWebServerFactoryTests @Test public void sslRestrictedProtocolsEmptyCipherFailure() throws Exception { - this.thrown.expect(anyOf(instanceOf(SSLHandshakeException.class), - instanceOf(SocketException.class))); - testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.2" }, - new String[] { "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" }); + assertThatIOException() + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites( + new String[] { "TLSv1.2" }, + new String[] { "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" })) + .isInstanceOfAny(SSLHandshakeException.class, SocketException.class); } @Test public void sslRestrictedProtocolsECDHETLS1Failure() throws Exception { - this.thrown.expect( - anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); - testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1" }, - new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }); + assertThatIOException() + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites( + new String[] { "TLSv1" }, + new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" })) + .isInstanceOfAny(SSLException.class, SocketException.class); } @Test @@ -237,10 +240,11 @@ public class UndertowServletWebServerFactoryTests @Test public void sslRestrictedProtocolsRSATLS11Failure() throws Exception { - this.thrown.expect( - anyOf(instanceOf(SSLException.class), instanceOf(SocketException.class))); - testRestrictedSSLProtocolsAndCipherSuites(new String[] { "TLSv1.1" }, - new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" }); + assertThatIOException() + .isThrownBy(() -> testRestrictedSSLProtocolsAndCipherSuites( + new String[] { "TLSv1.1" }, + new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA256" })) + .isInstanceOfAny(SSLException.class, SocketException.class); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java index 1a676c16d36..b2da054bfbf 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/error/DefaultErrorAttributesTests.java @@ -22,9 +22,7 @@ import java.util.Date; import java.util.List; import java.util.Map; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.core.MethodParameter; import org.springframework.http.HttpStatus; @@ -41,6 +39,7 @@ import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link DefaultErrorAttributes}. @@ -53,9 +52,6 @@ public class DefaultErrorAttributesTests { private static final ResponseStatusException NOT_FOUND = new ResponseStatusException( HttpStatus.NOT_FOUND); - @Rule - public ExpectedException thrown = ExpectedException.none(); - private DefaultErrorAttributes errorAttributes = new DefaultErrorAttributes(); private List> readers = ServerCodecConfigurer.create() @@ -63,12 +59,13 @@ public class DefaultErrorAttributesTests { @Test public void missingExceptionAttribute() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("Missing exception attribute in ServerWebExchange"); MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/test").build()); ServerRequest request = ServerRequest.create(exchange, this.readers); - this.errorAttributes.getErrorAttributes(request, false); + assertThatIllegalStateException() + .isThrownBy(() -> this.errorAttributes.getErrorAttributes(request, false)) + .withMessageContaining( + "Missing exception attribute in ServerWebExchange"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java index fbce32c475a..e76b40d2873 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/reactive/server/AbstractReactiveWebServerFactoryTests.java @@ -37,7 +37,6 @@ import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import reactor.core.publisher.Mono; import reactor.netty.NettyPipeline; import reactor.netty.http.client.HttpClient; @@ -71,9 +70,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public abstract class AbstractReactiveWebServerFactoryTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public OutputCapture output = new OutputCapture(); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java index 9a401485a09..412e31e7876 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessorTests.java @@ -23,9 +23,7 @@ import java.util.List; import java.util.Map; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -33,6 +31,7 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.ListableBeanFactory; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -43,9 +42,6 @@ import static org.mockito.Mockito.mock; */ public class WebServerFactoryCustomizerBeanPostProcessorTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private WebServerFactoryCustomizerBeanPostProcessor processor = new WebServerFactoryCustomizerBeanPostProcessor(); @Mock @@ -59,10 +55,10 @@ public class WebServerFactoryCustomizerBeanPostProcessorTests { @Test public void setBeanFactoryWhenNotListableShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("WebServerCustomizerBeanPostProcessor can only " - + "be used with a ListableBeanFactory"); - this.processor.setBeanFactory(mock(BeanFactory.class)); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.processor.setBeanFactory(mock(BeanFactory.class))) + .withMessageContaining("WebServerCustomizerBeanPostProcessor can only " + + "be used with a ListableBeanFactory"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java index e8a020e7605..3e591416a0b 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java @@ -29,12 +29,11 @@ import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -49,9 +48,6 @@ import static org.mockito.Mockito.verify; */ public abstract class AbstractFilterRegistrationBeanTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock ServletContext servletContext; @@ -130,17 +126,17 @@ public abstract class AbstractFilterRegistrationBeanTests { @Test public void setServletRegistrationBeanMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ServletRegistrationBeans must not be null"); - bean.setServletRegistrationBeans(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> bean.setServletRegistrationBeans(null)) + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test public void addServletRegistrationBeanMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ServletRegistrationBeans must not be null"); - bean.addServletRegistrationBeans((ServletRegistrationBean[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> bean.addServletRegistrationBeans((ServletRegistrationBean[]) null)) + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Test @@ -166,33 +162,31 @@ public abstract class AbstractFilterRegistrationBeanTests { @Test public void setUrlPatternMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("UrlPatterns must not be null"); - bean.setUrlPatterns(null); + assertThatIllegalArgumentException().isThrownBy(() -> bean.setUrlPatterns(null)) + .withMessageContaining("UrlPatterns must not be null"); } @Test public void addUrlPatternMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("UrlPatterns must not be null"); - bean.addUrlPatterns((String[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> bean.addUrlPatterns((String[]) null)) + .withMessageContaining("UrlPatterns must not be null"); } @Test public void setServletNameMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ServletNames must not be null"); - bean.setServletNames(null); + assertThatIllegalArgumentException().isThrownBy(() -> bean.setServletNames(null)) + .withMessageContaining("ServletNames must not be null"); } @Test public void addServletNameMustNotBeNull() { AbstractFilterRegistrationBean bean = createFilterRegistrationBean(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ServletNames must not be null"); - bean.addServletNames((String[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> bean.addServletNames((String[]) null)) + .withMessageContaining("ServletNames must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java index 82a2e7ccc4c..3cdb360f5d5 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBeanTests.java @@ -35,6 +35,7 @@ import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.filter.GenericFilterBean; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.isA; /** @@ -52,16 +53,16 @@ public class DelegatingFilterProxyRegistrationBeanTests @Test public void targetBeanNameMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TargetBeanName must not be null or empty"); - new DelegatingFilterProxyRegistrationBean(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingFilterProxyRegistrationBean(null)) + .withMessageContaining("TargetBeanName must not be null or empty"); } @Test public void targetBeanNameMustNotBeEmpty() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("TargetBeanName must not be null or empty"); - new DelegatingFilterProxyRegistrationBean(""); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingFilterProxyRegistrationBean("")) + .withMessageContaining("TargetBeanName must not be null or empty"); } @Test @@ -96,10 +97,10 @@ public class DelegatingFilterProxyRegistrationBeanTests @Test public void createServletRegistrationBeanMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ServletRegistrationBeans must not be null"); - new DelegatingFilterProxyRegistrationBean("mockFilter", - (ServletRegistrationBean[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingFilterProxyRegistrationBean("mockFilter", + (ServletRegistrationBean[]) null)) + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java index 93494e5088d..2fd2b2b57dc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/FilterRegistrationBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -22,6 +22,7 @@ import org.junit.Test; import org.springframework.boot.web.servlet.mock.MockFilter; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; @@ -45,23 +46,24 @@ public class FilterRegistrationBeanTests extends AbstractFilterRegistrationBeanT @Test public void setFilterMustNotBeNull() throws Exception { FilterRegistrationBean bean = new FilterRegistrationBean<>(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Filter must not be null"); - bean.onStartup(this.servletContext); + assertThatIllegalArgumentException() + .isThrownBy(() -> bean.onStartup(this.servletContext)) + .withMessageContaining("Filter must not be null"); } @Test public void constructFilterMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Filter must not be null"); - new FilterRegistrationBean<>(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new FilterRegistrationBean<>(null)) + .withMessageContaining("Filter must not be null"); } @Test public void createServletRegistrationBeanMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ServletRegistrationBeans must not be null"); - new FilterRegistrationBean<>(this.filter, (ServletRegistrationBean[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new FilterRegistrationBean<>(this.filter, + (ServletRegistrationBean[]) null)) + .withMessageContaining("ServletRegistrationBeans must not be null"); } @Override diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java index 8d1ddf8313e..979b4b22d9e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletComponentScanRegistrarTests.java @@ -17,9 +17,7 @@ package org.springframework.boot.web.servlet; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -27,8 +25,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.AnnotationConfigurationException; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.allOf; -import static org.hamcrest.Matchers.containsString; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link ServletComponentScanRegistrar} @@ -39,9 +36,6 @@ public class ServletComponentScanRegistrarTests { private AnnotationConfigApplicationContext context; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @After public void after() { if (this.context != null) { @@ -90,11 +84,14 @@ public class ServletComponentScanRegistrarTests { @Test public void packagesConfiguredWithBothValueAndBasePackages() { - this.thrown.expect(AnnotationConfigurationException.class); - this.thrown.expectMessage(allOf(containsString("'value'"), - containsString("'basePackages'"), containsString("com.example.foo"), - containsString("com.example.bar"))); - this.context = new AnnotationConfigApplicationContext(ValueAndBasePackages.class); + assertThatExceptionOfType(AnnotationConfigurationException.class) + .isThrownBy(() -> { + this.context = new AnnotationConfigApplicationContext( + ValueAndBasePackages.class); + }).withMessageContaining("'value'") + .withMessageContaining("'basePackages'") + .withMessageContaining("com.example.foo") + .withMessageContaining("com.example.bar"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java index ac75e4bfe91..d030a1c1fdc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletListenerRegistrationBeanTests.java @@ -22,12 +22,11 @@ import javax.servlet.ServletContext; import javax.servlet.ServletContextListener; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -39,9 +38,6 @@ import static org.mockito.Mockito.verify; */ public class ServletListenerRegistrationBeanTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private ServletContextListener listener; @@ -73,10 +69,10 @@ public class ServletListenerRegistrationBeanTests { @Test public void cannotRegisterUnsupportedType() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Listener is not of a supported type"); - new ServletListenerRegistrationBean(new EventListener() { - }); + assertThatIllegalArgumentException().isThrownBy( + () -> new ServletListenerRegistrationBean<>(new EventListener() { + + })).withMessageContaining("Listener is not of a supported type"); } } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java index 109688460d9..13275de06c9 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/ServletRegistrationBeanTests.java @@ -29,14 +29,13 @@ import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.web.servlet.mock.MockServlet; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -50,9 +49,6 @@ import static org.mockito.Mockito.verify; */ public class ServletRegistrationBeanTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private final MockServlet servlet = new MockServlet(); @Mock @@ -145,41 +141,40 @@ public class ServletRegistrationBeanTests { @Test public void setServletMustNotBeNull() throws Exception { ServletRegistrationBean bean = new ServletRegistrationBean<>(); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Servlet must not be null"); - bean.onStartup(this.servletContext); + assertThatIllegalArgumentException() + .isThrownBy(() -> bean.onStartup(this.servletContext)) + .withMessageContaining("Servlet must not be null"); } @Test public void createServletMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Servlet must not be null"); - new ServletRegistrationBean(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ServletRegistrationBean(null)) + .withMessageContaining("Servlet must not be null"); } @Test public void setMappingMustNotBeNull() { ServletRegistrationBean bean = new ServletRegistrationBean<>( this.servlet); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("UrlMappings must not be null"); - bean.setUrlMappings(null); + assertThatIllegalArgumentException().isThrownBy(() -> bean.setUrlMappings(null)) + .withMessageContaining("UrlMappings must not be null"); } @Test public void createMappingMustNotBeNull() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("UrlMappings must not be null"); - new ServletRegistrationBean<>(this.servlet, (String[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> new ServletRegistrationBean<>(this.servlet, (String[]) null)) + .withMessageContaining("UrlMappings must not be null"); } @Test public void addMappingMustNotBeNull() { ServletRegistrationBean bean = new ServletRegistrationBean<>( this.servlet); - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("UrlMappings must not be null"); - bean.addUrlMappings((String[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> bean.addUrlMappings((String[]) null)) + .withMessageContaining("UrlMappings must not be null"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java index 6623817942d..942b4671d18 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebFilterHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +30,7 @@ import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.config.BeanDefinition; @@ -41,6 +39,7 @@ import org.springframework.context.annotation.ScannedGenericBeanDefinition; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link WebFilterHandler} @@ -53,9 +52,6 @@ public class WebFilterHandlerTests { private final SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @SuppressWarnings("unchecked") @Test public void defaultFilterConfiguration() throws IOException { @@ -147,10 +143,10 @@ public class WebFilterHandlerTests { @Test public void urlPatternsDeclaredTwice() throws IOException { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The urlPatterns and value attributes are mutually exclusive."); - getBeanDefinition(UrlPatternsDeclaredTwiceFilter.class); + assertThatIllegalStateException() + .isThrownBy(() -> getBeanDefinition(UrlPatternsDeclaredTwiceFilter.class)) + .withMessageContaining( + "The urlPatterns and value attributes are mutually exclusive."); } BeanDefinition getBeanDefinition(Class filterClass) throws IOException { diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java index 5ccec78e559..5b8e1abfbb6 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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,9 +23,7 @@ import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.config.BeanDefinition; @@ -34,6 +32,7 @@ import org.springframework.context.annotation.ScannedGenericBeanDefinition; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link WebServletHandler}. @@ -46,9 +45,6 @@ public class WebServletHandlerTests { private final SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @SuppressWarnings("unchecked") @Test public void defaultServletConfiguration() throws IOException { @@ -125,13 +121,14 @@ public class WebServletHandlerTests { @Test public void urlPatternsDeclaredTwice() throws IOException { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage( - "The urlPatterns and value attributes are mutually exclusive."); - getBeanDefinition(UrlPatternsDeclaredTwiceServlet.class); + assertThatIllegalStateException() + .isThrownBy( + () -> getBeanDefinition(UrlPatternsDeclaredTwiceServlet.class)) + .withMessageContaining( + "The urlPatterns and value attributes are mutually exclusive."); } - BeanDefinition getBeanDefinition(Class filterClass) throws IOException { + private BeanDefinition getBeanDefinition(Class filterClass) throws IOException { ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition( new SimpleMetadataReaderFactory() .getMetadataReader(filterClass.getName())); diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java index 44ef0f35d07..0887236ec97 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContextTests.java @@ -31,9 +31,7 @@ import javax.servlet.ServletResponse; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; @@ -69,6 +67,8 @@ import org.springframework.web.context.request.SessionScope; import org.springframework.web.filter.GenericFilterBean; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -86,9 +86,6 @@ import static org.mockito.Mockito.withSettings; */ public class ServletWebServerApplicationContextTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - private ServletWebServerApplicationContext context; @Captor @@ -175,8 +172,7 @@ public class ServletWebServerApplicationContextTests { public void cannotSecondRefresh() { addWebServerFactoryBean(); this.context.refresh(); - this.thrown.expect(IllegalStateException.class); - this.context.refresh(); + assertThatIllegalStateException().isThrownBy(() -> this.context.refresh()); } @Test @@ -190,11 +186,10 @@ public class ServletWebServerApplicationContextTests { @Test public void missingServletWebServerFactory() { - this.thrown.expect(ApplicationContextException.class); - this.thrown.expectMessage( - "Unable to start ServletWebServerApplicationContext due to missing " - + "ServletWebServerFactory bean"); - this.context.refresh(); + assertThatExceptionOfType(ApplicationContextException.class) + .isThrownBy(() -> this.context.refresh()).withMessageContaining( + "Unable to start ServletWebServerApplicationContext due to missing " + + "ServletWebServerFactory bean"); } @Test @@ -202,11 +197,10 @@ public class ServletWebServerApplicationContextTests { addWebServerFactoryBean(); this.context.registerBeanDefinition("webServerFactory2", new RootBeanDefinition(MockServletWebServerFactory.class)); - this.thrown.expect(ApplicationContextException.class); - this.thrown.expectMessage( - "Unable to start ServletWebServerApplicationContext due to " - + "multiple ServletWebServerFactory beans"); - this.context.refresh(); + assertThatExceptionOfType(ApplicationContextException.class) + .isThrownBy(() -> this.context.refresh()).withMessageContaining( + "Unable to start ServletWebServerApplicationContext due to " + + "multiple ServletWebServerFactory beans"); } @@ -423,11 +417,11 @@ public class ServletWebServerApplicationContextTests { this.filterCaptor.capture()); // Up to this point the filterBean should not have been created, calling // the delegate proxy will trigger creation and an exception - this.thrown.expect(BeanCreationException.class); - this.thrown.expectMessage("Create FilterBean Failure"); - this.filterCaptor.getValue().init(new MockFilterConfig()); - this.filterCaptor.getValue().doFilter(new MockHttpServletRequest(), - new MockHttpServletResponse(), new MockFilterChain()); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> { + this.filterCaptor.getValue().init(new MockFilterConfig()); + this.filterCaptor.getValue().doFilter(new MockHttpServletRequest(), + new MockHttpServletResponse(), new MockFilterChain()); + }).withMessageContaining("Create FilterBean Failure"); } @Test 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 91db8a2185f..14307e0083e 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 @@ -82,7 +82,6 @@ import org.junit.After; import org.junit.Assume; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.InOrder; @@ -116,6 +115,10 @@ import org.springframework.util.SocketUtils; import org.springframework.util.StreamUtils; 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.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; @@ -135,9 +138,6 @@ import static org.mockito.Mockito.verify; */ public abstract class AbstractServletWebServerFactoryTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -205,10 +205,8 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer.start(); int port = this.webServer.getPort(); this.webServer.stop(); - this.thrown.expect(IOException.class); - String response = getResponse(getLocalUrl(port, "/hello")); - throw new RuntimeException( - "Unexpected response on port " + port + " : " + response); + assertThatIOException() + .isThrownBy(() -> getResponse(getLocalUrl(port, "/hello"))); } @Test @@ -281,24 +279,25 @@ public abstract class AbstractServletWebServerFactoryTests { @Test public void contextPathMustStartWithSlash() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ContextPath must start with '/' and not end with '/'"); - getFactory().setContextPath("missingslash"); + assertThatIllegalArgumentException() + .isThrownBy(() -> getFactory().setContextPath("missingslash")) + .withMessageContaining( + "ContextPath must start with '/' and not end with '/'"); } @Test public void contextPathMustNotEndWithSlash() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("ContextPath must start with '/' and not end with '/'"); - getFactory().setContextPath("extraslash/"); + assertThatIllegalArgumentException() + .isThrownBy(() -> getFactory().setContextPath("extraslash/")) + .withMessageContaining( + "ContextPath must start with '/' and not end with '/'"); } @Test public void contextRootPathMustNotBeSlash() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage( - "Root ContextPath must be specified using an empty string"); - getFactory().setContextPath("/"); + assertThatIllegalArgumentException() + .isThrownBy(() -> getFactory().setContextPath("/")).withMessageContaining( + "Root ContextPath must be specified using an empty string"); } @Test @@ -392,8 +391,8 @@ public abstract class AbstractServletWebServerFactoryTests { .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); - this.thrown.expect(SSLException.class); - getResponse(getLocalUrl("https", "/hello"), requestFactory); + assertThatExceptionOfType(SSLException.class).isThrownBy( + () -> getResponse(getLocalUrl("https", "/hello"), requestFactory)); } @Test @@ -696,16 +695,13 @@ public abstract class AbstractServletWebServerFactoryTests { this.webServer = factory.getWebServer( new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello")); this.webServer.start(); - SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); - HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); - assertThat(getResponse(getLocalUrl("https", "/hello"), requestFactory)) .contains("scheme=https"); } @@ -773,9 +769,9 @@ public abstract class AbstractServletWebServerFactoryTests { public void getValidSessionStoreWhenSessionStoreReferencesFile() throws Exception { AbstractServletWebServerFactory factory = getFactory(); factory.getSession().setStoreDir(this.temporaryFolder.newFile()); - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("points to a file"); - factory.getValidSessionStoreDir(false); + assertThatIllegalStateException() + .isThrownBy(() -> factory.getValidSessionStoreDir(false)) + .withMessageContaining("points to a file"); } @Test @@ -1003,8 +999,8 @@ public abstract class AbstractServletWebServerFactoryTests { } })); - this.thrown.expect(WebServerException.class); - factory.getWebServer().start(); + assertThatExceptionOfType(WebServerException.class) + .isThrownBy(() -> factory.getWebServer().start()); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java index c569ce59815..5649152195e 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/web/servlet/support/SpringBootServletInitializerTests.java @@ -24,7 +24,6 @@ import javax.servlet.ServletContext; import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.DirectFieldAccessor; import org.springframework.boot.SpringApplication; @@ -45,6 +44,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StandardServletEnvironment; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -56,9 +56,6 @@ import static org.mockito.Mockito.mock; */ public class SpringBootServletInitializerTests { - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Rule public OutputCapture output = new OutputCapture(); @@ -74,10 +71,10 @@ public class SpringBootServletInitializerTests { @Test public void failsWithoutConfigure() { - this.thrown.expect(IllegalStateException.class); - this.thrown.expectMessage("No SpringApplication sources have been defined"); - new MockSpringBootServletInitializer() - .createRootApplicationContext(this.servletContext); + assertThatIllegalStateException() + .isThrownBy(() -> new MockSpringBootServletInitializer() + .createRootApplicationContext(this.servletContext)) + .withMessageContaining("No SpringApplication sources have been defined"); } @Test diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java index 82480b57b51..0f40d8af345 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/webservices/client/WebServiceTemplateBuilderTests.java @@ -24,9 +24,7 @@ import java.util.Set; import javax.xml.transform.sax.SAXTransformerFactory; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -45,6 +43,7 @@ import org.springframework.ws.transport.http.ClientHttpRequestMessageSender; import org.springframework.ws.transport.http.HttpUrlConnectionMessageSender; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -61,9 +60,6 @@ public class WebServiceTemplateBuilderTests { private final WebServiceTemplateBuilder builder = new WebServiceTemplateBuilder(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private WebServiceMessageSender messageSender; @@ -102,16 +98,17 @@ public class WebServiceTemplateBuilderTests { @Test public void messageSendersWhenSendersAreAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("MessageSenders must not be null"); - this.builder.messageSenders((WebServiceMessageSender[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.messageSenders((WebServiceMessageSender[]) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test public void messageSendersCollectionWhenSendersAreAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("MessageSenders must not be null"); - this.builder.messageSenders((Collection) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.messageSenders( + (Collection) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test @@ -131,17 +128,18 @@ public class WebServiceTemplateBuilderTests { @Test public void additionalMessageSendersWhenSendersAreAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("MessageSenders must not be null"); - this.builder.additionalMessageSenders((WebServiceMessageSender[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .additionalMessageSenders((WebServiceMessageSender[]) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test public void additionalMessageSendersCollectionWhenSendersAreAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("MessageSenders must not be null"); - this.builder.additionalMessageSenders( - (Collection) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.additionalMessageSenders( + (Collection) null)) + .withMessageContaining("MessageSenders must not be null"); } @Test @@ -163,16 +161,17 @@ public class WebServiceTemplateBuilderTests { @Test public void interceptorsWhenInterceptorsAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Interceptors must not be null"); - this.builder.interceptors((ClientInterceptor[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.interceptors((ClientInterceptor[]) null)) + .withMessageContaining("Interceptors must not be null"); } @Test public void interceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Interceptors must not be null"); - this.builder.interceptors((Collection) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .interceptors((Collection) null)) + .withMessageContaining("Interceptors must not be null"); } @Test @@ -191,16 +190,16 @@ public class WebServiceTemplateBuilderTests { @Test public void additionalInterceptorsWhenInterceptorsAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Interceptors must not be null"); - this.builder.additionalInterceptors((ClientInterceptor[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.additionalInterceptors((ClientInterceptor[]) null)) + .withMessageContaining("Interceptors must not be null"); } @Test public void additionalInterceptorsCollectionWhenInterceptorsAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Interceptors must not be null"); - this.builder.additionalInterceptors((Set) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.additionalInterceptors((Set) null)) + .withMessageContaining("Interceptors must not be null"); } @Test @@ -225,17 +224,17 @@ public class WebServiceTemplateBuilderTests { @Test public void customizersWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.customizers((WebServiceTemplateCustomizer[]) null); + assertThatIllegalArgumentException().isThrownBy( + () -> this.builder.customizers((WebServiceTemplateCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test public void customizersCollectionWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder - .customizers((Collection) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.customizers( + (Collection) null)) + .withMessageContaining("Customizers must not be null"); } @Test @@ -269,17 +268,18 @@ public class WebServiceTemplateBuilderTests { @Test public void additionalCustomizersWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.additionalCustomizers((WebServiceTemplateCustomizer[]) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder + .additionalCustomizers((WebServiceTemplateCustomizer[]) null)) + .withMessageContaining("Customizers must not be null"); } @Test public void additionalCustomizersCollectionWhenCustomizersAreNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Customizers must not be null"); - this.builder.additionalCustomizers( - (Collection) null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.builder.additionalCustomizers( + (Collection) null)) + .withMessageContaining("Customizers must not be null"); } @Test diff --git a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Author.java b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Author.java index 70f5bae4908..5ad8b65b608 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Author.java +++ b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Author.java @@ -137,4 +137,5 @@ public class Author extends TableImpl { public Author rename(String name) { return new Author(name, null); } + } diff --git a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Book.java b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Book.java index 8b90b902c49..f570609a0a6 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Book.java +++ b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Book.java @@ -140,4 +140,5 @@ public class Book extends TableImpl { public Book rename(String name) { return new Book(name, null); } + } diff --git a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/BookStore.java b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/BookStore.java index 6bb06ff4a4e..2570226f192 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/BookStore.java +++ b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/BookStore.java @@ -98,4 +98,5 @@ public class BookStore extends TableImpl { public BookStore rename(String name) { return new BookStore(name, null); } + } diff --git a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/BookToBookStore.java b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/BookToBookStore.java index 87dcc42d625..82bf3748384 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/BookToBookStore.java +++ b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/BookToBookStore.java @@ -128,4 +128,5 @@ public class BookToBookStore extends TableImpl { public BookToBookStore rename(String name) { return new BookToBookStore(name, null); } + } diff --git a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/DefaultCatalog.java b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/DefaultCatalog.java index 8d7d9f5aba6..57ee959b355 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/DefaultCatalog.java +++ b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/DefaultCatalog.java @@ -49,4 +49,5 @@ public class DefaultCatalog extends CatalogImpl { private final List getSchemas0() { return Arrays.asList(Public.PUBLIC); } + } diff --git a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Keys.java b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Keys.java index c31be483460..0941413d7ab 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Keys.java +++ b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Keys.java @@ -28,9 +28,13 @@ public class Keys { // ------------------------------------------------------------------------- public static final UniqueKey CONSTRAINT_C = UniqueKeys0.CONSTRAINT_C; + public static final UniqueKey CONSTRAINT_7 = UniqueKeys0.CONSTRAINT_7; + public static final UniqueKey CONSTRAINT_1 = UniqueKeys0.CONSTRAINT_1; + public static final UniqueKey CONSTRAINT_F = UniqueKeys0.CONSTRAINT_F; + public static final UniqueKey CONSTRAINT_2 = UniqueKeys0.CONSTRAINT_2; // ------------------------------------------------------------------------- @@ -38,8 +42,11 @@ public class Keys { // ------------------------------------------------------------------------- public static final ForeignKey FK_BOOK_AUTHOR = ForeignKeys0.FK_BOOK_AUTHOR; + public static final ForeignKey FK_BOOK_LANGUAGE = ForeignKeys0.FK_BOOK_LANGUAGE; + public static final ForeignKey FK_B2BS_BOOK_STORE = ForeignKeys0.FK_B2BS_BOOK_STORE; + public static final ForeignKey FK_B2BS_BOOK = ForeignKeys0.FK_B2BS_BOOK; // ------------------------------------------------------------------------- @@ -47,32 +54,44 @@ public class Keys { // ------------------------------------------------------------------------- private static class UniqueKeys0 extends AbstractKeys { + public static final UniqueKey CONSTRAINT_C = createUniqueKey( Language.LANGUAGE, "CONSTRAINT_C", Language.LANGUAGE.ID); + public static final UniqueKey CONSTRAINT_7 = createUniqueKey( Author.AUTHOR, "CONSTRAINT_7", Author.AUTHOR.ID); + public static final UniqueKey CONSTRAINT_1 = createUniqueKey(Book.BOOK, "CONSTRAINT_1", Book.BOOK.ID); + public static final UniqueKey CONSTRAINT_F = createUniqueKey( BookStore.BOOK_STORE, "CONSTRAINT_F", BookStore.BOOK_STORE.NAME); + public static final UniqueKey CONSTRAINT_2 = createUniqueKey( BookToBookStore.BOOK_TO_BOOK_STORE, "CONSTRAINT_2", BookToBookStore.BOOK_TO_BOOK_STORE.NAME, BookToBookStore.BOOK_TO_BOOK_STORE.BOOK_ID); + } private static class ForeignKeys0 extends AbstractKeys { + public static final ForeignKey FK_BOOK_AUTHOR = createForeignKey( sample.jooq.domain.Keys.CONSTRAINT_7, Book.BOOK, "FK_BOOK_AUTHOR", Book.BOOK.AUTHOR_ID); + public static final ForeignKey FK_BOOK_LANGUAGE = createForeignKey( sample.jooq.domain.Keys.CONSTRAINT_C, Book.BOOK, "FK_BOOK_LANGUAGE", Book.BOOK.LANGUAGE_ID); + public static final ForeignKey FK_B2BS_BOOK_STORE = createForeignKey( sample.jooq.domain.Keys.CONSTRAINT_F, BookToBookStore.BOOK_TO_BOOK_STORE, "FK_B2BS_BOOK_STORE", BookToBookStore.BOOK_TO_BOOK_STORE.NAME); + public static final ForeignKey FK_B2BS_BOOK = createForeignKey( sample.jooq.domain.Keys.CONSTRAINT_1, BookToBookStore.BOOK_TO_BOOK_STORE, "FK_B2BS_BOOK", BookToBookStore.BOOK_TO_BOOK_STORE.BOOK_ID); + } + } diff --git a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Language.java b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Language.java index 6c901145497..5d378f14241 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Language.java +++ b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Language.java @@ -118,4 +118,5 @@ public class Language extends TableImpl { public Language rename(String name) { return new Language(name, null); } + } diff --git a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Public.java b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Public.java index 518929650f2..459e43a9a01 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Public.java +++ b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Public.java @@ -79,4 +79,5 @@ public class Public extends SchemaImpl { return Arrays.>asList(Language.LANGUAGE, Author.AUTHOR, Book.BOOK, BookStore.BOOK_STORE, BookToBookStore.BOOK_TO_BOOK_STORE); } + } diff --git a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Tables.java b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Tables.java index b31f88e74f0..5db3e0e23a7 100644 --- a/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Tables.java +++ b/spring-boot-samples/spring-boot-sample-jooq/gensrc/main/java/sample/jooq/domain/Tables.java @@ -37,4 +37,5 @@ public class Tables { * The table PUBLIC.BOOK_TO_BOOK_STORE. */ public static final BookToBookStore BOOK_TO_BOOK_STORE = sample.jooq.domain.BookToBookStore.BOOK_TO_BOOK_STORE; + } diff --git a/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java b/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java index 016065d1cc4..f16232c26e8 100644 --- a/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java +++ b/spring-boot-samples/spring-boot-sample-property-validation/src/test/java/sample/propertyvalidation/SamplePropertyValidationApplicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -17,9 +17,7 @@ package sample.propertyvalidation; import org.junit.After; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.autoconfigure.web.ServerProperties; @@ -27,6 +25,7 @@ import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link SamplePropertyValidationApplication}. @@ -36,9 +35,6 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class SamplePropertyValidationApplicationTests { - @Rule - public final ExpectedException thrown = ExpectedException.none(); - private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @After @@ -62,17 +58,17 @@ public class SamplePropertyValidationApplicationTests { this.context.register(SamplePropertyValidationApplication.class); TestPropertyValues.of("sample.host:xxxxxx", "sample.port:9090") .applyTo(this.context); - this.thrown.expect(BeanCreationException.class); - this.thrown.expectMessage("Failed to bind properties under 'sample'"); - this.context.refresh(); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.context.refresh()) + .withMessageContaining("Failed to bind properties under 'sample'"); } @Test public void bindNullHost() { this.context.register(SamplePropertyValidationApplication.class); - this.thrown.expect(BeanCreationException.class); - this.thrown.expectMessage("Failed to bind properties under 'sample'"); - this.context.refresh(); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.context.refresh()) + .withMessageContaining("Failed to bind properties under 'sample'"); } @Test diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java index c472353a615..51c31bc3c0c 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/UserEntityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package sample.test.domain; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -27,6 +25,7 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Data JPA tests for {@link User}. @@ -40,31 +39,25 @@ public class UserEntityTests { private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( "00000000000000000"); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private TestEntityManager entityManager; @Test public void createWhenUsernameIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Username must not be empty"); - new User(null, VIN); + assertThatIllegalArgumentException().isThrownBy(() -> new User(null, VIN)) + .withMessage("Username must not be empty"); } @Test public void createWhenUsernameIsEmptyShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Username must not be empty"); - new User("", VIN); + assertThatIllegalArgumentException().isThrownBy(() -> new User("", VIN)) + .withMessage("Username must not be empty"); } @Test public void createWhenVinIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("VIN must not be null"); - new User("sboot", null); + assertThatIllegalArgumentException().isThrownBy(() -> new User("sboot", null)) + .withMessage("VIN must not be null"); } @Test diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java index f9aef4deb09..5b46c5f099f 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/domain/VehicleIdentificationNumberTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2018 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. @@ -16,11 +16,10 @@ package sample.test.domain; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link VehicleIdentificationNumber}. @@ -34,28 +33,25 @@ public class VehicleIdentificationNumberTests { private static final String SAMPLE_VIN = "41549485710496749"; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void createWhenVinIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("VIN must not be null"); - new VehicleIdentificationNumber(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> new VehicleIdentificationNumber(null)) + .withMessage("VIN must not be null"); } @Test public void createWhenVinIsMoreThan17CharsShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("VIN must be exactly 17 characters"); - new VehicleIdentificationNumber("012345678901234567"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new VehicleIdentificationNumber("012345678901234567")) + .withMessage("VIN must be exactly 17 characters"); } @Test public void createWhenVinIsLessThan17CharsShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("VIN must be exactly 17 characters"); - new VehicleIdentificationNumber("0123456789012345"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new VehicleIdentificationNumber("0123456789012345")) + .withMessage("VIN must be exactly 17 characters"); } @Test diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java index 9acf27f0580..bac1711437a 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/service/RemoteVehicleDetailsServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2018 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. @@ -16,9 +16,7 @@ package sample.test.service; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import sample.test.domain.VehicleIdentificationNumber; @@ -32,6 +30,8 @@ import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.HttpServerErrorException; 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.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; @@ -48,9 +48,6 @@ public class RemoteVehicleDetailsServiceTests { private static final String VIN = "00000000000000000"; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Autowired private RemoteVehicleDetailsService service; @@ -59,9 +56,9 @@ public class RemoteVehicleDetailsServiceTests { @Test public void getVehicleDetailsWhenVinIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("VIN must not be null"); - this.service.getVehicleDetails(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.service.getVehicleDetails(null)) + .withMessage("VIN must not be null"); } @Test @@ -79,16 +76,18 @@ public class RemoteVehicleDetailsServiceTests { public void getVehicleDetailsWhenResultIsNotFoundShouldThrowException() { this.server.expect(requestTo("/vehicle/" + VIN + "/details")) .andRespond(withStatus(HttpStatus.NOT_FOUND)); - this.thrown.expect(VehicleIdentificationNumberNotFoundException.class); - this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN)); + assertThatExceptionOfType(VehicleIdentificationNumberNotFoundException.class) + .isThrownBy(() -> this.service + .getVehicleDetails(new VehicleIdentificationNumber(VIN))); } @Test public void getVehicleDetailsWhenResultIServerErrorShouldThrowException() { this.server.expect(requestTo("/vehicle/" + VIN + "/details")) .andRespond(withServerError()); - this.thrown.expect(HttpServerErrorException.class); - this.service.getVehicleDetails(new VehicleIdentificationNumber(VIN)); + assertThatExceptionOfType(HttpServerErrorException.class) + .isThrownBy(() -> this.service + .getVehicleDetails(new VehicleIdentificationNumber(VIN))); } private ClassPathResource getClassPathResource(String path) { diff --git a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java index 6198c4bf56a..1c5de216f68 100644 --- a/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java +++ b/spring-boot-samples/spring-boot-sample-test/src/test/java/sample/test/web/UserVehicleServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2018 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. @@ -17,9 +17,7 @@ package sample.test.web; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import sample.test.domain.User; @@ -29,6 +27,8 @@ import sample.test.service.VehicleDetails; import sample.test.service.VehicleDetailsService; 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.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; @@ -42,9 +42,6 @@ public class UserVehicleServiceTests { private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber( "00000000000000000"); - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Mock private VehicleDetailsService vehicleDetailsService; @@ -62,16 +59,16 @@ public class UserVehicleServiceTests { @Test public void getVehicleDetailsWhenUsernameIsNullShouldThrowException() { - this.thrown.expect(IllegalArgumentException.class); - this.thrown.expectMessage("Username must not be null"); - this.service.getVehicleDetails(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.service.getVehicleDetails(null)) + .withMessage("Username must not be null"); } @Test public void getVehicleDetailsWhenUsernameNotFoundShouldThrowException() { given(this.userRepository.findByUsername(anyString())).willReturn(null); - this.thrown.expect(UserNameNotFoundException.class); - this.service.getVehicleDetails("sboot"); + assertThatExceptionOfType(UserNameNotFoundException.class) + .isThrownBy(() -> this.service.getVehicleDetails("sboot")); } @Test diff --git a/src/checkstyle/checkstyle.xml b/src/checkstyle/checkstyle.xml index c8ab93869cf..607675132f6 100644 --- a/src/checkstyle/checkstyle.xml +++ b/src/checkstyle/checkstyle.xml @@ -9,7 +9,7 @@ + value="^reactor\.core\.support\.Assert, ^org\.junit\.rules\.ExpectedException" /> @@ -17,5 +17,14 @@ value="${main.basedir}/src/checkstyle/import-control.xml" /> + + + + + +