Migrate from ExpectedException rule to AssertJ

Replace ExpectedException JUnit rules with AssertJ exception
assertions.

Closes gh-14336
This commit is contained in:
Phillip Webb
2018-10-01 11:18:16 -07:00
parent 42cb0effc4
commit d76bba5e6f
273 changed files with 2752 additions and 3624 deletions

View File

@@ -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<Object>(
"CloudFoundryAuthorizationException with " + reason + " reason") {
@Override
public boolean matches(Object object) {
return ((object instanceof CloudFoundryAuthorizationException)
&& ((CloudFoundryAuthorizationException) object)
.getReason() == reason);
}
};
}
}

View File

@@ -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<CloudFoundryAuthorizationException> reasonRequirement(
Reason reason) {
return (ex) -> assertThat(ex.getReason()).isEqualTo(reason);
}
}

View File

@@ -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);
});
}

View File

@@ -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<CloudFoundryAuthorizationException> reasonRequirement(
Reason reason) {
return (ex) -> assertThat(ex.getReason()).isEqualTo(reason);
}
}

View File

@@ -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<String> 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<Throwable> isSSLHandshakeException() {
return instanceOf(SSLHandshakeException.class);
assertThatExceptionOfType(ResourceAccessException.class)
.isThrownBy(() -> otherRestTemplate.getForEntity(httpsUrl, String.class))
.withCauseInstanceOf(SSLHandshakeException.class);
}
private String getHttpsUrl() {

View File

@@ -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<CloudFoundryAuthorizationException> reasonRequirement(
Reason reason) {
return (ex) -> assertThat(ex.getReason()).isEqualTo(reason);
}
}

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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