From 4f3e59966c4bbc68722568316f468be3908b38f1 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 4 Aug 2020 14:20:45 -0700 Subject: [PATCH] Migrate to assertThatExceptionOfType Consistently use `assertThatExceptionOfType(...).isThrownBy(...)` rather than `assertThatCode` or `assertThatThrownBy`. This aligns with Spring Boot and Spring Cloud. It also allows the convenience `assertThatIllegalArgument` and `assertThatIllegalState` methods to be used. Issue gh-8945 --- .../rsocket/HelloRSocketITests.java | 10 +- ...RSocketMessageHandlerConnectionITests.java | 25 ++-- .../rsocket/RSocketMessageHandlerITests.java | 27 ++-- .../rsocket/SimpleAuthenticationITests.java | 6 +- .../AuthenticationConfigurationTests.java | 17 ++- .../EnableReactiveMethodSecurityTests.java | 10 +- ...lobalMethodSecurityConfigurationTests.java | 24 ++-- ...lMethodSecurityExpressionHandlerTests.java | 13 +- .../NamespaceGlobalMethodSecurityTests.java | 66 +++++----- ...SampleEnableGlobalMethodSecurityTests.java | 9 +- .../annotation/sec2758/Sec2758Tests.java | 5 +- .../WebSecurityConfigurerAdapterTests.java | 3 +- .../OAuth2ClientConfigurationTests.java | 30 +++-- .../WebSecurityConfigurationTests.java | 27 ++-- .../web/configurers/CorsConfigurerTests.java | 6 +- .../web/configurers/CsrfConfigurerTests.java | 12 +- ...essionUrlAuthorizationConfigurerTests.java | 17 +-- .../configurers/HeadersConfigurerTests.java | 17 ++- .../configurers/LogoutConfigurerTests.java | 32 +++-- .../NamespaceHttpFirewallTests.java | 13 +- .../configurers/PermitAllSupportTests.java | 8 +- .../RememberMeConfigurerTests.java | 17 ++- .../client/OAuth2LoginConfigurerTests.java | 10 +- .../OAuth2ResourceServerConfigurerTests.java | 46 ++++--- .../UserDetailsResourceFactoryBeanTests.java | 15 ++- ...eyConversionServicePostProcessorTests.java | 6 +- .../config/http/AccessDeniedConfigTests.java | 10 +- .../config/http/FormLoginConfigTests.java | 10 +- .../config/http/HttpCorsConfigTests.java | 7 +- .../config/http/HttpHeadersConfigTests.java | 101 +++++++-------- .../config/http/InterceptUrlConfigTests.java | 18 +-- .../config/http/MiscHttpConfigTests.java | 15 +-- .../http/MultiHttpBlockConfigTests.java | 12 +- ...sourceServerBeanDefinitionParserTests.java | 30 ++--- .../config/http/OpenIDConfigTests.java | 6 +- .../config/http/RememberMeConfigTests.java | 25 ++-- .../config/web/server/FormLoginTests.java | 7 +- .../server/OAuth2ResourceServerSpecTests.java | 11 +- .../WebSocketMessageBrokerConfigTests.java | 91 +++++++------ ...oryReactiveAuthenticationManagerTests.java | 7 +- .../dao/DaoAuthenticationProviderTests.java | 4 +- .../jaas/JaasGrantedAuthorityTests.java | 14 +- .../converter/RsaKeyConvertersTests.java | 8 +- .../SecurityJackson2ModulesTests.java | 5 +- .../DelegatingPasswordEncoderTests.java | 38 +++--- etc/checkstyle/checkstyle.xml | 8 ++ .../ldap/server/ApacheDSContainerTests.java | 12 +- ...UserDetailsManagerModifyPasswordTests.java | 6 +- ...deOAuth2AuthorizedClientProviderTests.java | 10 +- ...veOAuth2AuthorizedClientProviderTests.java | 10 +- ...iceOAuth2AuthorizedClientManagerTests.java | 49 +++---- ...iveOAuth2AuthorizedClientManagerTests.java | 62 +++++---- ...lsOAuth2AuthorizedClientProviderTests.java | 24 ++-- ...veOAuth2AuthorizedClientProviderTests.java | 24 ++-- ...ngOAuth2AuthorizedClientProviderTests.java | 14 +- ...veOAuth2AuthorizedClientProviderTests.java | 14 +- ...oryOAuth2AuthorizedClientServiceTests.java | 7 +- ...iveOAuth2AuthorizedClientServiceTests.java | 52 ++++---- ...dbcOAuth2AuthorizedClientServiceTests.java | 68 +++++----- .../OAuth2AuthorizationContextTests.java | 17 ++- .../client/OAuth2AuthorizeRequestTests.java | 21 +-- .../client/OAuth2AuthorizedClientIdTests.java | 10 +- ...2AuthorizedClientProviderBuilderTests.java | 15 ++- ...rdOAuth2AuthorizedClientProviderTests.java | 24 ++-- ...veOAuth2AuthorizedClientProviderTests.java | 24 ++-- ...2AuthorizedClientProviderBuilderTests.java | 15 ++- ...enOAuth2AuthorizedClientProviderTests.java | 30 +++-- ...veOAuth2AuthorizedClientProviderTests.java | 30 +++-- ...zationCodeAuthenticationProviderTests.java | 22 ++-- ...orizationCodeAuthenticationTokenTests.java | 24 ++-- ...odeReactiveAuthenticationManagerTests.java | 8 +- ...ginReactiveAuthenticationManagerTests.java | 28 ++-- ...orizationCodeTokenResponseClientTests.java | 50 +++---- ...ntCredentialsTokenResponseClientTests.java | 48 +++---- ...faultPasswordTokenResponseClientTests.java | 32 ++--- ...tRefreshTokenTokenResponseClientTests.java | 34 ++--- ...th2ClientCredentialsGrantRequestTests.java | 9 +- .../OAuth2PasswordGrantRequestTests.java | 33 +++-- .../OAuth2RefreshTokenGrantRequestTests.java | 17 ++- ...orizationCodeTokenResponseClientTests.java | 20 +-- ...ntCredentialsTokenResponseClientTests.java | 12 +- ...ctivePasswordTokenResponseClientTests.java | 39 +++--- ...eRefreshTokenTokenResponseClientTests.java | 36 +++--- .../OAuth2ErrorResponseErrorHandlerTests.java | 14 +- ...uth2AuthenticationExceptionMixinTests.java | 6 +- .../OAuth2AuthenticationTokenMixinTests.java | 6 +- .../OAuth2AuthorizationRequestMixinTests.java | 11 +- .../OAuth2AuthorizedClientMixinTests.java | 6 +- ...odeReactiveAuthenticationManagerTests.java | 41 +++--- .../OidcIdTokenDecoderFactoryTests.java | 41 +++--- .../OidcIdTokenValidatorTests.java | 9 +- ...eactiveOidcIdTokenDecoderFactoryTests.java | 41 +++--- .../OidcReactiveOAuth2UserServiceTests.java | 15 +-- .../oidc/userinfo/OidcUserRequestTests.java | 14 +- .../oidc/userinfo/OidcUserServiceTests.java | 11 +- ...entInitiatedLogoutSuccessHandlerTests.java | 8 +- ...tiatedServerLogoutSuccessHandlerTests.java | 8 +- .../registration/ClientRegistrationTests.java | 56 ++++---- .../ClientRegistrationsTests.java | 55 ++++---- ...tiveClientRegistrationRepositoryTests.java | 17 ++- ...DefaultReactiveOAuth2UserServiceTests.java | 30 +++-- .../userinfo/OAuth2UserRequestTests.java | 8 +- ...OAuth2AuthorizedClientRepositoryTests.java | 10 +- ...uth2AuthorizationRequestResolverTests.java | 18 ++- ...ultOAuth2AuthorizedClientManagerTests.java | 57 ++++---- ...iveOAuth2AuthorizedClientManagerTests.java | 74 ++++++----- ...h2AuthorizationRequestRepositoryTests.java | 25 ++-- ...OAuth2AuthorizedClientRepositoryTests.java | 34 +++-- ...uth2AuthorizationCodeGrantFilterTests.java | 21 +-- ...thorizationRequestRedirectFilterTests.java | 15 +-- .../OAuth2LoginAuthenticationFilterTests.java | 25 ++-- ...AuthorizedClientArgumentResolverTests.java | 53 ++++---- ...zedClientExchangeFilterFunctionITests.java | 6 +- ...izedClientExchangeFilterFunctionTests.java | 99 +++++++------- ...izedClientExchangeFilterFunctionTests.java | 87 +++++++------ ...AuthorizedClientArgumentResolverTests.java | 22 ++-- ...OAuth2AuthorizedClientRepositoryTests.java | 10 +- ...uth2AuthorizationRequestResolverTests.java | 13 +- ...2AuthorizationCodeGrantWebFilterTests.java | 39 +++--- ...rizationRequestRedirectWebFilterTests.java | 6 +- ...CodeAuthenticationTokenConverterTests.java | 12 +- ...OAuth2AuthorizedClientRepositoryTests.java | 47 +++---- ...erAuthorizationRequestRepositoryTests.java | 17 ++- ...OAuth2AuthorizedClientRepositoryTests.java | 31 ++--- .../core/AuthenticationMethodTests.java | 5 +- ...aultOAuth2AuthenticatedPrincipalTests.java | 10 +- .../DelegatingOAuth2TokenValidatorTests.java | 7 +- .../converter/ClaimTypeConverterTests.java | 7 +- .../OAuth2AuthorizationRequestTests.java | 42 +++--- .../OAuth2AuthorizationResponseTests.java | 9 +- ...okenResponseHttpMessageConverterTests.java | 22 ++-- .../OAuth2ErrorHttpMessageConverterTests.java | 21 ++- .../core/oidc/OidcIdTokenBuilderTests.java | 10 +- .../oidc/user/OidcUserAuthorityTests.java | 3 +- .../function/OAuth2BodyExtractorsTests.java | 10 +- .../security/oauth2/jwt/JwtBuilderTests.java | 10 +- .../oauth2/jwt/JwtClaimValidatorTests.java | 9 +- .../security/oauth2/jwt/JwtDecodersTests.java | 54 ++++---- .../oauth2/jwt/JwtIssuerValidatorTests.java | 6 +- .../jwt/JwtTimestampValidatorTests.java | 6 +- .../jwt/MappedJwtClaimSetConverterTests.java | 16 +-- .../jwt/NimbusJwtDecoderJwkSupportTests.java | 50 ++++--- .../oauth2/jwt/NimbusJwtDecoderTests.java | 103 ++++++++------- .../jwt/NimbusReactiveJwtDecoderTests.java | 122 +++++++++--------- .../oauth2/jwt/ReactiveJwtDecodersTests.java | 67 +++++----- .../BearerTokenAuthenticationTokenTests.java | 10 +- .../resource/BearerTokenErrorTests.java | 54 ++++---- .../BearerTokenAuthenticationTests.java | 12 +- .../JwtAuthenticationProviderTests.java | 13 +- .../JwtAuthenticationTokenTests.java | 6 +- ...uerAuthenticationManagerResolverTests.java | 44 ++++--- ...iveAuthenticationManagerResolverTests.java | 45 ++++--- ...JwtReactiveAuthenticationManagerTests.java | 20 +-- ...paqueTokenAuthenticationProviderTests.java | 9 +- ...kenReactiveAuthenticationManagerTests.java | 10 +- .../NimbusOpaqueTokenIntrospectorTests.java | 39 +++--- ...sReactiveOpaqueTokenIntrospectorTests.java | 48 +++---- ...rospectionAuthenticatedPrincipalTests.java | 10 +- ...rerTokenAuthenticationEntryPointTests.java | 3 +- .../BearerTokenAuthenticationFilterTests.java | 21 ++- .../web/DefaultBearerTokenResolverTests.java | 22 ++-- .../web/HeaderBearerTokenResolverTests.java | 10 +- .../BearerTokenAccessDeniedHandlerTests.java | 3 +- ...erTokenServerAccessDeniedHandlerTests.java | 3 +- ...arerTokenAuthenticationConverterTests.java | 43 +++--- .../AnonymousPayloadInterceptorTests.java | 16 +-- ...AuthenticationPayloadInterceptorTests.java | 4 +- .../core/PayloadInterceptorRSocketTests.java | 24 ++-- .../core/PayloadSocketAcceptorTests.java | 15 ++- .../OpenSamlInitializationServiceTests.java | 7 +- ...faultSaml2AuthenticatedPrincipalTests.java | 10 +- .../OpenSamlAuthenticationProviderTests.java | 12 +- ...SamlAuthenticationRequestFactoryTests.java | 5 +- ...ationBuilderHttpMessageConverterTests.java | 18 +-- .../RelyingPartyRegistrationsTests.java | 10 +- ...ebSsoAuthenticationRequestFilterTests.java | 6 +- ...RelyingPartyRegistrationResolverTests.java | 5 +- ...enticationRequestContextResolverTests.java | 5 +- ...aml2AuthenticationTokenConverterTests.java | 4 +- .../service/web/Saml2MetadataFilterTests.java | 4 +- ...ockServerConfigurersOAuth2ClientTests.java | 7 +- ...equestPostProcessorsOAuth2ClientTests.java | 7 +- .../ExceptionTranslationFilterTests.java | 6 +- .../web/access/intercept/RequestKeyTests.java | 6 +- .../SwitchUserGrantedAuthorityTests.java | 14 +- ...ecurityWebApplicationInitializerTests.java | 52 ++++---- .../web/firewall/StrictHttpFirewallTests.java | 53 ++++---- .../writers/CompositeHeaderWriterTests.java | 5 +- .../FeaturePolicyHeaderWriterTests.java | 10 +- ...icationPrincipalArgumentResolverTests.java | 4 +- .../savedrequest/CookieRequestCacheTests.java | 5 +- ...onverterServerWebExchangeMatcherTests.java | 7 +- ...rverAuthenticationSuccessHandlerTests.java | 12 +- .../DelegatingServerLogoutHandlerTests.java | 20 +-- .../HttpsRedirectWebFilterTests.java | 11 +- .../util/matcher/IpAddressMatcherTests.java | 13 +- 196 files changed, 2241 insertions(+), 2116 deletions(-) diff --git a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/HelloRSocketITests.java b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/HelloRSocketITests.java index 7262646c809..1277074e20f 100644 --- a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/HelloRSocketITests.java +++ b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/HelloRSocketITests.java @@ -20,6 +20,7 @@ import java.util.List; import io.rsocket.RSocketFactory; +import io.rsocket.exceptions.RejectedSetupException; import io.rsocket.frame.decoder.PayloadDecoder; import io.rsocket.transport.netty.server.CloseableChannel; import io.rsocket.transport.netty.server.TcpServerTransport; @@ -46,7 +47,7 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch @@ -87,10 +88,11 @@ public void retrieveMonoWhenSecureThenDenied() throws Exception { this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies()) .connectTcp("localhost", this.server.address().getPort()).block(); String data = "rob"; - assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block()) - .isNotNull(); + assertThatExceptionOfType(Exception.class).isThrownBy( + () -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block()) + .matches((ex) -> ex instanceof RejectedSetupException + || ex.getClass().toString().contains("ReactiveException")); // FIXME: https://github.com/rsocket/rsocket-java/issues/686 - // .isInstanceOf(RejectedSetupException.class); assertThat(this.controller.payloads).isEmpty(); } diff --git a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerConnectionITests.java b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerConnectionITests.java index ecacae6b212..2c3c6038386 100644 --- a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerConnectionITests.java +++ b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerConnectionITests.java @@ -21,6 +21,7 @@ import io.rsocket.RSocketFactory; import io.rsocket.exceptions.ApplicationErrorException; +import io.rsocket.exceptions.RejectedSetupException; import io.rsocket.frame.decoder.PayloadDecoder; import io.rsocket.transport.netty.server.CloseableChannel; import io.rsocket.transport.netty.server.TcpServerTransport; @@ -49,7 +50,7 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch @@ -103,8 +104,8 @@ public void routeWhenNotAuthorized() { UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password"); this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE) .connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block(); - assertThatCode(() -> this.requester.route("secure.admin.retrieve-mono").data("data").retrieveMono(String.class) - .block()).isInstanceOf(ApplicationErrorException.class); + assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(() -> this.requester + .route("secure.admin.retrieve-mono").data("data").retrieveMono(String.class).block()); } @Test @@ -137,10 +138,11 @@ public void routeWhenStreamCredentialsHaveAuthority() { public void connectWhenNotAuthenticated() { this.requester = requester().connectTcp(this.server.address().getHostName(), this.server.address().getPort()) .block(); - assertThatCode(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block()) - .isNotNull(); + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block()) + .matches((ex) -> ex instanceof RejectedSetupException + || ex.getClass().toString().contains("ReactiveException")); // FIXME: https://github.com/rsocket/rsocket-java/issues/686 - // .isInstanceOf(RejectedSetupException.class); } @Test @@ -148,10 +150,11 @@ public void connectWhenNotAuthorized() { UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("evil", "password"); this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE) .connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block(); - assertThatCode(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block()) - .isNotNull(); + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block()) + .matches((ex) -> ex instanceof RejectedSetupException + || ex.getClass().toString().contains("ReactiveException")); // FIXME: https://github.com/rsocket/rsocket-java/issues/686 - // .isInstanceOf(RejectedSetupException.class); } @Test @@ -159,8 +162,8 @@ public void connectionDenied() { UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password"); this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE) .connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block(); - assertThatCode(() -> this.requester.route("prohibit").data("data").retrieveMono(String.class).block()) - .isInstanceOf(ApplicationErrorException.class); + assertThatExceptionOfType(ApplicationErrorException.class) + .isThrownBy(() -> this.requester.route("prohibit").data("data").retrieveMono(String.class).block()); } @Test diff --git a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerITests.java b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerITests.java index 9b4f37a09dd..ee91c97f308 100644 --- a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerITests.java +++ b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerITests.java @@ -52,7 +52,7 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch @@ -96,8 +96,9 @@ public void dispose() { @Test public void retrieveMonoWhenSecureThenDenied() throws Exception { String data = "rob"; - assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block()) - .isInstanceOf(ApplicationErrorException.class).hasMessageContaining("Access Denied"); + assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy( + () -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block()) + .withMessageContaining("Access Denied"); assertThat(this.controller.payloads).isEmpty(); } @@ -105,10 +106,11 @@ public void retrieveMonoWhenSecureThenDenied() throws Exception { public void retrieveMonoWhenAuthenticationFailedThenException() throws Exception { String data = "rob"; UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("invalid", "password"); - assertThatCode(() -> this.requester.route("secure.retrieve-mono") - .metadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE).data(data) - .retrieveMono(String.class).block()).isInstanceOf(ApplicationErrorException.class) - .hasMessageContaining("Invalid Credentials"); + assertThatExceptionOfType(ApplicationErrorException.class) + .isThrownBy(() -> this.requester.route("secure.retrieve-mono") + .metadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE).data(data) + .retrieveMono(String.class).block()) + .withMessageContaining("Invalid Credentials"); assertThat(this.controller.payloads).isEmpty(); } @@ -134,9 +136,10 @@ public void retrieveMonoWhenPublicThenGranted() throws Exception { @Test public void retrieveFluxWhenDataFluxAndSecureThenDenied() throws Exception { Flux data = Flux.just("a", "b", "c"); - assertThatCode(() -> this.requester.route("secure.retrieve-flux").data(data, String.class) - .retrieveFlux(String.class).collectList().block()).isInstanceOf(ApplicationErrorException.class) - .hasMessageContaining("Access Denied"); + assertThatExceptionOfType(ApplicationErrorException.class) + .isThrownBy(() -> this.requester.route("secure.retrieve-flux").data(data, String.class) + .retrieveFlux(String.class).collectList().block()) + .withMessageContaining("Access Denied"); assertThat(this.controller.payloads).isEmpty(); } @@ -152,9 +155,9 @@ public void retrieveFluxWhenDataFluxAndPublicThenGranted() throws Exception { @Test public void retrieveFluxWhenDataStringAndSecureThenDenied() throws Exception { String data = "a"; - assertThatCode( + assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy( () -> this.requester.route("secure.hello").data(data).retrieveFlux(String.class).collectList().block()) - .isInstanceOf(ApplicationErrorException.class).hasMessageContaining("Access Denied"); + .withMessageContaining("Access Denied"); assertThat(this.controller.payloads).isEmpty(); } diff --git a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/SimpleAuthenticationITests.java b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/SimpleAuthenticationITests.java index 29f1c3b4956..370e1786ce7 100644 --- a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/SimpleAuthenticationITests.java +++ b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/SimpleAuthenticationITests.java @@ -52,7 +52,7 @@ import org.springframework.util.MimeTypeUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch @@ -93,8 +93,8 @@ public void retrieveMonoWhenSecureThenDenied() throws Exception { this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies()) .connectTcp("localhost", this.server.address().getPort()).block(); String data = "rob"; - assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block()) - .isInstanceOf(ApplicationErrorException.class); + assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy( + () -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block()); assertThat(this.controller.payloads).isEmpty(); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java index 9c5c1532009..d410060767f 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java @@ -63,7 +63,7 @@ import org.springframework.security.provisioning.InMemoryUserDetailsManager; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.startsWith; @@ -165,9 +165,8 @@ public void getAuthenticationWhenConfiguredThenBootNotTrigger() throws Exception new BootGlobalAuthenticationConfigurerAdapter())); AuthenticationManager authenticationManager = config.getAuthenticationManager(); authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); - assertThatThrownBy( - () -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password"))) - .isInstanceOf(AuthenticationException.class); + assertThatExceptionOfType(AuthenticationException.class).isThrownBy( + () -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password"))); } @Test @@ -207,8 +206,8 @@ public void getAuthenticationWhenUserDetailsServiceBeanThenAuthenticationManager .getAuthenticationManager(); given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user()); am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); - assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid"))) - .isInstanceOf(AuthenticationException.class); + assertThatExceptionOfType(AuthenticationException.class) + .isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid"))); } @Test @@ -222,8 +221,8 @@ public void getAuthenticationWhenUserDetailsServiceAndPasswordEncoderBeanThenEnc given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(), User.withUserDetails(user).build()); am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); - assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid"))) - .isInstanceOf(AuthenticationException.class); + assertThatExceptionOfType(AuthenticationException.class) + .isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid"))); } @Test @@ -291,7 +290,7 @@ public void getAuthenticationManagerWhenAuthenticationConfigurationSubclassedThe this.spring.register(AuthenticationConfigurationSubclass.class).autowire(); AuthenticationManagerBuilder ap = this.spring.getContext().getBean(AuthenticationManagerBuilder.class); this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager(); - assertThatThrownBy(ap::build).isInstanceOf(AlreadyBuiltException.class); + assertThatExceptionOfType(AlreadyBuiltException.class).isThrownBy(ap::build); } @EnableGlobalMethodSecurity(securedEnabled = true) diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java index 4a905ebe884..83ff811ce7d 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java @@ -35,7 +35,7 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; @@ -73,9 +73,11 @@ public void setConfig(Config config) { @Test public void notPublisherPreAuthorizeFindByIdThenThrowsIllegalStateException() { - assertThatThrownBy(() -> this.messageService.notPublisherPreAuthorizeFindById(1L)) - .isInstanceOf(IllegalStateException.class).extracting(Throwable::getMessage).isEqualTo( - "The returnType class java.lang.String on public abstract java.lang.String org.springframework.security.config.annotation.method.configuration.ReactiveMessageService.notPublisherPreAuthorizeFindById(long) must return an instance of org.reactivestreams.Publisher (i.e. Mono / Flux) in order to support Reactor Context"); + assertThatIllegalStateException().isThrownBy(() -> this.messageService.notPublisherPreAuthorizeFindById(1L)) + .withMessage("The returnType class java.lang.String on public abstract java.lang.String " + + "org.springframework.security.config.annotation.method.configuration.ReactiveMessageService" + + ".notPublisherPreAuthorizeFindById(long) must return an instance of org.reactivestreams" + + ".Publisher (i.e. Mono / Flux) in order to support Reactor Context"); } @Test diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java index 713839542b3..5b4ce0106ed 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java @@ -61,7 +61,7 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -125,7 +125,8 @@ public void methodSecurityWhenAuthenticationTrustResolverIsBeanThenAutowires() { this.spring.register(CustomTrustResolverConfig.class).autowire(); AuthenticationTrustResolver trustResolver = this.spring.getContext().getBean(AuthenticationTrustResolver.class); given(trustResolver.isAnonymous(any())).willReturn(true, false); - assertThatThrownBy(() -> this.service.preAuthorizeNotAnonymous()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> this.service.preAuthorizeNotAnonymous()); this.service.preAuthorizeNotAnonymous(); verify(trustResolver, atLeastOnce()).isAnonymous(any()); } @@ -136,7 +137,7 @@ public void methodSecurityWhenAuthenticationTrustResolverIsBeanThenAutowires() { public void defaultWebSecurityExpressionHandlerHasBeanResolverSet() { this.spring.register(ExpressionHandlerHasBeanResolverSetConfig.class).autowire(); Authz authz = this.spring.getContext().getBean(Authz.class); - assertThatThrownBy(() -> this.service.preAuthorizeBean(false)).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorizeBean(false)); this.service.preAuthorizeBean(true); } @@ -144,7 +145,7 @@ public void defaultWebSecurityExpressionHandlerHasBeanResolverSet() { @WithMockUser public void methodSecuritySupportsAnnotaitonsOnInterfaceParamerNames() { this.spring.register(MethodSecurityServiceConfig.class).autowire(); - assertThatThrownBy(() -> this.service.postAnnotation("deny")).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.postAnnotation("deny")); this.service.postAnnotation("grant"); // no exception } @@ -157,7 +158,8 @@ public void globalMethodSecurityConfigurationAutowiresPermissionEvaluator() { given(permission.hasPermission(any(), eq("something"), eq("read"))).willReturn(true, false); this.service.hasPermission("something"); // no exception - assertThatThrownBy(() -> this.service.hasPermission("something")).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> this.service.hasPermission("something")); } @Test @@ -171,7 +173,7 @@ public void multiPermissionEvaluatorConfig() { @WithMockUser public void enableGlobalMethodSecurityWorksOnSuperclass() { this.spring.register(ChildConfig.class).autowire(); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); } // SEC-2479 @@ -186,7 +188,7 @@ public void supportAuthenticationManagerInParent() { child.register(Sec2479ChildConfig.class); child.refresh(); this.spring.context(child).autowire(); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); } } } @@ -228,7 +230,7 @@ public void globalSecurityProxiesSecurity() { @WithMockUser public void preAuthorizeBeanSpel() { this.spring.register(PreAuthorizeBeanSpelConfig.class).autowire(); - assertThatThrownBy(() -> this.service.preAuthorizeBean(false)).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorizeBean(false)); this.service.preAuthorizeBean(true); } @@ -237,7 +239,7 @@ public void preAuthorizeBeanSpel() { @WithMockUser public void roleHierarchy() { this.spring.register(RoleHierarchyConfig.class).autowire(); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); this.service.preAuthorizeAdmin(); } @@ -247,7 +249,7 @@ public void grantedAuthorityDefaultsAutowires() { this.spring.register(CustomGrantedAuthorityConfig.class).autowire(); CustomGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext() .getBean(CustomGrantedAuthorityConfig.CustomAuthorityService.class); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); customService.customPrefixRoleUser(); // no exception } @@ -258,7 +260,7 @@ public void grantedAuthorityDefaultsWithEmptyRolePrefix() { this.spring.register(EmptyRolePrefixGrantedAuthorityConfig.class).autowire(); EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext() .getBean(EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService.class); - assertThatThrownBy(() -> this.service.securedUser()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.securedUser()); customService.emptyPrefixRoleUser(); // no exception } diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityExpressionHandlerTests.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityExpressionHandlerTests.java index 90d0d45f081..b9bf7080b8c 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityExpressionHandlerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityExpressionHandlerTests.java @@ -33,8 +33,8 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch @@ -54,16 +54,17 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests { @WithMockUser public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPreAuthorizesAccordingly() { this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire(); - assertThatCode(() -> this.service.hasPermission("granted")).doesNotThrowAnyException(); - assertThatThrownBy(() -> this.service.hasPermission("denied")).isInstanceOf(AccessDeniedException.class); + assertThat(this.service.hasPermission("granted")).isNull(); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.hasPermission("denied")); } @Test @WithMockUser public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPostAuthorizesAccordingly() { this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire(); - assertThatCode(() -> this.service.postHasPermission("granted")).doesNotThrowAnyException(); - assertThatThrownBy(() -> this.service.postHasPermission("denied")).isInstanceOf(AccessDeniedException.class); + assertThat(this.service.postHasPermission("granted")).isNull(); + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> this.service.postHasPermission("denied")); } @EnableGlobalMethodSecurity(prePostEnabled = true) diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityTests.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityTests.java index e61d475da54..fd46256b4ba 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityTests.java @@ -57,8 +57,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch @@ -78,32 +77,32 @@ public class NamespaceGlobalMethodSecurityTests { @WithMockUser public void methodSecurityWhenCustomAccessDecisionManagerThenAuthorizes() { this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire(); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); - assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.secured()); } @Test @WithMockUser public void methodSecurityWhenCustomAfterInvocationManagerThenAuthorizes() { this.spring.register(CustomAfterInvocationManagerConfig.class, MethodSecurityServiceConfig.class).autowire(); - assertThatThrownBy(() -> this.service.preAuthorizePermitAll()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorizePermitAll()); } @Test @WithMockUser public void methodSecurityWhenCustomAuthenticationManagerThenAuthorizes() { this.spring.register(CustomAuthenticationConfig.class, MethodSecurityServiceConfig.class).autowire(); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(UnsupportedOperationException.class); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.preAuthorize()); } @Test @WithMockUser public void methodSecurityWhenJsr250EnabledThenAuthorizes() { this.spring.register(Jsr250Config.class, MethodSecurityServiceConfig.class).autowire(); - assertThatCode(() -> this.service.preAuthorize()).doesNotThrowAnyException(); - assertThatCode(() -> this.service.secured()).doesNotThrowAnyException(); - assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class); - assertThatCode(() -> this.service.jsr250PermitAll()).doesNotThrowAnyException(); + this.service.preAuthorize(); + this.service.secured(); + this.service.jsr250PermitAll(); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250()); } @Test @@ -111,9 +110,9 @@ public void methodSecurityWhenJsr250EnabledThenAuthorizes() { public void methodSecurityWhenCustomMethodSecurityMetadataSourceThenAuthorizes() { this.spring.register(CustomMethodSecurityMetadataSourceConfig.class, MethodSecurityServiceConfig.class) .autowire(); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); - assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class); - assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.secured()); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250()); } @Test @@ -144,7 +143,7 @@ public void methodSecurityWhenOrderSpecifiedThenConfigured() { this.spring.register(CustomOrderConfig.class, MethodSecurityServiceConfig.class).autowire(); assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class) .getOrder()).isEqualTo(-135); - assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250()); } @Test @@ -153,7 +152,7 @@ public void methodSecurityWhenOrderUnspecifiedThenConfiguredToLowestPrecedence() this.spring.register(DefaultOrderConfig.class, MethodSecurityServiceConfig.class).autowire(); assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class) .getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); - assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(UnsupportedOperationException.class); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250()); } @Test @@ -163,25 +162,25 @@ public void methodSecurityWhenOrderUnspecifiedAndCustomGlobalMethodSecurityConfi .autowire(); assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class) .getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); - assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(UnsupportedOperationException.class); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250()); } @Test @WithMockUser public void methodSecurityWhenPrePostEnabledThenPreAuthorizes() { this.spring.register(PreAuthorizeConfig.class, MethodSecurityServiceConfig.class).autowire(); - assertThatCode(() -> this.service.secured()).doesNotThrowAnyException(); - assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException(); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); + this.service.secured(); + this.service.jsr250(); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); } @Test @WithMockUser public void methodSecurityWhenPrePostEnabledAndCustomGlobalMethodSecurityConfigurationThenPreAuthorizes() { this.spring.register(PreAuthorizeExtendsGMSCConfig.class, MethodSecurityServiceConfig.class).autowire(); - assertThatCode(() -> this.service.secured()).doesNotThrowAnyException(); - assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException(); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); + this.service.secured(); + this.service.jsr250(); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); } @Test @@ -190,7 +189,7 @@ public void methodSecurityWhenProxyTargetClassThenDoesNotWireToInterface() { this.spring.register(ProxyTargetClassConfig.class, MethodSecurityServiceConfig.class).autowire(); // make sure service was actually proxied assertThat(this.service.getClass().getInterfaces()).doesNotContain(MethodSecurityService.class); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); } @Test @@ -198,7 +197,7 @@ public void methodSecurityWhenProxyTargetClassThenDoesNotWireToInterface() { public void methodSecurityWhenDefaultProxyThenWiresToInterface() { this.spring.register(DefaultProxyConfig.class, MethodSecurityServiceConfig.class).autowire(); assertThat(this.service.getClass().getInterfaces()).contains(MethodSecurityService.class); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); } @Test @@ -213,26 +212,27 @@ public void methodSecurityWhenCustomRunAsManagerThenRunAsWrapsAuthentication() { @WithMockUser public void methodSecurityWhenSecuredEnabledThenSecures() { this.spring.register(SecuredConfig.class, MethodSecurityServiceConfig.class).autowire(); - assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class); - assertThatCode(() -> this.service.securedUser()).doesNotThrowAnyException(); - assertThatCode(() -> this.service.preAuthorize()).doesNotThrowAnyException(); - assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException(); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.secured()); + this.service.securedUser(); + this.service.preAuthorize(); + this.service.jsr250(); } @Test @WithMockUser public void methodSecurityWhenMissingEnableAnnotationThenShowsHelpfulError() { - assertThatThrownBy(() -> this.spring.register(ExtendsNoEnableAnntotationConfig.class).autowire()) - .hasStackTraceContaining(EnableGlobalMethodSecurity.class.getName() + " is required"); + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> this.spring.register(ExtendsNoEnableAnntotationConfig.class).autowire()) + .withStackTraceContaining(EnableGlobalMethodSecurity.class.getName() + " is required"); } @Test @WithMockUser public void methodSecurityWhenImportingGlobalMethodSecurityConfigurationSubclassThenAuthorizes() { this.spring.register(ImportSubclassGMSCConfig.class, MethodSecurityServiceConfig.class).autowire(); - assertThatCode(() -> this.service.secured()).doesNotThrowAnyException(); - assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException(); - assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class); + this.service.secured(); + this.service.jsr250(); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize()); } @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/SampleEnableGlobalMethodSecurityTests.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/SampleEnableGlobalMethodSecurityTests.java index 4984b241eb0..bf2bf1ae6ca 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/SampleEnableGlobalMethodSecurityTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/SampleEnableGlobalMethodSecurityTests.java @@ -35,7 +35,7 @@ import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Demonstrate the samples @@ -62,15 +62,16 @@ public void preAuthorize() { this.spring.register(SampleWebSecurityConfig.class).autowire(); assertThat(this.methodSecurityService.secured()).isNull(); assertThat(this.methodSecurityService.jsr250()).isNull(); - assertThatThrownBy(() -> this.methodSecurityService.preAuthorize()).isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> this.methodSecurityService.preAuthorize()); } @Test public void customPermissionHandler() { this.spring.register(CustomPermissionEvaluatorWebSecurityConfig.class).autowire(); assertThat(this.methodSecurityService.hasPermission("allowed")).isNull(); - assertThatThrownBy(() -> this.methodSecurityService.hasPermission("denied")) - .isInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> this.methodSecurityService.hasPermission("denied")); } @EnableGlobalMethodSecurity(prePostEnabled = true) diff --git a/config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java b/config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java index bbca9375c73..bd94e55f45f 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java @@ -44,7 +44,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import static org.assertj.core.api.Assertions.assertThatCode; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -76,8 +75,8 @@ public void requestWhenNullifyingRolePrefixThenPassivityRestored() throws Except @Test public void methodSecurityWhenNullifyingRolePrefixThenPassivityRestored() { this.spring.register(SecurityConfig.class).autowire(); - assertThatCode(() -> this.service.doJsr250()).doesNotThrowAnyException(); - assertThatCode(() -> this.service.doPreAuthorize()).doesNotThrowAnyException(); + this.service.doJsr250(); + this.service.doPreAuthorize(); } @EnableWebSecurity diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java index 68b3b22b1e2..1c2ad19eb27 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java @@ -56,7 +56,6 @@ import org.springframework.web.filter.OncePerRequestFilter; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -142,7 +141,7 @@ public void loadConfigWhenDefaultContentNegotiationStrategyThenHeaderContentNego public void loadConfigWhenUserDetailsServiceHasCircularReferenceThenStillLoads() { this.spring.register(RequiresUserDetailsServiceConfig.class, UserDetailsServiceConfig.class).autowire(); MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class); - assertThatCode(() -> myFilter.userDetailsService.loadUserByUsername("user")).doesNotThrowAnyException(); + myFilter.userDetailsService.loadUserByUsername("user"); assertThatExceptionOfType(UsernameNotFoundException.class) .isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin")); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java index 815317885ab..a8fca5db6d8 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java @@ -21,6 +21,7 @@ import org.junit.Rule; import org.junit.Test; +import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; @@ -46,7 +47,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -131,32 +132,37 @@ public void requestWhenAuthorizedClientNotFoundAndClientCredentialsThenTokenResp // gh-5321 @Test public void loadContextWhenOAuth2AuthorizedClientRepositoryRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() { - assertThatThrownBy( + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( () -> this.spring.register(OAuth2AuthorizedClientRepositoryRegisteredTwiceConfig.class).autowire()) - .hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class) - .hasMessageContaining("Expected single matching bean of type '" - + OAuth2AuthorizedClientRepository.class.getName() + .withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).withMessageContaining( + "Expected single matching bean of type '" + OAuth2AuthorizedClientRepository.class.getName() + "' but found 2: authorizedClientRepository1,authorizedClientRepository2"); } @Test public void loadContextWhenClientRegistrationRepositoryNotRegisteredThenThrowNoSuchBeanDefinitionException() { - assertThatThrownBy(() -> this.spring.register(ClientRegistrationRepositoryNotRegisteredConfig.class).autowire()) - .hasRootCauseInstanceOf(NoSuchBeanDefinitionException.class).hasMessageContaining( + assertThatExceptionOfType(Exception.class) + .isThrownBy( + () -> this.spring.register(ClientRegistrationRepositoryNotRegisteredConfig.class).autowire()) + .withRootCauseInstanceOf(NoSuchBeanDefinitionException.class).withMessageContaining( "No qualifying bean of type '" + ClientRegistrationRepository.class.getName() + "' available"); } @Test public void loadContextWhenClientRegistrationRepositoryRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() { - assertThatThrownBy(() -> this.spring.register(ClientRegistrationRepositoryRegisteredTwiceConfig.class) - .autowire()).hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).hasMessageContaining( - "expected single matching bean but found 2: clientRegistrationRepository1,clientRegistrationRepository2"); + assertThatExceptionOfType(Exception.class) + .isThrownBy( + () -> this.spring.register(ClientRegistrationRepositoryRegisteredTwiceConfig.class).autowire()) + .withMessageContaining( + "expected single matching bean but found 2: clientRegistrationRepository1,clientRegistrationRepository2") + .withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class); } @Test public void loadContextWhenAccessTokenResponseClientRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() { - assertThatThrownBy(() -> this.spring.register(AccessTokenResponseClientRegisteredTwiceConfig.class).autowire()) - .hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).hasMessageContaining( + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> this.spring.register(AccessTokenResponseClientRegisteredTwiceConfig.class).autowire()) + .withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).withMessageContaining( "expected single matching bean but found 2: accessTokenResponseClient1,accessTokenResponseClient2"); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java index 5950691cc5e..ad3bcb34084 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java @@ -61,7 +61,7 @@ import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -128,11 +128,11 @@ public void loadConfigWhenSecurityFilterChainsHaveOrderThenFilterChainsOrdered() @Test public void loadConfigWhenWebSecurityConfigurersHaveSameOrderThenThrowBeanCreationException() { - Throwable thrown = catchThrowable(() -> this.spring.register(DuplicateOrderConfig.class).autowire()); - assertThat(thrown).isInstanceOf(BeanCreationException.class) - .hasMessageContaining("@Order on WebSecurityConfigurers must be unique") - .hasMessageContaining(DuplicateOrderConfig.WebConfigurer1.class.getName()) - .hasMessageContaining(DuplicateOrderConfig.WebConfigurer2.class.getName()); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(DuplicateOrderConfig.class).autowire()) + .withMessageContaining("@Order on WebSecurityConfigurers must be unique") + .withMessageContaining(DuplicateOrderConfig.WebConfigurer1.class.getName()) + .withMessageContaining(DuplicateOrderConfig.WebConfigurer2.class.getName()); } @Test @@ -155,10 +155,9 @@ public void loadConfigWhenSecurityExpressionHandlerSetThenIsRegistered() { @Test public void loadConfigWhenSecurityExpressionHandlerIsNullThenException() { - Throwable thrown = catchThrowable( - () -> this.spring.register(NullWebSecurityExpressionHandlerConfig.class).autowire()); - assertThat(thrown).isInstanceOf(BeanCreationException.class); - assertThat(thrown).hasRootCauseExactlyInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NullWebSecurityExpressionHandlerConfig.class).autowire()) + .havingRootCause().isExactlyInstanceOf(IllegalArgumentException.class); } @Test @@ -250,10 +249,10 @@ public void loadConfigWhenBeanProxyingEnabledAndSubclassThenFilterChainsCreated( @Test public void loadConfigWhenBothAdapterAndFilterChainConfiguredThenException() { - Throwable thrown = catchThrowable(() -> this.spring.register(AdapterAndFilterChainConfig.class).autowire()); - assertThat(thrown).isInstanceOf(BeanCreationException.class) - .hasRootCauseExactlyInstanceOf(IllegalStateException.class) - .hasMessageContaining("Found WebSecurityConfigurerAdapter as well as SecurityFilterChain."); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(AdapterAndFilterChainConfig.class).autowire()) + .withRootCauseExactlyInstanceOf(IllegalStateException.class) + .withMessageContaining("Found WebSecurityConfigurerAdapter as well as SecurityFilterChain."); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CorsConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CorsConfigurerTests.java index 0530f29de3c..a13bb2af4f1 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CorsConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CorsConfigurerTests.java @@ -42,7 +42,7 @@ import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.security.config.Customizer.withDefaults; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; @@ -65,8 +65,8 @@ public class CorsConfigurerTests { @Test public void configureWhenNoMvcThenException() { - assertThatThrownBy(() -> this.spring.register(DefaultCorsConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasMessageContaining( + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(DefaultCorsConfig.class).autowire()).withMessageContaining( "Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext"); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java index dbdc70f79e5..a3629ab9bd4 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java @@ -52,7 +52,7 @@ import org.springframework.web.servlet.support.RequestDataValueProcessor; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.BDDMockito.given; @@ -343,8 +343,9 @@ public void logoutWhenGetRequestAndGetEnabledForLogoutThenLogsOut() throws Excep // SEC-2749 @Test public void configureWhenRequireCsrfProtectionMatcherNullThenException() { - assertThatThrownBy(() -> this.spring.register(NullRequireCsrfProtectionMatcherConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NullRequireCsrfProtectionMatcherConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } @Test @@ -356,8 +357,9 @@ public void getWhenDefaultCsrfTokenRepositoryThenDoesNotCreateSession() throws E @Test public void getWhenNullAuthenticationStrategyThenException() { - assertThatThrownBy(() -> this.spring.register(NullAuthenticationStrategy.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NullAuthenticationStrategy.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } @Test diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurerTests.java index f1abe4e97a3..95097349e92 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurerTests.java @@ -56,7 +56,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.spy; @@ -84,9 +84,9 @@ public class ExpressionUrlAuthorizationConfigurerTests { @Test public void configureWhenHasRoleStartingWithStringRoleThenException() { - assertThatThrownBy(() -> this.spring.register(HasRoleStartingWithRoleConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class) - .hasMessageContaining( + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(HasRoleStartingWithRoleConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class).withMessageContaining( "role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_USER'"); } @@ -98,15 +98,16 @@ public void configureWhenNoCustomAccessDecisionManagerThenUsesAffirmativeBased() @Test public void configureWhenAuthorizedRequestsAndNoRequestsThenException() { - assertThatThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasMessageContaining( + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire()).withMessageContaining( "At least one mapping is required (i.e. authorizeRequests().anyRequest().authenticated())"); } @Test public void configureWhenAnyRequestIncompleteMappingThenException() { - assertThatThrownBy(() -> this.spring.register(IncompleteMappingConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasMessageContaining("An incomplete mapping was found for "); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(IncompleteMappingConfig.class).autowire()) + .withMessageContaining("An incomplete mapping was found for "); } @Test diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java index c4da0f58094..a806075a0e7 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java @@ -36,7 +36,7 @@ import org.springframework.test.web.servlet.MvcResult; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.security.config.Customizer.withDefaults; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; @@ -320,14 +320,16 @@ public void getWhenContentSecurityPolicyWithReportOnlyInLambdaThenContentSecurit @Test public void configureWhenContentSecurityPolicyEmptyThenException() { - assertThatThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } @Test public void configureWhenContentSecurityPolicyEmptyInLambdaThenException() { - assertThatThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidInLambdaConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidInLambdaConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } @Test @@ -381,8 +383,9 @@ public void getWhenFeaturePolicyConfiguredThenFeaturePolicyHeaderInResponse() th @Test public void configureWhenFeaturePolicyEmptyThenException() { - assertThatThrownBy(() -> this.spring.register(FeaturePolicyInvalidConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(FeaturePolicyInvalidConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } @Test diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.java index 45bf7085530..c960699756d 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.java @@ -36,7 +36,7 @@ import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.test.web.servlet.MockMvc; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.spy; @@ -66,26 +66,30 @@ public class LogoutConfigurerTests { @Test public void configureWhenDefaultLogoutSuccessHandlerForHasNullLogoutHandlerThenException() { - assertThatThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } @Test public void configureWhenDefaultLogoutSuccessHandlerForHasNullLogoutHandlerInLambdaThenException() { - assertThatThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerInLambdaConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerInLambdaConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } @Test public void configureWhenDefaultLogoutSuccessHandlerForHasNullMatcherThenException() { - assertThatThrownBy(() -> this.spring.register(NullMatcherConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NullMatcherConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } @Test public void configureWhenDefaultLogoutSuccessHandlerForHasNullMatcherInLambdaThenException() { - assertThatThrownBy(() -> this.spring.register(NullMatcherInLambdaConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NullMatcherInLambdaConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } @Test @@ -161,14 +165,16 @@ public void logoutWhenCustomLogoutUrlInLambdaThenRedirectsToLogin() throws Excep // SEC-3170 @Test public void configureWhenLogoutHandlerNullThenException() { - assertThatThrownBy(() -> this.spring.register(NullLogoutHandlerConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NullLogoutHandlerConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } @Test public void configureWhenLogoutHandlerNullInLambdaThenException() { - assertThatThrownBy(() -> this.spring.register(NullLogoutHandlerInLambdaConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NullLogoutHandlerInLambdaConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class); } // SEC-3170 diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.java index 3802251c4d6..61b7b91598d 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.java @@ -33,7 +33,7 @@ import org.springframework.security.web.firewall.RequestRejectedException; import org.springframework.test.web.servlet.MockMvc; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; /** @@ -54,21 +54,22 @@ public class NamespaceHttpFirewallTests { @Test public void requestWhenPathContainsDoubleDotsThenBehaviorMatchesNamespace() { this.rule.register(HttpFirewallConfig.class).autowire(); - assertThatCode(() -> this.mvc.perform(get("/public/../private/"))).isInstanceOf(RequestRejectedException.class); + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.mvc.perform(get("/public/../private/"))); } @Test public void requestWithCustomFirewallThenBehaviorMatchesNamespace() { this.rule.register(CustomHttpFirewallConfig.class).autowire(); - assertThatCode(() -> this.mvc.perform(get("/").param("deny", "true"))) - .isInstanceOf(RequestRejectedException.class); + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.mvc.perform(get("/").param("deny", "true"))); } @Test public void requestWithCustomFirewallBeanThenBehaviorMatchesNamespace() { this.rule.register(CustomHttpFirewallBeanConfig.class).autowire(); - assertThatCode(() -> this.mvc.perform(get("/").param("deny", "true"))) - .isInstanceOf(RequestRejectedException.class); + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.mvc.perform(get("/").param("deny", "true"))); } @EnableWebSecurity diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.java index ce7a15b331a..79d4d121dc9 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.java @@ -27,7 +27,7 @@ import org.springframework.security.config.test.SpringTestRule; import org.springframework.test.web.servlet.MockMvc; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -57,9 +57,9 @@ public void performWhenUsingPermitAllExactUrlRequestMatcherThenMatchesExactUrl() @Test public void configureWhenNotAuthorizeRequestsThenException() { - assertThatCode(() -> this.spring.register(NoAuthorizedUrlsConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class) - .hasMessageContaining("permitAll only works with HttpSecurity.authorizeRequests"); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(NoAuthorizedUrlsConfig.class).autowire()) + .withMessageContaining("permitAll only works with HttpSecurity.authorizeRequests"); } @EnableWebSecurity diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java index 54bc6ee5826..b64e772290c 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java @@ -47,7 +47,8 @@ import org.springframework.test.web.servlet.MvcResult; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -81,8 +82,10 @@ public class RememberMeConfigurerTests { @Test public void postWhenNoUserDetailsServiceThenException() { this.spring.register(NullUserDetailsConfig.class).autowire(); - assertThatThrownBy(() -> this.mvc.perform(post("/login").param("username", "user").param("password", "password") - .param("remember-me", "true").with(csrf()))).hasMessageContaining("UserDetailsService is required"); + assertThatIllegalStateException() + .isThrownBy(() -> this.mvc.perform(post("/login").param("username", "user") + .param("password", "password").param("remember-me", "true").with(csrf()))) + .withMessageContaining("UserDetailsService is required"); } @Test @@ -168,9 +171,11 @@ public void loginWhenRememberMeTrueAndCookieDomainInLambdaThenRememberMeCookieHa @Test public void configureWhenRememberMeCookieNameAndRememberMeServicesThenException() { - assertThatThrownBy(() -> this.spring.register(RememberMeCookieNameAndRememberMeServicesConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Can not set rememberMeCookieName and custom rememberMeServices."); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy( + () -> this.spring.register(RememberMeCookieNameAndRememberMeServicesConfig.class).autowire()) + .withRootCauseInstanceOf(IllegalArgumentException.class) + .withMessageContaining("Can not set rememberMeCookieName and custom rememberMeServices."); } @Test diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java index 6845659dce1..09bbc43e6ce 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java @@ -29,6 +29,7 @@ import org.junit.Rule; import org.junit.Test; +import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; @@ -91,7 +92,7 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -479,9 +480,10 @@ public void oidcLoginCustomWithBeanRegistration() throws Exception { @Test public void oidcLoginCustomWithNoUniqueJwtDecoderFactory() { - assertThatThrownBy(() -> loadConfig(OAuth2LoginConfig.class, NoUniqueJwtDecoderFactoryConfig.class)) - .hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class) - .hasMessageContaining("No qualifying bean of type " + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> loadConfig(OAuth2LoginConfig.class, NoUniqueJwtDecoderFactoryConfig.class)) + .withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class) + .withMessageContaining("No qualifying bean of type " + "'org.springframework.security.oauth2.jwt.JwtDecoderFactory' " + "available: expected single matching bean but found 2: jwtDecoderFactory1,jwtDecoderFactory2"); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java index 47540c3e062..57096426683 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java @@ -133,7 +133,8 @@ import org.springframework.web.context.support.GenericWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.startsWith; import static org.mockito.ArgumentMatchers.any; @@ -565,9 +566,10 @@ public void getBearerTokenResolverWhenDuplicateResolverBeansAndAnotherOnTheDslTh @Test public void getBearerTokenResolverWhenDuplicateResolverBeansThenWiringException() { - assertThatCode(() -> this.spring.register(MultipleBearerTokenResolverBeansConfig.class, JwtDecoderConfig.class) - .autowire()).isInstanceOf(BeanCreationException.class) - .hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring + .register(MultipleBearerTokenResolverBeansConfig.class, JwtDecoderConfig.class).autowire()) + .withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class); } @Test @@ -675,7 +677,8 @@ public void getJwtDecoderWhenTwoJwtDecoderBeansThenThrowsException() { context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder); this.spring.context(context).autowire(); OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt(); - assertThatCode(() -> jwtConfigurer.getJwtDecoder()).isInstanceOf(NoUniqueBeanDefinitionException.class); + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class) + .isThrownBy(() -> jwtConfigurer.getJwtDecoder()); } @Test @@ -701,14 +704,14 @@ public void requestWhenRealmNameConfiguredThenUsesOnAccessDenied() throws Except public void authenticationEntryPointWhenGivenNullThenThrowsException() { ApplicationContext context = mock(ApplicationContext.class); OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context); - assertThatCode(() -> configurer.authenticationEntryPoint(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> configurer.authenticationEntryPoint(null)); } @Test public void accessDeniedHandlerWhenGivenNullThenThrowsException() { ApplicationContext context = mock(ApplicationContext.class); OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context); - assertThatCode(() -> configurer.accessDeniedHandler(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> configurer.accessDeniedHandler(null)); } @Test @@ -862,8 +865,8 @@ public void getWhenCustomIntrospectionAuthenticationManagerInLambdaThenUsed() th @Test public void configureWhenOnlyIntrospectionUrlThenException() { - assertThatCode(() -> this.spring.register(OpaqueTokenHalfConfiguredConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(OpaqueTokenHalfConfiguredConfig.class).autowire()); } @Test @@ -991,27 +994,30 @@ public void getWhenMultipleIssuersThenUsesIssuerClaimToDifferentiate() throws Ex @Test public void configuredWhenMissingJwtAuthenticationProviderThenWiringException() { - assertThatCode(() -> this.spring.register(JwtlessConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasMessageContaining("neither was found"); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(JwtlessConfig.class).autowire()) + .withMessageContaining("neither was found"); } @Test public void configureWhenMissingJwkSetUriThenWiringException() { - assertThatCode(() -> this.spring.register(JwtHalfConfiguredConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasMessageContaining("No qualifying bean of type"); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(JwtHalfConfiguredConfig.class).autowire()) + .withMessageContaining("No qualifying bean of type"); } @Test public void configureWhenUsingBothJwtAndOpaqueThenWiringException() { - assertThatCode(() -> this.spring.register(OpaqueAndJwtConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Spring Security only supports JWTs or Opaque Tokens"); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(OpaqueAndJwtConfig.class).autowire()) + .withMessageContaining("Spring Security only supports JWTs or Opaque Tokens"); } @Test public void configureWhenUsingBothAuthenticationManagerResolverAndOpaqueThenWiringException() { - assertThatCode(() -> this.spring.register(AuthenticationManagerResolverPlusOtherConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasMessageContaining("authenticationManagerResolver"); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(AuthenticationManagerResolverPlusOtherConfig.class).autowire()) + .withMessageContaining("authenticationManagerResolver"); } @Test @@ -1064,8 +1070,8 @@ public void getJwtAuthenticationConverterWhenDuplicateConverterBeansThenThrowsEx context.registerBean("converterTwo", JwtAuthenticationConverter.class, () -> converterBean); this.spring.context(context).autowire(); OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt(); - assertThatCode(jwtConfigurer::getJwtAuthenticationConverter) - .isInstanceOf(NoUniqueBeanDefinitionException.class); + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class) + .isThrownBy(jwtConfigurer::getJwtAuthenticationConverter); } private static void registerMockBean(GenericApplicationContext context, String name, Class clazz) { diff --git a/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java b/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java index 223f082498e..f3e77d44645 100644 --- a/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java +++ b/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java @@ -29,7 +29,8 @@ import org.springframework.security.util.InMemoryResource; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * @author Rob Winch @@ -45,15 +46,15 @@ public class UserDetailsResourceFactoryBeanTests { @Test public void setResourceLoaderWhenNullThenThrowsException() { - assertThatThrownBy(() -> this.factory.setResourceLoader(null)).isInstanceOf(IllegalArgumentException.class) - .hasStackTraceContaining("resourceLoader cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.factory.setResourceLoader(null)) + .withStackTraceContaining("resourceLoader cannot be null"); } @Test public void getObjectWhenPropertiesResourceLocationNullThenThrowsIllegalStateException() { this.factory.setResourceLoader(this.resourceLoader); - assertThatThrownBy(() -> this.factory.getObject()).isInstanceOf(IllegalArgumentException.class) - .hasStackTraceContaining("resource cannot be null if resourceLocation is null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.factory.getObject()) + .withStackTraceContaining("resource cannot be null if resourceLocation is null"); } @Test @@ -72,8 +73,8 @@ public void getObjectWhenPropertiesResourceSingleUserThenThrowsGetsSingleUser() @Test public void getObjectWhenInvalidUserThenThrowsMeaningfulException() { this.factory.setResource(new InMemoryResource("user=invalidFormatHere")); - assertThatThrownBy(() -> this.factory.getObject()).isInstanceOf(IllegalStateException.class) - .hasStackTraceContaining("user").hasStackTraceContaining("invalidFormatHere"); + assertThatIllegalStateException().isThrownBy(() -> this.factory.getObject()).withStackTraceContaining("user") + .withStackTraceContaining("invalidFormatHere"); } @Test diff --git a/config/src/test/java/org/springframework/security/config/crypto/RsaKeyConversionServicePostProcessorTests.java b/config/src/test/java/org/springframework/security/config/crypto/RsaKeyConversionServicePostProcessorTests.java index dfa8399e665..07f30bde9bc 100644 --- a/config/src/test/java/org/springframework/security/config/crypto/RsaKeyConversionServicePostProcessorTests.java +++ b/config/src/test/java/org/springframework/security/config/crypto/RsaKeyConversionServicePostProcessorTests.java @@ -38,7 +38,7 @@ import org.springframework.security.config.test.SpringTestRule; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link RsaKeyConversionServicePostProcessor} @@ -131,9 +131,9 @@ public void valueWhenReferringToCustomResourceLoadedPublicKeyThenConverts() { @Test public void valueWhenOverridingConversionServiceThenUsed() { - assertThatCode( + assertThatExceptionOfType(Exception.class).isThrownBy( () -> this.spring.register(OverrideConversionServiceConfig.class, DefaultConfig.class).autowire()) - .hasRootCauseInstanceOf(IllegalArgumentException.class); + .withRootCauseInstanceOf(IllegalArgumentException.class); } @EnableWebSecurity diff --git a/config/src/test/java/org/springframework/security/config/http/AccessDeniedConfigTests.java b/config/src/test/java/org/springframework/security/config/http/AccessDeniedConfigTests.java index 3535309aa8a..1344c1b3a5f 100644 --- a/config/src/test/java/org/springframework/security/config/http/AccessDeniedConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/AccessDeniedConfigTests.java @@ -36,7 +36,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -59,8 +59,8 @@ public class AccessDeniedConfigTests { @Test public void configureWhenAccessDeniedHandlerIsMissingLeadingSlashThenException() { SpringTestContext context = this.spring.configLocations(this.xml("NoLeadingSlash")); - assertThatThrownBy(() -> context.autowire()).isInstanceOf(BeanCreationException.class) - .hasMessageContaining("errorPage must begin with '/'"); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> context.autowire()) + .withMessageContaining("errorPage must begin with '/'"); } @Test @@ -73,8 +73,8 @@ public void configureWhenAccessDeniedHandlerRefThenAutowire() throws Exception { @Test public void configureWhenAccessDeniedHandlerUsesPathAndRefThenException() { SpringTestContext context = this.spring.configLocations(this.xml("UsesPathAndRef")); - assertThatThrownBy(() -> context.autowire()).isInstanceOf(BeanDefinitionParsingException.class) - .hasMessageContaining("attribute error-page cannot be used together with the 'ref' attribute"); + assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() -> context.autowire()) + .withMessageContaining("attribute error-page cannot be used together with the 'ref' attribute"); } private String xml(String configName) { diff --git a/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java b/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java index faa60c2bc51..dec1dc15152 100644 --- a/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java @@ -42,7 +42,7 @@ import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -89,14 +89,14 @@ public void authenticateWhenConfiguredWithSpelThenRedirectsAccordingly() throws @Test public void autowireWhenLoginPageIsMisconfiguredThenDetects() { - assertThatThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashLoginPage")).autowire()) - .isInstanceOf(BeanCreationException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashLoginPage")).autowire()); } @Test public void autowireWhenDefaultTargetUrlIsMisconfiguredThenDetects() { - assertThatThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashDefaultTargetUrl")).autowire()) - .isInstanceOf(BeanCreationException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashDefaultTargetUrl")).autowire()); } @Test diff --git a/config/src/test/java/org/springframework/security/config/http/HttpCorsConfigTests.java b/config/src/test/java/org/springframework/security/config/http/HttpCorsConfigTests.java index 6f3b20db831..6dcbab2f182 100644 --- a/config/src/test/java/org/springframework/security/config/http/HttpCorsConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/HttpCorsConfigTests.java @@ -36,7 +36,7 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.request.MockMvcRequestBuilders.options; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; @@ -59,8 +59,9 @@ public class HttpCorsConfigTests { @Test public void autowireWhenMissingMvcThenGivesInformativeError() { - assertThatThrownBy(() -> this.spring.configLocations(this.xml("RequiresMvc")).autowire()) - .isInstanceOf(BeanCreationException.class).hasMessageContaining( + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("RequiresMvc")).autowire()) + .withMessageContaining( "Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext"); } diff --git a/config/src/test/java/org/springframework/security/config/http/HttpHeadersConfigTests.java b/config/src/test/java/org/springframework/security/config/http/HttpHeadersConfigTests.java index da112ae7317..a8ea0264887 100644 --- a/config/src/test/java/org/springframework/security/config/http/HttpHeadersConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/HttpHeadersConfigTests.java @@ -37,7 +37,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -92,9 +92,9 @@ public void requestWhenHeadersDisabledRefMissingPlaceholderThenResponseIncludesA @Test public void configureWhenHeadersDisabledHavingChildElementThenAutowireFails() { - assertThatThrownBy(() -> this.spring.configLocations(this.xml("HeadersDisabledHavingChildElement")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class) - .hasMessageContaining("Cannot specify with child elements"); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("HeadersDisabledHavingChildElement")).autowire()) + .withMessageContaining("Cannot specify with child elements"); } @Test @@ -185,24 +185,20 @@ public void requestWhenUsingFrameOptionsSameOriginThenRespondsWithSameOrigin() t @Test public void configureWhenUsingFrameOptionsAllowFromNoOriginThenAutowireFails() { - assertThatThrownBy(() -> this.spring - .configLocations(this.xml("DefaultsDisabledWithFrameOptionsAllowFromNoOrigin")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class) - .hasMessageContaining("Strategy requires a 'value' to be set."); // FIXME - // better - // error - // message? + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring + .configLocations(this.xml("DefaultsDisabledWithFrameOptionsAllowFromNoOrigin")).autowire()) + .withMessageContaining("Strategy requires a 'value' to be set."); + // FIXME better error message? } @Test public void configureWhenUsingFrameOptionsAllowFromBlankOriginThenAutowireFails() { - assertThatThrownBy(() -> this.spring - .configLocations(this.xml("DefaultsDisabledWithFrameOptionsAllowFromBlankOrigin")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class) - .hasMessageContaining("Strategy requires a 'value' to be set."); // FIXME - // better - // error - // message? + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring + .configLocations(this.xml("DefaultsDisabledWithFrameOptionsAllowFromBlankOrigin")).autowire()) + .withMessageContaining("Strategy requires a 'value' to be set."); + // FIXME better error message? } @Test @@ -243,15 +239,14 @@ public void requestWhenUsingCustomHeaderWriterThenRespondsWithThatHeader() throw @Test public void configureWhenUsingCustomHeaderNameOnlyThenAutowireFails() { - assertThatThrownBy(() -> this.spring.configLocations(this.xml("DefaultsDisabledWithOnlyHeaderName")).autowire()) - .isInstanceOf(BeanCreationException.class); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + () -> this.spring.configLocations(this.xml("DefaultsDisabledWithOnlyHeaderName")).autowire()); } @Test public void configureWhenUsingCustomHeaderValueOnlyThenAutowireFails() { - assertThatThrownBy( - () -> this.spring.configLocations(this.xml("DefaultsDisabledWithOnlyHeaderValue")).autowire()) - .isInstanceOf(BeanCreationException.class); + assertThatExceptionOfType(BeanCreationException.class).isThrownBy( + () -> this.spring.configLocations(this.xml("DefaultsDisabledWithOnlyHeaderValue")).autowire()); } @Test @@ -283,10 +278,10 @@ public void requestWhenDisablingXssProtectionThenDefaultsToZero() throws Excepti @Test public void configureWhenXssProtectionDisabledAndBlockSetThenAutowireFails() { - assertThatThrownBy(() -> this.spring - .configLocations(this.xml("DefaultsDisabledWithXssProtectionDisabledAndBlockSet")).autowire()) - .isInstanceOf(BeanCreationException.class) - .hasMessageContaining("Cannot set block to true with enabled false"); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring + .configLocations(this.xml("DefaultsDisabledWithXssProtectionDisabledAndBlockSet")).autowire()) + .withMessageContaining("Cannot set block to true with enabled false"); } @Test @@ -326,16 +321,16 @@ public void insecureRequestWhenUsingCustomHstsRequestMatcherThenIncludesHstsHead @Test public void configureWhenUsingHpkpWithoutPinsThenAutowireFails() { - assertThatThrownBy(() -> this.spring.configLocations(this.xml("DefaultsDisabledWithEmptyHpkp")).autowire()) - .isInstanceOf(XmlBeanDefinitionStoreException.class) - .hasMessageContaining("The content of element 'hpkp' is not complete"); + assertThatExceptionOfType(XmlBeanDefinitionStoreException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("DefaultsDisabledWithEmptyHpkp")).autowire()) + .withMessageContaining("The content of element 'hpkp' is not complete"); } @Test public void configureWhenUsingHpkpWithEmptyPinsThenAutowireFails() { - assertThatThrownBy(() -> this.spring.configLocations(this.xml("DefaultsDisabledWithEmptyPins")).autowire()) - .isInstanceOf(XmlBeanDefinitionStoreException.class) - .hasMessageContaining("The content of element 'pins' is not complete"); + assertThatExceptionOfType(XmlBeanDefinitionStoreException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("DefaultsDisabledWithEmptyPins")).autowire()) + .withMessageContaining("The content of element 'pins' is not complete"); } @Test @@ -452,42 +447,47 @@ public void requestWhenXssProtectionDisabledThenExcludesHeader() throws Exceptio @Test public void configureWhenHstsDisabledAndIncludeSubdomainsSpecifiedThenAutowireFails() { - assertThatThrownBy( + assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy( () -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingIncludeSubdomains")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("include-subdomains"); + .withMessageContaining("include-subdomains"); } @Test public void configureWhenHstsDisabledAndMaxAgeSpecifiedThenAutowireFails() { - assertThatThrownBy(() -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingMaxAge")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("max-age"); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingMaxAge")).autowire()) + .withMessageContaining("max-age"); } @Test public void configureWhenHstsDisabledAndRequestMatcherSpecifiedThenAutowireFails() { - assertThatThrownBy( - () -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingRequestMatcher")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("request-matcher-ref"); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy( + () -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingRequestMatcher")).autowire()) + .withMessageContaining("request-matcher-ref"); } @Test public void configureWhenXssProtectionDisabledAndEnabledThenAutowireFails() { - assertThatThrownBy(() -> this.spring.configLocations(this.xml("XssProtectionDisabledAndEnabled")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("enabled"); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("XssProtectionDisabledAndEnabled")).autowire()) + .withMessageContaining("enabled"); } @Test public void configureWhenXssProtectionDisabledAndBlockSpecifiedThenAutowireFails() { - assertThatThrownBy( - () -> this.spring.configLocations(this.xml("XssProtectionDisabledSpecifyingBlock")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("block"); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy( + () -> this.spring.configLocations(this.xml("XssProtectionDisabledSpecifyingBlock")).autowire()) + .withMessageContaining("block"); } @Test public void configureWhenFrameOptionsDisabledAndPolicySpecifiedThenAutowireFails() { - assertThatThrownBy( - () -> this.spring.configLocations(this.xml("FrameOptionsDisabledSpecifyingPolicy")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("policy"); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy( + () -> this.spring.configLocations(this.xml("FrameOptionsDisabledSpecifyingPolicy")).autowire()) + .withMessageContaining("policy"); } @Test @@ -514,9 +514,8 @@ public void requestWhenDefaultsDisabledAndContentSecurityPolicyConfiguredThenInc @Test public void configureWhenContentSecurityPolicyConfiguredWithEmptyDirectivesThenAutowireFails() { - assertThatThrownBy( - () -> this.spring.configLocations(this.xml("ContentSecurityPolicyWithEmptyDirectives")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy( + () -> this.spring.configLocations(this.xml("ContentSecurityPolicyWithEmptyDirectives")).autowire()); } @Test diff --git a/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java b/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java index 1b7d40c3392..4985cd0cc6a 100644 --- a/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java @@ -35,7 +35,7 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.ConfigurableWebApplicationContext; -import static org.assertj.core.api.Assertions.assertThatCode; +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.spy; @@ -151,26 +151,26 @@ public void requestWhenUsingMvcMatchersAndServletPathThenAuthorizesRequestsAccor @Test public void configureWhenUsingAntMatcherAndServletPathThenThrowsException() { - assertThatCode(() -> this.spring.configLocations(this.xml("AntMatcherServletPath")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("AntMatcherServletPath")).autowire()); } @Test public void configureWhenUsingRegexMatcherAndServletPathThenThrowsException() { - assertThatCode(() -> this.spring.configLocations(this.xml("RegexMatcherServletPath")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("RegexMatcherServletPath")).autowire()); } @Test public void configureWhenUsingCiRegexMatcherAndServletPathThenThrowsException() { - assertThatCode(() -> this.spring.configLocations(this.xml("CiRegexMatcherServletPath")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("CiRegexMatcherServletPath")).autowire()); } @Test public void configureWhenUsingDefaultMatcherAndServletPathThenThrowsException() { - assertThatCode(() -> this.spring.configLocations(this.xml("DefaultMatcherServletPath")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("DefaultMatcherServletPath")).autowire()); } private MockServletContext mockServletContext(String servletPath) { diff --git a/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java b/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java index 1438a39056e..de7537b92f8 100644 --- a/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java @@ -111,7 +111,7 @@ import org.springframework.web.context.support.XmlWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willAnswer; @@ -296,8 +296,8 @@ public void configureWhenCustomFiltersThenAddedToChainInCorrectOrder() { @Test public void configureWhenTwoFiltersWithSameOrderThenException() { - assertThatCode(() -> this.spring.configLocations(xml("CollidingFilters")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("CollidingFilters")).autowire()); } @Test @@ -319,8 +319,8 @@ public void getWhenUsingX509AndPropertyPlaceholderThenSubjectPrincipalRegexIsCon @Test public void configureWhenUsingInvalidLogoutSuccessUrlThenThrowsException() { - assertThatCode(() -> this.spring.configLocations(xml("InvalidLogoutSuccessUrl")).autowire()) - .isInstanceOf(BeanCreationException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.configLocations(xml("InvalidLogoutSuccessUrl")).autowire()); } @Test @@ -432,9 +432,8 @@ public void configureWhenUsingDisableUrlRewritingThenRedirectIsNotEncodedByRespo @Test public void configureWhenUserDetailsServiceInParentContextThenLocatesSuccessfully() { - assertThatCode( - () -> this.spring.configLocations(MiscHttpConfigTests.xml("MissingUserDetailsService")).autowire()) - .isInstanceOf(BeansException.class); + assertThatExceptionOfType(BeansException.class).isThrownBy( + () -> this.spring.configLocations(MiscHttpConfigTests.xml("MissingUserDetailsService")).autowire()); try (XmlWebApplicationContext parent = new XmlWebApplicationContext()) { parent.setConfigLocations(MiscHttpConfigTests.xml("AutoConfig")); parent.refresh(); diff --git a/config/src/test/java/org/springframework/security/config/http/MultiHttpBlockConfigTests.java b/config/src/test/java/org/springframework/security/config/http/MultiHttpBlockConfigTests.java index 4c19f1d5d22..07ddc0303c9 100644 --- a/config/src/test/java/org/springframework/security/config/http/MultiHttpBlockConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/MultiHttpBlockConfigTests.java @@ -27,7 +27,7 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.web.bind.annotation.GetMapping; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -61,14 +61,16 @@ public void requestWhenUsingMutuallyExclusiveHttpElementsThenIsRoutedAccordingly @Test public void configureWhenUsingDuplicateHttpElementsThenThrowsWiringException() { - assertThatCode(() -> this.spring.configLocations(this.xml("IdenticalHttpElements")).autowire()) - .isInstanceOf(BeanCreationException.class).hasCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("IdenticalHttpElements")).autowire()) + .withCauseInstanceOf(IllegalArgumentException.class); } @Test public void configureWhenUsingIndenticallyPatternedHttpElementsThenThrowsWiringException() { - assertThatCode(() -> this.spring.configLocations(this.xml("IdenticallyPatternedHttpElements")).autowire()) - .isInstanceOf(BeanCreationException.class).hasCauseInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("IdenticallyPatternedHttpElements")).autowire()) + .withCauseInstanceOf(IllegalArgumentException.class); } /** diff --git a/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java index 9ba660ea3a0..84a77ed2043 100644 --- a/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java @@ -96,8 +96,7 @@ import org.springframework.web.client.RestOperations; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.startsWith; import static org.mockito.ArgumentMatchers.any; @@ -436,8 +435,8 @@ public void requestWhenCustomJwtDecoderThenUsed() throws Exception { @Test public void configureWhenDecoderAndJwkSetUriThenException() { - assertThatThrownBy(() -> this.spring.configLocations(xml("JwtDecoderAndJwkSetUri")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("JwtDecoderAndJwkSetUri")).autowire()); } @Test @@ -554,14 +553,14 @@ public void getWhenIntrospectionLacksScopeThenForbidden() throws Exception { @Test public void configureWhenOnlyIntrospectionUrlThenException() { - assertThatCode(() -> this.spring.configLocations(xml("OpaqueTokenHalfConfigured")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("OpaqueTokenHalfConfigured")).autowire()); } @Test public void configureWhenIntrospectorAndIntrospectionUriThenError() { - assertThatCode(() -> this.spring.configLocations(xml("OpaqueTokenAndIntrospectionUri")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("OpaqueTokenAndIntrospectionUri")).autowire()); } @Test @@ -642,22 +641,23 @@ public void getWhenAlsoUsingHttpBasicThenCorrectProviderEngages() throws Excepti @Test public void configuredWhenMissingJwtAuthenticationProviderThenWiringException() { - assertThatCode(() -> this.spring.configLocations(xml("Jwtless")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("Please select one"); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("Jwtless")).autowire()) + .withMessageContaining("Please select one"); } @Test public void configureWhenMissingJwkSetUriThenWiringException() { - assertThatCode(() -> this.spring.configLocations(xml("JwtHalfConfigured")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("Please specify either"); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("JwtHalfConfigured")).autowire()) + .withMessageContaining("Please specify either"); } @Test public void configureWhenUsingBothAuthenticationManagerResolverAndJwtThenException() { - assertThatCode( + assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy( () -> this.spring.configLocations(xml("AuthenticationManagerResolverPlusOtherConfig")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class) - .hasMessageContaining("authentication-manager-resolver-ref"); + .withMessageContaining("authentication-manager-resolver-ref"); } @Test diff --git a/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java b/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java index 7017e60822b..904b3e6a285 100644 --- a/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java @@ -44,7 +44,7 @@ import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -92,8 +92,8 @@ public void requestWhenOpenIDAndFormLoginWithOpenIDLoginPageConfiguredThenOpenID @Test public void configureWhenOpenIDAndFormLoginBothConfigureLoginPagesThenWiringException() { - assertThatCode(() -> this.spring.configLocations(this.xml("WithFormLoginAndOpenIDLoginPages")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(this.xml("WithFormLoginAndOpenIDLoginPages")).autowire()); } @Test diff --git a/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java b/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java index 46fc53c5705..d0067d06c94 100644 --- a/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java @@ -41,7 +41,7 @@ import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; @@ -155,8 +155,8 @@ public void requestWithRememberMeWhenTokenValidityIsNegativeThenCookieReflectsCo @Test public void configureWhenUsingDataSourceAndANegativeTokenValidityThenThrowsWiringException() { - assertThatCode(() -> this.spring.configLocations(this.xml("NegativeTokenValidityWithDataSource")).autowire()) - .isInstanceOf(FatalBeanException.class); + assertThatExceptionOfType(FatalBeanException.class).isThrownBy( + () -> this.spring.configLocations(this.xml("NegativeTokenValidityWithDataSource")).autowire()); } @Test @@ -186,9 +186,8 @@ public void requestWithRememberMeWhenUseSecureCookieIsFalseThenCookieIsNotSecure @Test public void configureWhenUsingPersistentTokenRepositoryAndANegativeTokenValidityThenThrowsWiringException() { - assertThatCode( - () -> this.spring.configLocations(this.xml("NegativeTokenValidityWithPersistentRepository")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() -> this.spring + .configLocations(this.xml("NegativeTokenValidityWithPersistentRepository")).autowire()); } @Test @@ -231,8 +230,8 @@ public void requestWithRememberMeWhenUsingCustomRememberMeParameterThenReauthent @Test public void configureWhenUsingRememberMeParameterAndServicesRefThenThrowsWiringException() { - assertThatCode(() -> this.spring.configLocations(this.xml("WithRememberMeParameterAndServicesRef")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy( + () -> this.spring.configLocations(this.xml("WithRememberMeParameterAndServicesRef")).autowire()); } /** @@ -249,11 +248,13 @@ public void authenticateWhenUsingCustomRememberMeCookieNameThenIssuesCookieWithT */ @Test public void configureWhenUsingRememberMeCookieAndServicesRefThenThrowsWiringException() { - assertThatCode(() -> this.spring.configLocations(this.xml("WithRememberMeCookieAndServicesRef")).autowire()) - .isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining( + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy( + () -> this.spring.configLocations(this.xml("WithRememberMeCookieAndServicesRef")).autowire()) + .withMessageContaining( "Configuration problem: services-ref can't be used in combination with attributes " - + "token-repository-ref,data-source-ref, user-service-ref, token-validity-seconds, use-secure-cookie, " - + "remember-me-parameter or remember-me-cookie"); + + "token-repository-ref,data-source-ref, user-service-ref, token-validity-seconds, " + + "use-secure-cookie, remember-me-parameter or remember-me-cookie"); } private ResultActions rememberAuthentication(String username, String password) throws Exception { diff --git a/config/src/test/java/org/springframework/security/config/web/server/FormLoginTests.java b/config/src/test/java/org/springframework/security/config/web/server/FormLoginTests.java index cf96b628a1e..b53176c4aea 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/FormLoginTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/FormLoginTests.java @@ -47,8 +47,7 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.atLeastOnce; @@ -294,7 +293,7 @@ public DefaultLoginPage assertLogout() { } public DefaultLoginPage assertLoginFormNotPresent() { - assertThatThrownBy(() -> loginForm().username("")).isInstanceOf(NoSuchElementException.class); + assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(() -> loginForm().username("")); return this; } @@ -353,7 +352,7 @@ public WebElement findClientRegistrationByName(String clientName) { } public OAuth2Login assertClientRegistrationByName(String clientName) { - assertThatCode(() -> findClientRegistrationByName(clientName)).doesNotThrowAnyException(); + findClientRegistrationByName(clientName); return this; } diff --git a/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java b/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java index 301644ccd15..a6918809a99 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java @@ -80,7 +80,7 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.CoreMatchers.startsWith; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -334,7 +334,7 @@ public void getJwtDecoderWhenTwoBeansWiredThenThrowsWiringException() { context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder); context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder); ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt(); - assertThatCode(() -> jwt.getJwtDecoder()).isInstanceOf(NoUniqueBeanDefinitionException.class); + assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder()); } @Test @@ -343,7 +343,7 @@ public void getJwtDecoderWhenNoBeansAndNoDslWiredThenWiringException() { ServerHttpSecurity http = new ServerHttpSecurity(); http.setApplicationContext(context); ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt(); - assertThatCode(() -> jwt.getJwtDecoder()).isInstanceOf(NoSuchBeanDefinitionException.class); + assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder()); } @Test @@ -366,8 +366,9 @@ public void introspectWhenValidAndIntrospectionInLambdaThenReturnsOk() { @Test public void configureWhenUsingBothAuthenticationManagerResolverAndOpaqueThenWiringException() { - assertThatCode(() -> this.spring.register(AuthenticationManagerResolverPlusOtherConfig.class).autowire()) - .isInstanceOf(BeanCreationException.class).hasMessageContaining("authenticationManagerResolver"); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(AuthenticationManagerResolverPlusOtherConfig.class).autowire()) + .withMessageContaining("authenticationManagerResolver"); } private static Dispatcher requiresAuth(String username, String password, String response) { diff --git a/config/src/test/java/org/springframework/security/config/websocket/WebSocketMessageBrokerConfigTests.java b/config/src/test/java/org/springframework/security/config/websocket/WebSocketMessageBrokerConfigTests.java index 8d760858d5c..3e72669f577 100644 --- a/config/src/test/java/org/springframework/security/config/websocket/WebSocketMessageBrokerConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/websocket/WebSocketMessageBrokerConfigTests.java @@ -20,7 +20,6 @@ import java.util.Map; import org.assertj.core.api.ThrowableAssert; -import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -68,8 +67,7 @@ import org.springframework.web.socket.server.HandshakeHandler; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; /** @@ -103,8 +101,8 @@ public class WebSocketMessageBrokerConfigTests { public void sendWhenNoIdSpecifiedThenIntegratesWithClientInboundChannel() { this.spring.configLocations(xml("NoIdConfig")).autowire(); this.clientInboundChannel.send(message("/permitAll")); - assertThatThrownBy(() -> this.clientInboundChannel.send(message("/denyAll"))) - .hasCauseInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> this.clientInboundChannel.send(message("/denyAll"))) + .withCauseInstanceOf(AccessDeniedException.class); } @Test @@ -112,141 +110,146 @@ public void sendWhenAnonymousMessageWithConnectMessageTypeThenPermitted() { this.spring.configLocations(xml("NoIdConfig")).autowire(); SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT); headers.setNativeHeader(this.token.getHeaderName(), this.token.getToken()); - assertThatCode(() -> this.clientInboundChannel.send(message("/permitAll", headers))).doesNotThrowAnyException(); + this.clientInboundChannel.send(message("/permitAll", headers)); } @Test public void sendWhenAnonymousMessageWithConnectAckMessageTypeThenPermitted() { this.spring.configLocations(xml("NoIdConfig")).autowire(); Message message = message("/permitAll", SimpMessageType.CONNECT_ACK); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test public void sendWhenAnonymousMessageWithDisconnectMessageTypeThenPermitted() { this.spring.configLocations(xml("NoIdConfig")).autowire(); Message message = message("/permitAll", SimpMessageType.DISCONNECT); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test public void sendWhenAnonymousMessageWithDisconnectAckMessageTypeThenPermitted() { this.spring.configLocations(xml("NoIdConfig")).autowire(); Message message = message("/permitAll", SimpMessageType.DISCONNECT_ACK); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test public void sendWhenAnonymousMessageWithHeartbeatMessageTypeThenPermitted() { this.spring.configLocations(xml("NoIdConfig")).autowire(); Message message = message("/permitAll", SimpMessageType.HEARTBEAT); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test public void sendWhenAnonymousMessageWithMessageMessageTypeThenPermitted() { this.spring.configLocations(xml("NoIdConfig")).autowire(); Message message = message("/permitAll", SimpMessageType.MESSAGE); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test public void sendWhenAnonymousMessageWithOtherMessageTypeThenPermitted() { this.spring.configLocations(xml("NoIdConfig")).autowire(); Message message = message("/permitAll", SimpMessageType.OTHER); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test public void sendWhenAnonymousMessageWithSubscribeMessageTypeThenPermitted() { this.spring.configLocations(xml("NoIdConfig")).autowire(); Message message = message("/permitAll", SimpMessageType.SUBSCRIBE); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test public void sendWhenAnonymousMessageWithUnsubscribeMessageTypeThenPermitted() { this.spring.configLocations(xml("NoIdConfig")).autowire(); Message message = message("/permitAll", SimpMessageType.UNSUBSCRIBE); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test public void sendWhenConnectWithoutCsrfTokenThenDenied() { this.spring.configLocations(xml("SyncConfig")).autowire(); Message message = message("/message", SimpMessageType.CONNECT); - assertThatThrownBy(send(message)).hasCauseInstanceOf(InvalidCsrfTokenException.class); + assertThatExceptionOfType(Exception.class).isThrownBy(send(message)) + .withCauseInstanceOf(InvalidCsrfTokenException.class); } @Test public void sendWhenConnectWithSameOriginDisabledThenCsrfTokenNotRequired() { this.spring.configLocations(xml("SyncSameOriginDisabledConfig")).autowire(); Message message = message("/message", SimpMessageType.CONNECT); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test public void sendWhenInterceptWiredForMessageTypeThenDeniesOnTypeMismatch() { this.spring.configLocations(xml("MessageInterceptTypeConfig")).autowire(); Message message = message("/permitAll", SimpMessageType.MESSAGE); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); message = message("/permitAll", SimpMessageType.UNSUBSCRIBE); - assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(Exception.class).isThrownBy(send(message)) + .withCauseInstanceOf(AccessDeniedException.class); message = message("/anyOther", SimpMessageType.MESSAGE); - assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(Exception.class).isThrownBy(send(message)) + .withCauseInstanceOf(AccessDeniedException.class); } @Test public void sendWhenInterceptWiredForSubscribeTypeThenDeniesOnTypeMismatch() { this.spring.configLocations(xml("SubscribeInterceptTypeConfig")).autowire(); Message message = message("/permitAll", SimpMessageType.SUBSCRIBE); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); message = message("/permitAll", SimpMessageType.UNSUBSCRIBE); - assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(Exception.class).isThrownBy(send(message)) + .withCauseInstanceOf(AccessDeniedException.class); message = message("/anyOther", SimpMessageType.SUBSCRIBE); - assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(Exception.class).isThrownBy(send(message)) + .withCauseInstanceOf(AccessDeniedException.class); } @Test public void configureWhenUsingConnectMessageTypeThenAutowireFails() { - ThrowingCallable bad = () -> this.spring.configLocations(xml("ConnectInterceptTypeConfig")).autowire(); - assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("ConnectInterceptTypeConfig")).autowire()); } @Test public void configureWhenUsingConnectAckMessageTypeThenAutowireFails() { - ThrowingCallable bad = () -> this.spring.configLocations(xml("ConnectAckInterceptTypeConfig")).autowire(); - assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("ConnectAckInterceptTypeConfig")).autowire()); } @Test public void configureWhenUsingDisconnectMessageTypeThenAutowireFails() { - ThrowingCallable bad = () -> this.spring.configLocations(xml("DisconnectInterceptTypeConfig")).autowire(); - assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("DisconnectInterceptTypeConfig")).autowire()); } @Test public void configureWhenUsingDisconnectAckMessageTypeThenAutowireFails() { - ThrowingCallable bad = () -> this.spring.configLocations(xml("DisconnectAckInterceptTypeConfig")).autowire(); - assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("DisconnectAckInterceptTypeConfig")).autowire()); } @Test public void configureWhenUsingHeartbeatMessageTypeThenAutowireFails() { - ThrowingCallable bad = () -> this.spring.configLocations(xml("HeartbeatInterceptTypeConfig")).autowire(); - assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("HeartbeatInterceptTypeConfig")).autowire()); } @Test public void configureWhenUsingOtherMessageTypeThenAutowireFails() { - ThrowingCallable bad = () -> this.spring.configLocations(xml("OtherInterceptTypeConfig")).autowire(); - assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("OtherInterceptTypeConfig")).autowire()); } @Test public void configureWhenUsingUnsubscribeMessageTypeThenAutowireFails() { - ThrowingCallable bad = () -> this.spring.configLocations(xml("UnsubscribeInterceptTypeConfig")).autowire(); - assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class); + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> this.spring.configLocations(xml("UnsubscribeInterceptTypeConfig")).autowire()); } @Test @@ -301,16 +304,17 @@ public void sendWhenNoIdSpecifiedThenCustomArgumentResolversAreNotOverridden() { public void sendWhenUsingCustomPathMatcherThenSecurityAppliesIt() { this.spring.configLocations(xml("CustomPathMatcherConfig")).autowire(); Message message = message("/denyAll.a"); - assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(Exception.class).isThrownBy(send(message)) + .withCauseInstanceOf(AccessDeniedException.class); message = message("/denyAll.a.b"); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test public void sendWhenIdSpecifiedThenSecurityDoesNotIntegrateWithClientInboundChannel() { this.spring.configLocations(xml("IdConfig")).autowire(); Message message = message("/denyAll"); - assertThatCode(send(message)).doesNotThrowAnyException(); + send(message); } @Test @@ -318,14 +322,16 @@ public void sendWhenIdSpecifiedThenSecurityDoesNotIntegrateWithClientInboundChan public void sendWhenIdSpecifiedAndExplicitlyIntegratedWhenBrokerUsesClientInboundChannel() { this.spring.configLocations(xml("IdIntegratedConfig")).autowire(); Message message = message("/denyAll"); - assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(Exception.class).isThrownBy(send(message)) + .withCauseInstanceOf(AccessDeniedException.class); } @Test public void sendWhenNoIdSpecifiedThenSecurityDoesntOverrideCustomInterceptors() { this.spring.configLocations(xml("CustomInterceptorConfig")).autowire(); Message message = message("/throwAll"); - assertThatThrownBy(send(message)).hasCauseInstanceOf(UnsupportedOperationException.class); + assertThatExceptionOfType(Exception.class).isThrownBy(send(message)) + .withCauseInstanceOf(UnsupportedOperationException.class); } @Test @@ -333,7 +339,8 @@ public void sendWhenNoIdSpecifiedThenSecurityDoesntOverrideCustomInterceptors() public void sendWhenCustomExpressionHandlerThenAuthorizesAccordingly() { this.spring.configLocations(xml("CustomExpressionHandlerConfig")).autowire(); Message message = message("/denyNile"); - assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(Exception.class).isThrownBy(send(message)) + .withCauseInstanceOf(AccessDeniedException.class); } private String xml(String configName) { diff --git a/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java b/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java index 8c6362b14e2..7cd80768dc8 100644 --- a/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java @@ -33,9 +33,7 @@ import org.springframework.security.core.userdetails.UserDetailsChecker; import org.springframework.security.crypto.password.PasswordEncoder; -import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -85,7 +83,7 @@ public void setup() { @Test public void setSchedulerWhenNullThenIllegalArgumentException() { - assertThatCode(() -> this.manager.setScheduler(null)).isInstanceOf(IllegalArgumentException.class); + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> this.manager.setScheduler(null)); } @Test @@ -125,7 +123,8 @@ public void authenticateWhenPasswordServiceAndBadCredentialsThenNotUpdated() { this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user, this.user.getPassword()); - assertThatThrownBy(() -> this.manager.authenticate(token).block()).isInstanceOf(BadCredentialsException.class); + assertThatExceptionOfType(BadCredentialsException.class) + .isThrownBy(() -> this.manager.authenticate(token).block()); verifyZeroInteractions(this.userDetailsPasswordService); } diff --git a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java index 84295033198..b045b798bb2 100644 --- a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java @@ -49,7 +49,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -362,7 +362,7 @@ public void authenticateWhenBadCredentialsAndPasswordManagerThenNoUpdate() { UserDetails user = PasswordEncodedUser.user(); given(encoder.matches(any(), any())).willReturn(false); given(userDetailsService.loadUserByUsername(any())).willReturn(user); - assertThatThrownBy(() -> provider.authenticate(token)).isInstanceOf(BadCredentialsException.class); + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token)); verifyZeroInteractions(passwordManager); } diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/JaasGrantedAuthorityTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/JaasGrantedAuthorityTests.java index 09f2441ba1e..83106933372 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/JaasGrantedAuthorityTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/JaasGrantedAuthorityTests.java @@ -18,7 +18,7 @@ import org.junit.Test; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Clement Ng @@ -26,20 +26,16 @@ */ public class JaasGrantedAuthorityTests { - /** - */ @Test public void authorityWithNullRoleFailsAssertion() { - assertThatThrownBy(() -> new JaasGrantedAuthority(null, null)).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("role cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new JaasGrantedAuthority(null, null)) + .withMessageContaining("role cannot be null"); } - /** - */ @Test public void authorityWithNullPrincipleFailsAssertion() { - assertThatThrownBy(() -> new JaasGrantedAuthority("role", null)).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("principal cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new JaasGrantedAuthority("role", null)) + .withMessageContaining("principal cannot be null"); } } diff --git a/core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTests.java b/core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTests.java index 17019a626fb..f37fb4c5bf8 100644 --- a/core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTests.java +++ b/core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTests.java @@ -28,7 +28,7 @@ import org.springframework.core.convert.converter.Converter; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link RsaKeyConverters} @@ -99,8 +99,7 @@ public void pkcs8WhenConvertingPkcs8PrivateKeyThenOk() { @Test public void pkcs8WhenConvertingPkcs1PrivateKeyThenIllegalArgumentException() { - assertThatCode(() -> this.pkcs8.convert(toInputStream(PKCS1_PRIVATE_KEY))) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.pkcs8.convert(toInputStream(PKCS1_PRIVATE_KEY))); } @Test @@ -111,8 +110,7 @@ public void x509WhenConverteringX509PublicKeyThenOk() { @Test public void x509WhenConvertingDerEncodedX509PublicKeyThenIllegalArgumentException() { - assertThatCode(() -> this.x509.convert(toInputStream(MALFORMED_X509_KEY))) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.x509.convert(toInputStream(MALFORMED_X509_KEY))); } private static InputStream toInputStream(String string) { diff --git a/core/src/test/java/org/springframework/security/jackson2/SecurityJackson2ModulesTests.java b/core/src/test/java/org/springframework/security/jackson2/SecurityJackson2ModulesTests.java index 106750a1e62..81b78f6b785 100644 --- a/core/src/test/java/org/springframework/security/jackson2/SecurityJackson2ModulesTests.java +++ b/core/src/test/java/org/springframework/security/jackson2/SecurityJackson2ModulesTests.java @@ -32,7 +32,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch @@ -51,7 +51,8 @@ public void setup() { @Test public void readValueWhenNotAllowedOrMappedThenThrowsException() { String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlisted\",\"property\":\"bar\"}"; - assertThatThrownBy(() -> this.mapper.readValue(content, Object.class)).hasStackTraceContaining("allowlist"); + assertThatExceptionOfType(Exception.class).isThrownBy(() -> this.mapper.readValue(content, Object.class)) + .withStackTraceContaining("allowlist"); } @Test diff --git a/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java b/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java index c98fd1016b4..e123f27c5fa 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java @@ -27,7 +27,7 @@ import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.verify; @@ -120,41 +120,43 @@ public void matchesWhenNoopThenDelegatesToNoop() { @Test public void matchesWhenUnMappedThenIllegalArgumentException() { - assertThatThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{unmapped}" + this.rawPassword)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("There is no PasswordEncoder mapped for the id \"unmapped\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{unmapped}" + this.rawPassword)) + .withMessage("There is no PasswordEncoder mapped for the id \"unmapped\""); verifyZeroInteractions(this.bcrypt, this.noop); } @Test public void matchesWhenNoClosingPrefixStringThenIllegalArgumentExcetion() { - assertThatThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{bcrypt" + this.rawPassword)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("There is no PasswordEncoder mapped for the id \"null\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{bcrypt" + this.rawPassword)) + .withMessage("There is no PasswordEncoder mapped for the id \"null\""); verifyZeroInteractions(this.bcrypt, this.noop); } @Test public void matchesWhenNoStartingPrefixStringThenFalse() { - assertThatThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "bcrypt}" + this.rawPassword)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("There is no PasswordEncoder mapped for the id \"null\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "bcrypt}" + this.rawPassword)) + .withMessage("There is no PasswordEncoder mapped for the id \"null\""); verifyZeroInteractions(this.bcrypt, this.noop); } @Test public void matchesWhenNoIdStringThenFalse() { - assertThatThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{}" + this.rawPassword)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("There is no PasswordEncoder mapped for the id \"\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{}" + this.rawPassword)) + .withMessage("There is no PasswordEncoder mapped for the id \"\""); verifyZeroInteractions(this.bcrypt, this.noop); } @Test public void matchesWhenPrefixInMiddleThenFalse() { - assertThatThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "invalid" + this.bcryptEncodedPassword)) + assertThatIllegalArgumentException() + .isThrownBy( + () -> this.passwordEncoder.matches(this.rawPassword, "invalid" + this.bcryptEncodedPassword)) .isInstanceOf(IllegalArgumentException.class) - .hasMessage("There is no PasswordEncoder mapped for the id \"null\""); + .withMessage("There is no PasswordEncoder mapped for the id \"null\""); verifyZeroInteractions(this.bcrypt, this.noop); } @@ -162,9 +164,9 @@ public void matchesWhenPrefixInMiddleThenFalse() { public void matchesWhenIdIsNullThenFalse() { this.delegates = new Hashtable<>(this.delegates); DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates); - assertThatThrownBy(() -> passwordEncoder.matches(this.rawPassword, this.rawPassword)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("There is no PasswordEncoder mapped for the id \"null\""); + assertThatIllegalArgumentException() + .isThrownBy(() -> passwordEncoder.matches(this.rawPassword, this.rawPassword)) + .withMessage("There is no PasswordEncoder mapped for the id \"null\""); verifyZeroInteractions(this.bcrypt, this.noop); } diff --git a/etc/checkstyle/checkstyle.xml b/etc/checkstyle/checkstyle.xml index e2c3704a5a4..83028dcf7a7 100644 --- a/etc/checkstyle/checkstyle.xml +++ b/etc/checkstyle/checkstyle.xml @@ -14,4 +14,12 @@ + + + + + + + + \ No newline at end of file diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java index b297fe66cde..8a14656709f 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java @@ -32,6 +32,7 @@ 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.fail; /** @@ -138,15 +139,8 @@ public void startWithLdapOverSslWithWrongPassword() throws Exception { server.setLdapOverSslEnabled(true); server.setKeyStoreFile(temporaryKeyStoreFile); server.setCertificatePassord("incorrect-password"); - - try { - server.afterPropertiesSet(); - fail("Expected a RuntimeException to be thrown."); - } - catch (RuntimeException ex) { - assertThat(ex).hasMessage("Server startup failed"); - assertThat(ex).hasRootCauseInstanceOf(UnrecoverableKeyException.class); - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(server::afterPropertiesSet) + .withMessage("Server startup failed").withRootCauseInstanceOf(UnrecoverableKeyException.class); } /** diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerModifyPasswordTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerModifyPasswordTests.java index 275cd0cb02e..ab2e6e3992d 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerModifyPasswordTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerModifyPasswordTests.java @@ -36,7 +36,7 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link LdapUserDetailsManager#changePassword}, specifically relating to the @@ -63,8 +63,8 @@ public void setup() { @Test @WithMockUser(username = "bob", password = "bobspassword", authorities = "ROLE_USER") public void changePasswordWhenOldPasswordIsIncorrectThenThrowsException() { - assertThatCode(() -> this.userDetailsManager.changePassword("wrongoldpassword", "bobsnewpassword")) - .isInstanceOf(BadCredentialsException.class); + assertThatExceptionOfType(BadCredentialsException.class) + .isThrownBy(() -> this.userDetailsManager.changePassword("wrongoldpassword", "bobsnewpassword")); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeOAuth2AuthorizedClientProviderTests.java index bb777ce8202..88e52dbf4d5 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeOAuth2AuthorizedClientProviderTests.java @@ -26,7 +26,8 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link AuthorizationCodeOAuth2AuthorizedClientProvider}. @@ -54,8 +55,7 @@ public void setup() { @Test public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null)); } @Test @@ -77,8 +77,8 @@ public void authorizeWhenAuthorizationCodeAndAuthorizedThenNotAuthorize() { public void authorizeWhenAuthorizationCodeAndNotAuthorizedThenAuthorize() { OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext .withClientRegistration(this.clientRegistration).principal(this.principal).build(); - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext)) - .isInstanceOf(ClientAuthorizationRequiredException.class); + assertThatExceptionOfType(ClientAuthorizationRequiredException.class) + .isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext)); } } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests.java index 190af59bc3a..8f6c25abd15 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests.java @@ -26,7 +26,8 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link AuthorizationCodeReactiveOAuth2AuthorizedClientProvider}. @@ -54,8 +55,7 @@ public void setup() { @Test public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null).block()); } @Test @@ -77,8 +77,8 @@ public void authorizeWhenAuthorizationCodeAndAuthorizedThenNotAuthorize() { public void authorizeWhenAuthorizationCodeAndNotAuthorizedThenAuthorize() { OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext .withClientRegistration(this.clientRegistration).principal(this.principal).build(); - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block()) - .isInstanceOf(ClientAuthorizationRequiredException.class); + assertThatExceptionOfType(ClientAuthorizationRequiredException.class) + .isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block()); } } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java index 8de43688772..6aa17a1365c 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java @@ -35,8 +35,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.BDDMockito.given; @@ -108,57 +108,58 @@ public void onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Auth @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( + assertThatIllegalArgumentException().isThrownBy( () -> new AuthorizedClientServiceOAuth2AuthorizedClientManager(null, this.authorizedClientService)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("clientRegistrationRepository cannot be null"); + .withMessage("clientRegistrationRepository cannot be null"); } @Test public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( + assertThatIllegalArgumentException().isThrownBy( () -> new AuthorizedClientServiceOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("authorizedClientService cannot be null"); + .withMessage("authorizedClientService cannot be null"); } @Test public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClientProvider cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null)) + .withMessage("authorizedClientProvider cannot be null"); } @Test public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("contextAttributesMapper cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null)) + .withMessage("contextAttributesMapper cannot be null"); } @Test public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationSuccessHandler cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null)) + .withMessage("authorizationSuccessHandler cannot be null"); } @Test public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationFailureHandler cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null)) + .withMessage("authorizationFailureHandler cannot be null"); } @Test public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.authorize(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizeRequest cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null)) + .withMessage("authorizeRequest cannot be null"); } @Test public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() { OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId("invalid-registration-id").principal(this.principal).build(); - assertThatThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Could not find ClientRegistration with id 'invalid-registration-id'"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest)) + .withMessage("Could not find ClientRegistration with id 'invalid-registration-id'"); } @SuppressWarnings("unchecked") @@ -308,7 +309,8 @@ public void reauthorizeWhenErrorCodeMatchThenRemoveAuthorizedClient() { .willThrow(authorizationException); OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient) .principal(this.principal).build(); - assertThatCode(() -> this.authorizedClientManager.authorize(reauthorizeRequest)) + assertThatExceptionOfType(ClientAuthorizationException.class) + .isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest)) .isEqualTo(authorizationException); verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal), any()); @@ -324,7 +326,8 @@ public void reauthorizeWhenErrorCodeDoesNotMatchThenDoNotRemoveAuthorizedClient( .willThrow(authorizationException); OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient) .principal(this.principal).build(); - assertThatCode(() -> this.authorizedClientManager.authorize(reauthorizeRequest)) + assertThatExceptionOfType(ClientAuthorizationException.class) + .isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest)) .isEqualTo(authorizationException); verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal), any()); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java index aafb30ec739..4edf4810526 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java @@ -39,8 +39,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.BDDMockito.given; @@ -105,46 +105,52 @@ public void setup() { @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(null, - this.authorizedClientService)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("clientRegistrationRepository cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(null, + this.authorizedClientService)) + .withMessage("clientRegistrationRepository cannot be null"); } @Test public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( - this.clientRegistrationRepository, null)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("authorizedClientService cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager( + this.clientRegistrationRepository, null)) + .withMessage("authorizedClientService cannot be null"); } @Test public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClientProvider cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null)) + .withMessage("authorizedClientProvider cannot be null"); } @Test public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("contextAttributesMapper cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null)) + .withMessage("contextAttributesMapper cannot be null"); } @Test public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationSuccessHandler cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null)) + .withMessage("authorizationSuccessHandler cannot be null"); } @Test public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationFailureHandler cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null)) + .withMessage("authorizationFailureHandler cannot be null"); } @Test public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.authorize(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizeRequest cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null)) + .withMessage("authorizeRequest cannot be null"); } @Test @@ -243,7 +249,9 @@ public void authorizeWhenInvalidTokenThenRemoveAuthorizedClient() { this.clientRegistration.getRegistrationId()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); - assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception); + assertThatExceptionOfType(ClientAuthorizationException.class) + .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) + .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); @@ -269,7 +277,9 @@ public void authorizeWhenInvalidGrantThenRemoveAuthorizedClient() { this.clientRegistration.getRegistrationId()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); - assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception); + assertThatExceptionOfType(ClientAuthorizationException.class) + .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) + .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); @@ -295,7 +305,9 @@ public void authorizeWhenServerErrorThenDoNotRemoveAuthorizedClient() { this.clientRegistration.getRegistrationId()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); - assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception); + assertThatExceptionOfType(ClientAuthorizationException.class) + .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) + .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); @@ -318,7 +330,9 @@ public void authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedCl new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null)); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); - assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) + .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); @@ -344,7 +358,9 @@ public void authorizeWhenOAuth2AuthorizationExceptionAndCustomFailureHandlerThen PublisherProbe authorizationFailureHandlerProbe = PublisherProbe.empty(); this.authorizedClientManager.setAuthorizationFailureHandler( (client, principal, attributes) -> authorizationFailureHandlerProbe.mono()); - assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) + .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java index 3fd74024662..4264a4718ce 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java @@ -34,7 +34,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -65,32 +65,34 @@ public void setup() { @Test public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) + .isInstanceOf(IllegalArgumentException.class).withMessage("accessTokenResponseClient cannot be null"); } @Test public void setClockSkewWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) + .withMessage("clockSkew cannot be null"); } @Test public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) + .withMessage("clockSkew must be >= 0"); } @Test public void setClockWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null)) + .withMessage("clock cannot be null"); } @Test public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null)) + .withMessage("context cannot be null"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java index b6014bf6c40..91ca2c2b946 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java @@ -35,7 +35,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -66,32 +66,34 @@ public void setup() { @Test public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) + .withMessage("accessTokenResponseClient cannot be null"); } @Test public void setClockSkewWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) + .withMessage("clockSkew cannot be null"); } @Test public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) + .withMessage("clockSkew must be >= 0"); } @Test public void setClockWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null)) + .withMessage("clock cannot be null"); } @Test public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null).block()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null).block()) + .withMessage("context cannot be null"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java index cd86c5d4166..f595fa571cc 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java @@ -27,7 +27,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -41,18 +41,18 @@ public class DelegatingOAuth2AuthorizedClientProviderTests { @Test public void constructorWhenProvidersIsEmptyThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(new OAuth2AuthorizedClientProvider[0])) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(Collections.emptyList())) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(new OAuth2AuthorizedClientProvider[0])); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(Collections.emptyList())); } @Test public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() { DelegatingOAuth2AuthorizedClientProvider delegate = new DelegatingOAuth2AuthorizedClientProvider( mock(OAuth2AuthorizedClientProvider.class)); - assertThatThrownBy(() -> delegate.authorize(null)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("context cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> delegate.authorize(null)) + .withMessage("context cannot be null"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java index 802465922cb..5619fd4be29 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java @@ -28,7 +28,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -42,18 +42,18 @@ public class DelegatingReactiveOAuth2AuthorizedClientProviderTests { @Test public void constructorWhenProvidersIsEmptyThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider( - new ReactiveOAuth2AuthorizedClientProvider[0])).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(Collections.emptyList())) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider( + new ReactiveOAuth2AuthorizedClientProvider[0])); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(Collections.emptyList())); } @Test public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() { DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider( mock(ReactiveOAuth2AuthorizedClientProvider.class)); - assertThatThrownBy(() -> delegate.authorize(null).block()).isInstanceOf(IllegalArgumentException.class) - .hasMessage("context cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> delegate.authorize(null).block()) + .withMessage("context cannot be null"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java index 0c7b2c5be97..42b141468f2 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java @@ -29,8 +29,8 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatObject; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -67,8 +67,9 @@ public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArg @Test public void constructorWhenAuthorizedClientsIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClients cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository, null)) + .withMessage("authorizedClients cannot be empty"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java index 6855cd58466..a972dfa8e07 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java @@ -35,7 +35,7 @@ import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.OAuth2AccessToken; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; /** @@ -76,40 +76,36 @@ public void setup() { @Test public void constructorNullClientRegistrationRepositoryThenThrowsIllegalArgumentException() { this.clientRegistrationRepository = null; - assertThatThrownBy(() -> new InMemoryReactiveOAuth2AuthorizedClientService(this.clientRegistrationRepository)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new InMemoryReactiveOAuth2AuthorizedClientService(this.clientRegistrationRepository)); } @Test public void loadAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() { this.clientRegistrationId = null; - assertThatThrownBy( - () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)); } @Test public void loadAuthorizedClientWhenClientRegistrationIdEmptyThenIllegalArgumentException() { this.clientRegistrationId = ""; - assertThatThrownBy( - () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)); } @Test public void loadAuthorizedClientWhenPrincipalNameNullThenIllegalArgumentException() { this.principalName = null; - assertThatThrownBy( - () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)); } @Test public void loadAuthorizedClientWhenPrincipalNameEmptyThenIllegalArgumentException() { this.principalName = ""; - assertThatThrownBy( - () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)); } @Test @@ -145,8 +141,8 @@ public void loadAuthorizedClientWhenClientRegistrationFoundThenFound() { @Test public void saveAuthorizedClientWhenAuthorizedClientNullThenIllegalArgumentException() { OAuth2AuthorizedClient authorizedClient = null; - assertThatThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal)); } @Test @@ -154,38 +150,36 @@ public void saveAuthorizedClientWhenPrincipalNullThenIllegalArgumentException() OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principalName, this.accessToken); this.principal = null; - assertThatThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal)); } @Test public void removeAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() { this.clientRegistrationId = null; - assertThatThrownBy( - () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)); } @Test public void removeAuthorizedClientWhenClientRegistrationIdEmptyThenIllegalArgumentException() { this.clientRegistrationId = ""; - assertThatThrownBy( - () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)); } @Test public void removeAuthorizedClientWhenPrincipalNameNullThenIllegalArgumentException() { this.principalName = null; - assertThatThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(this.clientRegistrationId, - this.principalName)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientService + .removeAuthorizedClient(this.clientRegistrationId, this.principalName)); } @Test public void removeAuthorizedClientWhenPrincipalNameEmptyThenIllegalArgumentException() { this.principalName = ""; - assertThatThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(this.clientRegistrationId, - this.principalName)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientService + .removeAuthorizedClient(this.clientRegistrationId, this.principalName)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java index 49b7fbb3fa2..684f0bd59c6 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java @@ -54,7 +54,8 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.within; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; @@ -103,40 +104,45 @@ public void tearDown() { @Test public void constructorWhenJdbcOperationsIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new JdbcOAuth2AuthorizedClientService(null, this.clientRegistrationRepository)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("jdbcOperations cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JdbcOAuth2AuthorizedClientService(null, this.clientRegistrationRepository)) + .withMessage("jdbcOperations cannot be null"); } @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new JdbcOAuth2AuthorizedClientService(this.jdbcOperations, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationRepository cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JdbcOAuth2AuthorizedClientService(this.jdbcOperations, null)) + .withMessage("clientRegistrationRepository cannot be null"); } @Test public void setAuthorizedClientRowMapperWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientService.setAuthorizedClientRowMapper(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClientRowMapper cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientService.setAuthorizedClientRowMapper(null)) + .withMessage("authorizedClientRowMapper cannot be null"); } @Test public void setAuthorizedClientParametersMapperWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientService.setAuthorizedClientParametersMapper(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("authorizedClientParametersMapper cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientService.setAuthorizedClientParametersMapper(null)) + .withMessage("authorizedClientParametersMapper cannot be null"); } @Test public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, "principalName")) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationId cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, "principalName")) + .withMessage("clientRegistrationId cannot be empty"); } @Test public void loadAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientService - .loadAuthorizedClient(this.clientRegistration.getRegistrationId(), null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("principalName cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientService + .loadAuthorizedClient(this.clientRegistration.getRegistrationId(), null)) + .withMessage("principalName cannot be empty"); } @Test @@ -177,26 +183,28 @@ public void loadAuthorizedClientWhenExistsButNotFoundInClientRegistrationReposit Authentication principal = createPrincipal(); OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration); this.authorizedClientService.saveAuthorizedClient(expected, principal); - assertThatThrownBy(() -> this.authorizedClientService - .loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())) - .isInstanceOf(DataRetrievalFailureException.class) - .hasMessage("The ClientRegistration with id '" + this.clientRegistration.getRegistrationId() - + "' exists in the data source, however, it was not found in the ClientRegistrationRepository."); + assertThatExceptionOfType(DataRetrievalFailureException.class) + .isThrownBy(() -> this.authorizedClientService + .loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())) + .withMessage("The ClientRegistration with id '" + this.clientRegistration.getRegistrationId() + + "' exists in the data source, however, it was not found in the ClientRegistrationRepository."); } @Test public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() { Authentication principal = createPrincipal(); - assertThatThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, principal)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, principal)) + .withMessage("authorizedClient cannot be null"); } @Test public void saveAuthorizedClientWhenPrincipalIsNullThenThrowIllegalArgumentException() { Authentication principal = createPrincipal(); OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration); - assertThatThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("principal cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, null)) + .withMessage("principal cannot be null"); } @Test @@ -293,15 +301,17 @@ public void saveLoadAuthorizedClientWhenCustomStrategiesSetThenCalled() throws E @Test public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, "principalName")) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationId cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, "principalName")) + .withMessage("clientRegistrationId cannot be empty"); } @Test public void removeAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientService - .removeAuthorizedClient(this.clientRegistration.getRegistrationId(), null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("principalName cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientService + .removeAuthorizedClient(this.clientRegistration.getRegistrationId(), null)) + .withMessage("principalName cannot be empty"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizationContextTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizationContextTests.java index 103fe77dce6..b2bcab54ab3 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizationContextTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizationContextTests.java @@ -26,7 +26,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.entry; /** @@ -52,20 +52,23 @@ public void setup() { @Test public void withClientRegistrationWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(null).build()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistration cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(null).build()) + .withMessage("clientRegistration cannot be null"); } @Test public void withAuthorizedClientWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizationContext.withAuthorizedClient(null).build()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> OAuth2AuthorizationContext.withAuthorizedClient(null).build()) + .withMessage("authorizedClient cannot be null"); } @Test public void withClientRegistrationWhenPrincipalIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).build()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("principal cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).build()) + .withMessage("principal cannot be null"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizeRequestTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizeRequestTests.java index cf348d52cdb..588f6283f53 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizeRequestTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizeRequestTests.java @@ -26,7 +26,7 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.entry; /** @@ -46,28 +46,29 @@ public class OAuth2AuthorizeRequestTests { @Test public void withClientRegistrationIdWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizeRequest.withClientRegistrationId(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationId cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest.withClientRegistrationId(null)) + .withMessage("clientRegistrationId cannot be empty"); } @Test public void withAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizeRequest.withAuthorizedClient(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClient cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest.withAuthorizedClient(null)) + .withMessage("authorizedClient cannot be null"); } @Test public void withClientRegistrationIdWhenPrincipalIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizeRequest - .withClientRegistrationId(this.clientRegistration.getRegistrationId()).build()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("principal cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> OAuth2AuthorizeRequest + .withClientRegistrationId(this.clientRegistration.getRegistrationId()).build()) + .withMessage("principal cannot be null"); } @Test public void withClientRegistrationIdWhenPrincipalNameIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizeRequest + assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal((String) null).build()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("principalName cannot be empty"); + .withMessage("principalName cannot be empty"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientIdTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientIdTests.java index 5a14d458546..f8a9cdf4de2 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientIdTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientIdTests.java @@ -19,7 +19,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2AuthorizedClientId}. @@ -30,14 +30,14 @@ public class OAuth2AuthorizedClientIdTests { @Test public void constructorWhenRegistrationIdNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizedClientId(null, "test-principal")) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationId cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientId(null, "test-principal")) + .withMessage("clientRegistrationId cannot be empty"); } @Test public void constructorWhenPrincipalNameNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizedClientId("test-client", null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("principalName cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientId("test-client", null)) + .withMessage("principalName cannot be empty"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java index c1639e420c3..a9ad9639635 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java @@ -39,7 +39,8 @@ import org.springframework.web.client.RestOperations; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.BDDMockito.given; @@ -82,8 +83,8 @@ public void setup() { @Test public void providerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizedClientProviderBuilder.builder().provider(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> OAuth2AuthorizedClientProviderBuilder.builder().provider(null)); } @Test @@ -93,8 +94,8 @@ public void buildWhenAuthorizationCodeProviderThenProviderAuthorizes() { OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext .withClientRegistration(TestClientRegistrations.clientRegistration().build()).principal(this.principal) .build(); - assertThatThrownBy(() -> authorizedClientProvider.authorize(authorizationContext)) - .isInstanceOf(ClientAuthorizationRequiredException.class); + assertThatExceptionOfType(ClientAuthorizationRequiredException.class) + .isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext)); } @Test @@ -155,8 +156,8 @@ public void buildWhenAllProvidersThenProvidersAuthorize() { // authorization_code OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext .withClientRegistration(clientRegistration).principal(this.principal).build(); - assertThatThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext)) - .isInstanceOf(ClientAuthorizationRequiredException.class); + assertThatExceptionOfType(ClientAuthorizationRequiredException.class) + .isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext)); // refresh_token OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken()); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java index 8ded4880917..e172c65b1c6 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java @@ -34,7 +34,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -65,32 +65,34 @@ public void setup() { @Test public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) + .withMessage("accessTokenResponseClient cannot be null"); } @Test public void setClockSkewWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) + .withMessage("clockSkew cannot be null"); } @Test public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) + .withMessage("clockSkew must be >= 0"); } @Test public void setClockWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null)) + .withMessage("clock cannot be null"); } @Test public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null)) + .withMessage("context cannot be null"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java index 53f11ad2dbf..e54dc285fcc 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java @@ -35,7 +35,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -66,32 +66,34 @@ public void setup() { @Test public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) + .withMessage("accessTokenResponseClient cannot be null"); } @Test public void setClockSkewWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) + .withMessage("clockSkew cannot be null"); } @Test public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) + .withMessage("clockSkew must be >= 0"); } @Test public void setClockWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null)) + .withMessage("clock cannot be null"); } @Test public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null).block()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null).block()) + .withMessage("context cannot be null"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java index a43dba12119..b555ffc3e3e 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java @@ -38,7 +38,8 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -73,8 +74,8 @@ public void cleanup() throws Exception { @Test public void providerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(null)); } @Test @@ -83,8 +84,8 @@ public void buildWhenAuthorizationCodeProviderThenProviderAuthorizes() { .builder().authorizationCode().build(); OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext .withClientRegistration(this.clientRegistrationBuilder.build()).principal(this.principal).build(); - assertThatThrownBy(() -> authorizedClientProvider.authorize(authorizationContext).block()) - .isInstanceOf(ClientAuthorizationRequiredException.class); + assertThatExceptionOfType(ClientAuthorizationRequiredException.class) + .isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext).block()); } @Test @@ -157,8 +158,8 @@ public void buildWhenAllProvidersThenProvidersAuthorize() throws Exception { // authorization_code OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext .withClientRegistration(this.clientRegistrationBuilder.build()).principal(this.principal).build(); - assertThatThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext).block()) - .isInstanceOf(ClientAuthorizationRequiredException.class); + assertThatExceptionOfType(ClientAuthorizationRequiredException.class) + .isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext).block()); // refresh_token OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(), this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken()); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java index ee63d83c364..8451e115cbc 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java @@ -38,7 +38,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -78,32 +78,34 @@ public void setup() { @Test public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) + .withMessage("accessTokenResponseClient cannot be null"); } @Test public void setClockSkewWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) + .withMessage("clockSkew cannot be null"); } @Test public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) + .withMessage("clockSkew must be >= 0"); } @Test public void setClockWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null)) + .withMessage("clock cannot be null"); } @Test public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null)) + .withMessage("context cannot be null"); } @Test @@ -193,9 +195,9 @@ public void authorizeWhenAuthorizedAndInvalidRequestScopeProvidedThenThrowIllega OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext .withAuthorizedClient(this.authorizedClient).principal(this.principal) .attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, invalidRequestScope).build(); - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageStartingWith("The context attribute must be of type String[] '" + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext)) + .withMessageStartingWith("The context attribute must be of type String[] '" + OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'"); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java index 07dcd2b7a1d..3b628587477 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java @@ -39,7 +39,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -79,32 +79,34 @@ public void setup() { @Test public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null)) + .withMessage("accessTokenResponseClient cannot be null"); } @Test public void setClockSkewWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null)) + .withMessage("clockSkew cannot be null"); } @Test public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1))) + .withMessage("clockSkew must be >= 0"); } @Test public void setClockWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null)) + .withMessage("clock cannot be null"); } @Test public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null).block()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null).block()) + .withMessage("context cannot be null"); } @Test @@ -196,9 +198,9 @@ public void authorizeWhenAuthorizedAndInvalidRequestScopeProvidedThenThrowIllega OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext .withAuthorizedClient(this.authorizedClient).principal(this.principal) .attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, invalidRequestScope).build(); - assertThatThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageStartingWith("The context attribute must be of type String[] '" + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block()) + .withMessageStartingWith("The context attribute must be of type String[] '" + OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'"); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java index 251dbb8fc9b..2ff9683ef49 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java @@ -38,7 +38,8 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -69,8 +70,7 @@ public void setUp() { @Test public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationProvider(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationProvider(null)); } @Test @@ -84,10 +84,10 @@ public void authenticateWhenAuthorizationErrorResponseThenThrowOAuth2Authorizati .errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, authorizationResponse); - assertThatThrownBy(() -> this.authenticationProvider.authenticate( - new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange))) - .isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.authenticationProvider.authenticate( + new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange))) + .withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST); } @Test @@ -96,10 +96,10 @@ public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationReque .build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, authorizationResponse); - assertThatThrownBy(() -> this.authenticationProvider.authenticate( - new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange))) - .isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining("invalid_state_parameter"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.authenticationProvider.authenticate( + new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange))) + .withMessageContaining("invalid_state_parameter"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationTokenTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationTokenTests.java index c93b774a3c8..b96992ea857 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationTokenTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationTokenTests.java @@ -30,7 +30,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2AuthorizationCodeAuthenticationToken}. @@ -55,14 +55,14 @@ public void setUp() { @Test public void constructorAuthorizationRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange)); } @Test public void constructorAuthorizationRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null)); } @Test @@ -81,21 +81,21 @@ public void constructorAuthorizationRequestResponseWhenAllParametersProvidedAndV @Test public void constructorTokenRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange, - this.accessToken)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, + this.authorizationExchange, this.accessToken)); } @Test public void constructorTokenRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( - () -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null, this.accessToken)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null, this.accessToken)); } @Test public void constructorTokenRequestResponseWhenAccessTokenIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, - this.authorizationExchange, null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, + this.authorizationExchange, null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java index 459ac5c5b9f..91731b06428 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java @@ -38,7 +38,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -70,13 +70,13 @@ public void setup() { @Test public void authenticateWhenErrorThenOAuth2AuthorizationException() { this.authorizationResponse = TestOAuth2AuthorizationResponses.error(); - assertThatCode(() -> authenticate()).isInstanceOf(OAuth2AuthorizationException.class); + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate()); } @Test public void authenticateWhenStateNotEqualThenOAuth2AuthorizationException() { this.authorizationRequest.state("notequal"); - assertThatCode(() -> authenticate()).isInstanceOf(OAuth2AuthorizationException.class); + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate()); } @Test @@ -97,7 +97,7 @@ public void authenticateWhenEmptyThenEmpty() { public void authenticateWhenOAuth2AuthorizationExceptionThenOAuth2AuthorizationException() { given(this.accessTokenResponseClient.getTokenResponse(any())) .willReturn(Mono.error(() -> new OAuth2AuthorizationException(new OAuth2Error("error")))); - assertThatCode(() -> authenticate()).isInstanceOf(OAuth2AuthorizationException.class); + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate()); } private OAuth2AuthorizationCodeAuthenticationToken authenticate() { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManagerTests.java index 9309ba2db3e..d6e5acd1278 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManagerTests.java @@ -52,8 +52,8 @@ import org.springframework.security.oauth2.core.user.OAuth2User; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.anyCollection; import static org.mockito.BDDMockito.given; @@ -90,22 +90,20 @@ public void setup() { @Test public void constructorWhenNullAccessTokenResponseClientThenIllegalArgumentException() { this.accessTokenResponseClient = null; - assertThatThrownBy( - () -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService)); } @Test public void constructorWhenNullUserServiceThenIllegalArgumentException() { this.userService = null; - assertThatThrownBy( - () -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService)); } @Test public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.manager.setAuthoritiesMapper(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setAuthoritiesMapper(null)); } @Test @@ -113,8 +111,8 @@ public void authenticateWhenNoSubscriptionThenDoesNothing() { // we didn't do anything because it should cause a ClassCastException (as verified // below) TestingAuthenticationToken token = new TestingAuthenticationToken("a", "b"); - assertThatCode(() -> this.manager.authenticate(token)).doesNotThrowAnyException(); - assertThatThrownBy(() -> this.manager.authenticate(token).block()).isInstanceOf(Throwable.class); + this.manager.authenticate(token); + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> this.manager.authenticate(token).block()); } @Test @@ -127,15 +125,15 @@ public void authenticationWhenOidcThenEmpty() { @Test public void authenticationWhenErrorThenOAuth2AuthenticationException() { this.authorizationResponseBldr = OAuth2AuthorizationResponse.error("error").state("state"); - assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block()) - .isInstanceOf(OAuth2AuthenticationException.class); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.manager.authenticate(loginToken()).block()); } @Test public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() { this.authorizationResponseBldr.state("notmatch"); - assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block()) - .isInstanceOf(OAuth2AuthenticationException.class); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.manager.authenticate(loginToken()).block()); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultAuthorizationCodeTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultAuthorizationCodeTokenResponseClientTests.java index 9338e165b5a..70d488ae33a 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultAuthorizationCodeTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultAuthorizationCodeTokenResponseClientTests.java @@ -39,7 +39,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultAuthorizationCodeTokenResponseClient}. @@ -74,20 +75,17 @@ public void cleanup() throws Exception { @Test public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null)); } @Test public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null)); } @Test public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null)); } @Test @@ -151,22 +149,22 @@ public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAu String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n" + " \"token_type\": \"not-bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n"; this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest())) - .isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest())) + .withMessageContaining( "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response") - .hasMessageContaining("tokenType cannot be null"); + .withMessageContaining("tokenType cannot be null"); } @Test public void getTokenResponseWhenSuccessResponseAndMissingTokenTypeParameterThenThrowOAuth2AuthorizationException() { String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\"\n" + "}\n"; this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest())) - .isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest())) + .withMessageContaining( "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response") - .hasMessageContaining("tokenType cannot be null"); + .withMessageContaining("tokenType cannot be null"); } @Test @@ -195,8 +193,9 @@ public void getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenAccessToke public void getTokenResponseWhenTokenUriInvalidThenThrowOAuth2AuthorizationException() { String invalidTokenUri = "https://invalid-provider.com/oauth2/token"; ClientRegistration clientRegistration = this.from(this.clientRegistration).tokenUri(invalidTokenUri).build(); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest( - clientRegistration))).isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy( + () -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest(clientRegistration))) + .withMessageContaining( "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response"); } @@ -209,8 +208,9 @@ public void getTokenResponseWhenMalformedResponseThenThrowOAuth2AuthorizationExc + " \"custom_parameter_2\": \"custom-value-2\"\n"; // "}\n"; // Make the JSON invalid/malformed this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest())) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest())) + .withMessageContaining( "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response"); } @@ -218,16 +218,18 @@ public void getTokenResponseWhenMalformedResponseThenThrowOAuth2AuthorizationExc public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() { String accessTokenErrorResponse = "{\n" + " \"error\": \"unauthorized_client\"\n" + "}\n"; this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400)); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest())) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("[unauthorized_client]"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest())) + .withMessageContaining("[unauthorized_client]"); } @Test public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() { this.server.enqueue(new MockResponse().setResponseCode(500)); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest())) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining( - "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest())) + .withMessageContaining("[invalid_token_response] An error occurred while attempting to retrieve " + + "the OAuth 2.0 Access Token Response"); } private OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest() { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultClientCredentialsTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultClientCredentialsTokenResponseClientTests.java index a7e28cf9548..6e0875ec79d 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultClientCredentialsTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultClientCredentialsTokenResponseClientTests.java @@ -36,7 +36,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultClientCredentialsTokenResponseClient}. @@ -69,20 +70,17 @@ public void cleanup() throws Exception { @Test public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null)); } @Test public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null)); } @Test public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null)); } @Test @@ -152,11 +150,11 @@ public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAu this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest( this.clientRegistration); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) + .withMessageContaining( "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response") - .hasMessageContaining("tokenType cannot be null"); + .withMessageContaining("tokenType cannot be null"); } @Test @@ -165,11 +163,11 @@ public void getTokenResponseWhenSuccessResponseAndMissingTokenTypeParameterThenT this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest( this.clientRegistration); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) + .withMessageContaining( "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response") - .hasMessageContaining("tokenType cannot be null"); + .withMessageContaining("tokenType cannot be null"); } @Test @@ -203,8 +201,9 @@ public void getTokenResponseWhenTokenUriInvalidThenThrowOAuth2AuthorizationExcep ClientRegistration clientRegistration = this.from(this.clientRegistration).tokenUri(invalidTokenUri).build(); OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest( clientRegistration); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) + .withMessageContaining( "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response"); } @@ -218,8 +217,9 @@ public void getTokenResponseWhenMalformedResponseThenThrowOAuth2AuthorizationExc this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest( this.clientRegistration); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) + .withMessageContaining( "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response"); } @@ -229,8 +229,9 @@ public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationExcepti this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400)); OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest( this.clientRegistration); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("[unauthorized_client]"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) + .withMessageContaining("[unauthorized_client]"); } @Test @@ -238,8 +239,9 @@ public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationE this.server.enqueue(new MockResponse().setResponseCode(500)); OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest( this.clientRegistration); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest)) + .withMessageContaining( "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response"); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultPasswordTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultPasswordTokenResponseClientTests.java index 31e196cf00f..e838ef47019 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultPasswordTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultPasswordTokenResponseClientTests.java @@ -37,7 +37,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultPasswordTokenResponseClient}. @@ -72,20 +73,17 @@ public void cleanup() throws Exception { @Test public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null)); } @Test public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null)); } @Test public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null)); } @Test @@ -141,11 +139,11 @@ public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAu this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest( this.clientRegistrationBuilder.build(), this.username, this.password); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest)) + .withMessageContaining( "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response") - .hasMessageContaining("tokenType cannot be null"); + .withMessageContaining("tokenType cannot be null"); } @Test @@ -169,8 +167,9 @@ public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationExcepti this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400)); OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest( this.clientRegistrationBuilder.build(), this.username, this.password); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("[unauthorized_client]"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest)) + .withMessageContaining("[unauthorized_client]"); } @Test @@ -178,9 +177,10 @@ public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationE this.server.enqueue(new MockResponse().setResponseCode(500)); OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest( this.clientRegistrationBuilder.build(), this.username, this.password); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining( - "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest)) + .withMessageContaining("[invalid_token_response] An error occurred while attempting to " + + "retrieve the OAuth 2.0 Access Token Response"); } private MockResponse jsonResponse(String json) { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultRefreshTokenTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultRefreshTokenTokenResponseClientTests.java index a4cd6dd27d7..474e627de2e 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultRefreshTokenTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultRefreshTokenTokenResponseClientTests.java @@ -40,7 +40,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultRefreshTokenTokenResponseClient}. @@ -76,20 +77,17 @@ public void cleanup() throws Exception { @Test public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null)); } @Test public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null)); } @Test public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null)); } @Test @@ -144,11 +142,11 @@ public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAu this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest( this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining( - "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response") - .hasMessageContaining("tokenType cannot be null"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest)) + .withMessageContaining("[invalid_token_response] An error occurred while attempting to " + + "retrieve the OAuth 2.0 Access Token Response") + .withMessageContaining("tokenType cannot be null"); } @Test @@ -174,8 +172,9 @@ public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationExcepti this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400)); OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest( this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("[unauthorized_client]"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest)) + .withMessageContaining("[unauthorized_client]"); } @Test @@ -183,9 +182,10 @@ public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationE this.server.enqueue(new MockResponse().setResponseCode(500)); OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest( this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest)) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining( - "[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest)) + .withMessageContaining("[invalid_token_response] An error occurred while attempting to " + + "retrieve the OAuth 2.0 Access Token Response"); } private MockResponse jsonResponse(String json) { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java index 1bb619e9b19..676ca8957aa 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java @@ -24,7 +24,7 @@ import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2ClientCredentialsGrantRequest}. @@ -45,8 +45,7 @@ public void setup() { @Test public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(null)); } @Test @@ -55,8 +54,8 @@ public void constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArg .clientId("client-1").authorizationGrantType(AuthorizationGrantType.IMPLICIT) .redirectUri("https://localhost:8080/redirect-uri").authorizationUri("https://provider.com/oauth2/auth") .clientName("Client 1").build(); - assertThatThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(clientRegistration)) - .isInstanceOf(IllegalArgumentException.class).hasMessage( + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(clientRegistration)).withMessage( "clientRegistration.authorizationGrantType must be AuthorizationGrantType.CLIENT_CREDENTIALS"); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestTests.java index 38e88cee946..dfcfe698413 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestTests.java @@ -23,7 +23,7 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2PasswordGrantRequest}. @@ -41,32 +41,37 @@ public class OAuth2PasswordGrantRequestTests { @Test public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(null, this.username, this.password)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistration cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2PasswordGrantRequest(null, this.username, this.password)) + .withMessage("clientRegistration cannot be null"); } @Test public void constructorWhenUsernameIsEmptyThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, null, this.password)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("username cannot be empty"); - assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, "", this.password)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("username cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, null, this.password)) + .withMessage("username cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, "", this.password)) + .withMessage("username cannot be empty"); } @Test public void constructorWhenPasswordIsEmptyThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, this.username, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("password cannot be empty"); - assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, this.username, "")) - .isInstanceOf(IllegalArgumentException.class).hasMessage("password cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, this.username, null)) + .withMessage("password cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, this.username, "")) + .withMessage("password cannot be empty"); } @Test public void constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException() { ClientRegistration registration = TestClientRegistrations.clientCredentials().build(); - assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(registration, this.username, this.password)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("clientRegistration.authorizationGrantType must be AuthorizationGrantType.PASSWORD"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2PasswordGrantRequest(registration, this.username, this.password)) + .withMessage("clientRegistration.authorizationGrantType must be AuthorizationGrantType.PASSWORD"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestTests.java index f9f7fffe8e0..8b51a22e04b 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestTests.java @@ -31,7 +31,7 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2RefreshTokenGrantRequest}. @@ -55,20 +55,23 @@ public void setup() { @Test public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2RefreshTokenGrantRequest(null, this.accessToken, this.refreshToken)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistration cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(null, this.accessToken, this.refreshToken)) + .withMessage("clientRegistration cannot be null"); } @Test public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, null, this.refreshToken)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("accessToken cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, null, this.refreshToken)) + .withMessage("accessToken cannot be null"); } @Test public void constructorWhenRefreshTokenIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, this.accessToken, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("refreshToken cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, this.accessToken, null)) + .withMessage("refreshToken cannot be null"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java index f614700b0f9..7291f83a29e 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java @@ -41,7 +41,7 @@ import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; @@ -179,10 +179,10 @@ public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationExcepti String accessTokenErrorResponse = "{\n" + " \"error\": \"unauthorized_client\"\n" + "}\n"; this.server.enqueue( jsonResponse(accessTokenErrorResponse).setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value())); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block()) - .isInstanceOfSatisfying(OAuth2AuthorizationException.class, - (e) -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client")) - .hasMessageContaining("unauthorized_client"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block()) + .satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("unauthorized_client")) + .withMessageContaining("unauthorized_client"); } // gh-5594 @@ -191,8 +191,9 @@ public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationE String accessTokenErrorResponse = "{}"; this.server.enqueue( jsonResponse(accessTokenErrorResponse).setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value())); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block()) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("server_error"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block()) + .withMessageContaining("server_error"); } @Test @@ -200,8 +201,9 @@ public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAu String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n" + " \"token_type\": \"not-bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n"; this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block()) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("invalid_token_response"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block()) + .withMessageContaining("invalid_token_response"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClientTests.java index 7e47b195338..85de9ebff86 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClientTests.java @@ -34,7 +34,7 @@ import org.springframework.web.reactive.function.client.WebClientResponseException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; @@ -134,11 +134,11 @@ public void getTokenResponseWhenInvalidResponse() throws WebClientResponseExcept ClientRegistration registration = this.clientRegistration.build(); enqueueUnexpectedResponse(); OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration); - assertThatThrownBy(() -> this.client.getTokenResponse(request).block()) - .isInstanceOfSatisfying(OAuth2AuthorizationException.class, - (e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response")) - .hasMessageContaining("[invalid_token_response]") - .hasMessageContaining("Empty OAuth 2.0 Access Token Response"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.client.getTokenResponse(request).block()) + .satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response")) + .withMessageContaining("[invalid_token_response]") + .withMessageContaining("Empty OAuth 2.0 Access Token Response"); } private void enqueueUnexpectedResponse() { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactivePasswordTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactivePasswordTokenResponseClientTests.java index a48a48505ce..07eb3bf3b69 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactivePasswordTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactivePasswordTokenResponseClientTests.java @@ -36,7 +36,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link WebClientReactivePasswordTokenResponseClient}. @@ -70,14 +71,12 @@ public void cleanup() throws Exception { @Test public void setWebClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.setWebClient(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setWebClient(null)); } @Test public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block()); } @Test @@ -134,12 +133,12 @@ public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAu this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest( this.clientRegistrationBuilder.build(), this.username, this.password); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block()) - .isInstanceOfSatisfying(OAuth2AuthorizationException.class, - (e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response")) - .hasMessageContaining("[invalid_token_response]") - .hasMessageContaining("An error occurred parsing the Access Token response") - .hasCauseInstanceOf(Throwable.class); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block()) + .satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response")) + .withMessageContaining("[invalid_token_response]") + .withMessageContaining("An error occurred parsing the Access Token response") + .withCauseInstanceOf(Throwable.class); } @Test @@ -164,10 +163,10 @@ public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationExcepti this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400)); OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest( this.clientRegistrationBuilder.build(), this.username, this.password); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block()) - .isInstanceOfSatisfying(OAuth2AuthorizationException.class, - (e) -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client")) - .hasMessageContaining("[unauthorized_client]"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block()) + .satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("unauthorized_client")) + .withMessageContaining("[unauthorized_client]"); } @Test @@ -175,11 +174,11 @@ public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationE this.server.enqueue(new MockResponse().setResponseCode(500)); OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest( this.clientRegistrationBuilder.build(), this.username, this.password); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block()) - .isInstanceOfSatisfying(OAuth2AuthorizationException.class, - (e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response")) - .hasMessageContaining("[invalid_token_response]") - .hasMessageContaining("Empty OAuth 2.0 Access Token Response"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block()) + .satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response")) + .withMessageContaining("[invalid_token_response]") + .withMessageContaining("Empty OAuth 2.0 Access Token Response"); } private MockResponse jsonResponse(String json) { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveRefreshTokenTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveRefreshTokenTokenResponseClientTests.java index 47a5cdcd24c..dd9262271bd 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveRefreshTokenTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveRefreshTokenTokenResponseClientTests.java @@ -40,7 +40,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link WebClientReactiveRefreshTokenTokenResponseClient}. @@ -76,14 +77,12 @@ public void cleanup() throws Exception { @Test public void setWebClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.setWebClient(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setWebClient(null)); } @Test public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block()); } @Test @@ -138,10 +137,11 @@ public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAu this.server.enqueue(jsonResponse(accessTokenSuccessResponse)); OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest( this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block()) - .isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("[invalid_token_response]") - .hasMessageContaining("An error occurred parsing the Access Token response") - .hasCauseInstanceOf(Throwable.class); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block()) + .withMessageContaining("[invalid_token_response]") + .withMessageContaining("An error occurred parsing the Access Token response") + .withCauseInstanceOf(Throwable.class); } @Test @@ -167,10 +167,10 @@ public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationExcepti this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400)); OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest( this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block()) - .isInstanceOfSatisfying(OAuth2AuthorizationException.class, - (e) -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client")) - .hasMessageContaining("[unauthorized_client]"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block()) + .satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("unauthorized_client")) + .withMessageContaining("[unauthorized_client]"); } @Test @@ -178,11 +178,11 @@ public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationE this.server.enqueue(new MockResponse().setResponseCode(500)); OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest( this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken); - assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block()) - .isInstanceOfSatisfying(OAuth2AuthorizationException.class, - (e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response")) - .hasMessageContaining("[invalid_token_response]") - .hasMessageContaining("Empty OAuth 2.0 Access Token Response"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block()) + .satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response")) + .withMessageContaining("[invalid_token_response]") + .withMessageContaining("Empty OAuth 2.0 Access Token Response"); } private MockResponse jsonResponse(String json) { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java index 6eeade77ca6..d4c1c909a30 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java @@ -23,7 +23,7 @@ import org.springframework.mock.http.client.MockClientHttpResponse; import org.springframework.security.oauth2.core.OAuth2AuthorizationException; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link OAuth2ErrorResponseErrorHandler}. @@ -39,9 +39,9 @@ public void handleErrorWhenErrorResponseBodyThenHandled() { String errorResponse = "{\n" + " \"error\": \"unauthorized_client\",\n" + " \"error_description\": \"The client is not authorized\"\n" + "}\n"; MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST); - assertThatThrownBy(() -> this.errorHandler.handleError(response)) - .isInstanceOf(OAuth2AuthorizationException.class) - .hasMessage("[unauthorized_client] The client is not authorized"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.errorHandler.handleError(response)) + .withMessage("[unauthorized_client] The client is not authorized"); } @Test @@ -49,9 +49,9 @@ public void handleErrorWhenErrorResponseWwwAuthenticateHeaderThenHandled() { String wwwAuthenticateHeader = "Bearer realm=\"auth-realm\" error=\"insufficient_scope\" error_description=\"The access token expired\""; MockClientHttpResponse response = new MockClientHttpResponse(new byte[0], HttpStatus.BAD_REQUEST); response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticateHeader); - assertThatThrownBy(() -> this.errorHandler.handleError(response)) - .isInstanceOf(OAuth2AuthorizationException.class) - .hasMessage("[insufficient_scope] The access token expired"); + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.errorHandler.handleError(response)) + .withMessage("[insufficient_scope] The access token expired"); } } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java index e47de4a0a4a..5052f98a071 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java @@ -27,7 +27,7 @@ import org.springframework.security.oauth2.core.OAuth2Error; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link OAuth2AuthenticationExceptionMixin}. @@ -68,8 +68,8 @@ public void serializeWhenRequiredAttributesOnlyThenSerializes() throws Exception @Test public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() { String json = asJson(new OAuth2AuthenticationException(new OAuth2Error("[authorization_request_not_found]"))); - assertThatThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthenticationException.class)) - .isInstanceOf(JsonProcessingException.class); + assertThatExceptionOfType(JsonProcessingException.class) + .isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthenticationException.class)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java index ad7e4f57524..e394254109a 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java @@ -48,7 +48,7 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link OAuth2AuthenticationTokenMixin}. @@ -95,8 +95,8 @@ public void serializeWhenRequiredAttributesOnlyThenSerializes() throws Exception public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() { OAuth2AuthenticationToken authentication = TestOAuth2AuthenticationTokens.oidcAuthenticated(); String json = asJson(authentication); - assertThatThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthenticationToken.class)) - .isInstanceOf(JsonProcessingException.class); + assertThatExceptionOfType(JsonProcessingException.class) + .isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthenticationToken.class)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java index 326a56c3fa7..569e584349b 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java @@ -34,7 +34,7 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link OAuth2AuthorizationRequestMixin}. @@ -79,8 +79,8 @@ public void serializeWhenRequiredAttributesOnlyThenSerializes() throws Exception @Test public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() { String json = asJson(this.authorizationRequestBuilder.build()); - assertThatThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthorizationRequest.class)) - .isInstanceOf(JsonProcessingException.class); + assertThatExceptionOfType(JsonProcessingException.class) + .isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthorizationRequest.class)); } @Test @@ -128,8 +128,9 @@ public void deserializeWhenRequiredAttributesOnlyThenDeserializes() throws Excep public void deserializeWhenInvalidAuthorizationGrantTypeThenThrowJsonParseException() { OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestBuilder.build(); String json = asJson(authorizationRequest).replace("authorization_code", "client_credentials"); - assertThatThrownBy(() -> this.mapper.readValue(json, OAuth2AuthorizationRequest.class)) - .isInstanceOf(JsonParseException.class).hasMessageContaining("Invalid authorizationGrantType"); + assertThatExceptionOfType(JsonParseException.class) + .isThrownBy(() -> this.mapper.readValue(json, OAuth2AuthorizationRequest.class)) + .withMessageContaining("Invalid authorizationGrantType"); } private static String asJson(OAuth2AuthorizationRequest authorizationRequest) { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java index b829abc6517..02b40783d04 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java @@ -40,7 +40,7 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link OAuth2AuthorizedClientMixin}. @@ -99,8 +99,8 @@ public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(), this.principalName, this.accessToken); String json = asJson(authorizedClient); - assertThatThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthorizedClient.class)) - .isInstanceOf(JsonProcessingException.class); + assertThatExceptionOfType(JsonProcessingException.class) + .isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthorizedClient.class)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java index cd1157c53b1..09134357951 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java @@ -66,8 +66,8 @@ import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.anyCollection; import static org.mockito.BDDMockito.given; @@ -113,25 +113,27 @@ public void setup() { @Test public void constructorWhenNullAccessTokenResponseClientThenIllegalArgumentException() { this.accessTokenResponseClient = null; - assertThatThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient, - this.userService)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient, + this.userService)); } @Test public void constructorWhenNullUserServiceThenIllegalArgumentException() { this.userService = null; - assertThatThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient, - this.userService)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient, + this.userService)); } @Test public void setJwtDecoderFactoryWhenNullThenIllegalArgumentException() { - assertThatThrownBy(() -> this.manager.setJwtDecoderFactory(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setJwtDecoderFactory(null)); } @Test public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.manager.setAuthoritiesMapper(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setAuthoritiesMapper(null)); } @Test @@ -139,8 +141,8 @@ public void authenticateWhenNoSubscriptionThenDoesNothing() { // we didn't do anything because it should cause a ClassCastException (as verified // below) TestingAuthenticationToken token = new TestingAuthenticationToken("a", "b"); - assertThatCode(() -> this.manager.authenticate(token)).doesNotThrowAnyException(); - assertThatThrownBy(() -> this.manager.authenticate(token).block()).isInstanceOf(Throwable.class); + this.manager.authenticate(token); + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> this.manager.authenticate(token).block()); } @Test @@ -152,15 +154,15 @@ public void authenticationWhenNotOidcThenEmpty() { @Test public void authenticationWhenErrorThenOAuth2AuthenticationException() { this.authorizationResponseBldr = OAuth2AuthorizationResponse.error("error").state("state"); - assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block()) - .isInstanceOf(OAuth2AuthenticationException.class); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.manager.authenticate(loginToken()).block()); } @Test public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() { this.authorizationResponseBldr.state("notmatch"); - assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block()) - .isInstanceOf(OAuth2AuthenticationException.class); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.manager.authenticate(loginToken()).block()); } @Test @@ -172,9 +174,9 @@ public void authenticateWhenIdTokenValidationErrorThenOAuth2AuthenticationExcept given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); given(this.jwtDecoder.decode(any())).willThrow(new JwtException("ID Token Validation Error")); this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder); - assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block()) - .isInstanceOf(OAuth2AuthenticationException.class) - .hasMessageContaining("[invalid_id_token] ID Token Validation Error"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.manager.authenticate(loginToken()).block()) + .withMessageContaining("[invalid_id_token] ID Token Validation Error"); } @Test @@ -193,8 +195,9 @@ public void authenticateWhenIdTokenInvalidNonceThenOAuth2AuthenticationException given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken)); this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder); - assertThatThrownBy(() -> this.manager.authenticate(authorizationCodeAuthentication).block()) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("[invalid_nonce]"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.manager.authenticate(authorizationCodeAuthentication).block()) + .withMessageContaining("[invalid_nonce]"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java index c74a5fc23e6..224d49fe71e 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java @@ -36,7 +36,8 @@ import org.springframework.security.oauth2.jwt.Jwt; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.same; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -76,33 +77,30 @@ public void createDefaultClaimTypeConvertersWhenCalledThenDefaultsAreCorrect() { @Test public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null)); } @Test public void setJwsAlgorithmResolverWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null)); } @Test public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null)); } @Test public void createDecoderWhenClientRegistrationNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null)); } @Test public void createDecoderWhenJwsAlgorithmDefaultAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() { - assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build())) - .isInstanceOf(OAuth2AuthenticationException.class) - .hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build())) + .withMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + "for Client Registration: 'registration-id'. " + "Check to ensure you have configured the JwkSet URI."); } @@ -110,9 +108,9 @@ public void createDecoderWhenJwsAlgorithmDefaultAndJwkSetUriEmptyThenThrowOAuth2 @Test public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() { this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> SignatureAlgorithm.ES256); - assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build())) - .isInstanceOf(OAuth2AuthenticationException.class) - .hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build())) + .withMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + "for Client Registration: 'registration-id'. " + "Check to ensure you have configured the JwkSet URI."); } @@ -120,9 +118,10 @@ public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2Authe @Test public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() { this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> MacAlgorithm.HS256); - assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build())) - .isInstanceOf(OAuth2AuthenticationException.class) - .hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy( + () -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build())) + .withMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + "for Client Registration: 'registration-id'. " + "Check to ensure you have configured the client secret."); } @@ -130,9 +129,9 @@ public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2A @Test public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() { this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> null); - assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build())) - .isInstanceOf(OAuth2AuthenticationException.class) - .hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build())) + .withMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + "for Client Registration: 'registration-id'. " + "Check to ensure you have configured a valid JWS Algorithm: 'null'"); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenValidatorTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenValidatorTests.java index 9c6aa401eca..f0a555b4ba5 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenValidatorTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenValidatorTests.java @@ -35,7 +35,7 @@ import org.springframework.security.oauth2.jwt.Jwt; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch @@ -72,20 +72,19 @@ public void validateWhenValidThenNoErrors() { @Test public void setClockSkewWhenNullThenThrowIllegalArgumentException() { OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build()); - assertThatThrownBy(() -> idTokenValidator.setClockSkew(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> idTokenValidator.setClockSkew(null)); } @Test public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() { OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build()); - assertThatThrownBy(() -> idTokenValidator.setClockSkew(Duration.ofSeconds(-1))) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> idTokenValidator.setClockSkew(Duration.ofSeconds(-1))); } @Test public void setClockWhenNullThenThrowIllegalArgumentException() { OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build()); - assertThatThrownBy(() -> idTokenValidator.setClock(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> idTokenValidator.setClock(null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java index 10a57382c15..736866d4d9f 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java @@ -36,7 +36,8 @@ import org.springframework.security.oauth2.jwt.Jwt; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.same; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -76,33 +77,30 @@ public void createDefaultClaimTypeConvertersWhenCalledThenDefaultsAreCorrect() { @Test public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null)); } @Test public void setJwsAlgorithmResolverWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null)); } @Test public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null)); } @Test public void createDecoderWhenClientRegistrationNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null)); } @Test public void createDecoderWhenJwsAlgorithmDefaultAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() { - assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build())) - .isInstanceOf(OAuth2AuthenticationException.class) - .hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build())) + .withMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + "for Client Registration: 'registration-id'. " + "Check to ensure you have configured the JwkSet URI."); } @@ -110,9 +108,9 @@ public void createDecoderWhenJwsAlgorithmDefaultAndJwkSetUriEmptyThenThrowOAuth2 @Test public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() { this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> SignatureAlgorithm.ES256); - assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build())) - .isInstanceOf(OAuth2AuthenticationException.class) - .hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build())) + .withMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + "for Client Registration: 'registration-id'. " + "Check to ensure you have configured the JwkSet URI."); } @@ -120,9 +118,10 @@ public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2Authe @Test public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() { this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> MacAlgorithm.HS256); - assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build())) - .isInstanceOf(OAuth2AuthenticationException.class) - .hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy( + () -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build())) + .withMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + "for Client Registration: 'registration-id'. " + "Check to ensure you have configured the client secret."); } @@ -130,9 +129,9 @@ public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2A @Test public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() { this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> null); - assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build())) - .isInstanceOf(OAuth2AuthenticationException.class) - .hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build())) + .withMessage("[missing_signature_verifier] Failed to find a Signature Verifier " + "for Client Registration: 'registration-id'. " + "Check to ensure you have configured a valid JWS Algorithm: 'null'"); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java index 0289684cc6f..e41eafe7001 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java @@ -53,8 +53,8 @@ import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.same; import static org.mockito.BDDMockito.given; @@ -97,8 +97,7 @@ public void createDefaultClaimTypeConvertersWhenCalledThenDefaultsAreCorrect() { @Test public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.userService.setClaimTypeConverterFactory(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setClaimTypeConverterFactory(null)); } @Test @@ -120,8 +119,8 @@ public void loadUserWhenOAuth2UserSubjectNullThenOAuth2AuthenticationException() OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user"); given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User)); - assertThatCode(() -> this.userService.loadUser(userRequest()).block()) - .isInstanceOf(OAuth2AuthenticationException.class); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.userService.loadUser(userRequest()).block()); } @Test @@ -132,8 +131,8 @@ public void loadUserWhenOAuth2UserSubjectNotEqualThenOAuth2AuthenticationExcepti OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes, "user"); given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User)); - assertThatCode(() -> this.userService.loadUser(userRequest()).block()) - .isInstanceOf(OAuth2AuthenticationException.class); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.userService.loadUser(userRequest()).block()); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestTests.java index 412a1ed786b..af20f2c911b 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestTests.java @@ -32,7 +32,7 @@ import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OidcUserRequest}. @@ -62,20 +62,20 @@ public void setUp() { @Test public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OidcUserRequest(null, this.accessToken, this.idToken)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OidcUserRequest(null, this.accessToken, this.idToken)); } @Test public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OidcUserRequest(this.clientRegistration, null, this.idToken)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OidcUserRequest(this.clientRegistration, null, this.idToken)); } @Test public void constructorWhenIdTokenIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OidcUserRequest(this.clientRegistration, this.accessToken, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OidcUserRequest(this.clientRegistration, this.accessToken, null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java index 73b0e8c68b5..602cf47e32f 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java @@ -56,7 +56,7 @@ import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.ArgumentMatchers.same; import static org.mockito.BDDMockito.given; @@ -113,20 +113,17 @@ public void createDefaultClaimTypeConvertersWhenCalledThenDefaultsAreCorrect() { @Test public void setOauth2UserServiceWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.userService.setOauth2UserService(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setOauth2UserService(null)); } @Test public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.userService.setClaimTypeConverterFactory(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setClaimTypeConverterFactory(null)); } @Test public void setAccessibleScopesWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.userService.setAccessibleScopes(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setAccessibleScopes(null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandlerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandlerTests.java index a72c9059d69..f1b461e556e 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandlerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandlerTests.java @@ -40,7 +40,7 @@ import org.springframework.security.oauth2.core.user.TestOAuth2Users; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -137,14 +137,12 @@ public void logoutWhenUsingPostLogoutRedirectUriTemplateThenBuildsItForRedirect( @Test public void setPostLogoutRedirectUriWhenGivenNullThenThrowsException() { - assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null)); } @Test public void setPostLogoutRedirectUriTemplateWhenGivenNullThenThrowsException() { - assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null)); } } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java index b0465c0dc65..ba32753428f 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java @@ -42,7 +42,7 @@ import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -149,14 +149,12 @@ public void logoutWhenUsingPostLogoutRedirectUriTemplateThenBuildsItForRedirect( @Test public void setPostLogoutRedirectUriWhenGivenNullThenThrowsException() { - assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null)); } @Test public void setPostLogoutRedirectUriTemplateWhenGivenNullThenThrowsException() { - assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null)); } private String redirectedUrl(ServerWebExchange exchange) { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java index f419a9c07f0..e2d37065be6 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java @@ -30,7 +30,7 @@ import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ClientRegistration}. @@ -364,18 +364,17 @@ public void buildWhenClientCredentialsGrantAllAttributesProvidedThenAllAttribute @Test public void buildWhenClientCredentialsGrantRegistrationIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> ClientRegistration.withRegistrationId(null).clientId(CLIENT_ID) - .clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) - .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(TOKEN_URI).build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> ClientRegistration.withRegistrationId(null).clientId(CLIENT_ID) + .clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) + .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(TOKEN_URI).build()); } @Test public void buildWhenClientCredentialsGrantClientIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(null) - .clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) - .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(TOKEN_URI).build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID) + .clientId(null).clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) + .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(TOKEN_URI).build()); } @Test @@ -396,23 +395,23 @@ public void buildWhenClientCredentialsGrantClientAuthenticationMethodNotProvided @Test public void buildWhenClientCredentialsGrantTokenUriIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(CLIENT_ID) - .clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) - .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(null).build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(CLIENT_ID) + .clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) + .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(null).build()); } // gh-6256 @Test public void buildWhenScopesContainASpaceThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> TestClientRegistrations.clientCredentials().scope("openid profile email").build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> TestClientRegistrations.clientCredentials().scope("openid profile email").build()); } @Test public void buildWhenScopesContainAnInvalidCharacterThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> TestClientRegistrations.clientCredentials().scope("an\"invalid\"scope").build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> TestClientRegistrations.clientCredentials().scope("an\"invalid\"scope").build()); } @Test @@ -433,18 +432,17 @@ public void buildWhenPasswordGrantAllAttributesProvidedThenAllAttributesAreSet() @Test public void buildWhenPasswordGrantRegistrationIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> ClientRegistration.withRegistrationId(null).clientId(CLIENT_ID) - .clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) - .authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(TOKEN_URI).build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> ClientRegistration.withRegistrationId(null).clientId(CLIENT_ID) + .clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) + .authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(TOKEN_URI).build()); } @Test public void buildWhenPasswordGrantClientIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(null) - .clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) - .authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(TOKEN_URI).build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID) + .clientId(null).clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) + .authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(TOKEN_URI).build()); } @Test @@ -465,10 +463,10 @@ public void buildWhenPasswordGrantClientAuthenticationMethodNotProvidedThenDefau @Test public void buildWhenPasswordGrantTokenUriIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(CLIENT_ID) - .clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) - .authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(null).build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(CLIENT_ID) + .clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) + .authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(null).build()); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java index 4fa404c5e67..9510deb6d07 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java @@ -35,7 +35,8 @@ import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * @author Rob Winch @@ -142,17 +143,16 @@ private void assertIssuerMetadata(ClientRegistration registration, ClientRegistr @Test public void issuerWhenResponseMissingJwksUriThenThrowsIllegalArgumentException() throws Exception { this.response.remove("jwks_uri"); - assertThatThrownBy(() -> registration("").build()).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("The public JWK set URI must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> registration("").build()) + .withMessageContaining("The public JWK set URI must not be null"); } // gh-7512 @Test public void issuerWhenOidcFallbackResponseMissingJwksUriThenThrowsIllegalArgumentException() throws Exception { this.response.remove("jwks_uri"); - assertThatThrownBy(() -> registrationOidcFallback("issuer1", null).build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("The public JWK set URI must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> registrationOidcFallback("issuer1", null).build()) + .withMessageContaining("The public JWK set URI must not be null"); } // gh-7512 @@ -239,16 +239,16 @@ public void issuerWhenOAuth2GrantTypesSupportedNullThenDefaulted() throws Except @Test public void issuerWhenGrantTypesSupportedInvalidThenException() { this.response.put("grant_types_supported", Arrays.asList("implicit")); - assertThatThrownBy(() -> registration("")).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \"" + assertThatIllegalArgumentException().isThrownBy(() -> registration("")) + .withMessageContaining("Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \"" + this.issuer + "\" returned a configuration of [implicit]"); } @Test public void issuerWhenOAuth2GrantTypesSupportedInvalidThenException() { this.response.put("grant_types_supported", Arrays.asList("implicit")); - assertThatThrownBy(() -> registrationOAuth2("", null)).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \"" + assertThatIllegalArgumentException().isThrownBy(() -> registrationOAuth2("", null)) + .withMessageContaining("Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \"" + this.issuer + "\" returned a configuration of [implicit]"); } @@ -301,30 +301,31 @@ public void issuerWhenOAuth2TokenEndpointAuthMethodsNoneThenMethodIsNone() throw @Test public void issuerWhenTokenEndpointAuthMethodsInvalidThenException() { this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("tls_client_auth")); - assertThatThrownBy(() -> registration("")).isInstanceOf(IllegalArgumentException.class).hasMessageContaining( - "Only ClientAuthenticationMethod.BASIC, ClientAuthenticationMethod.POST and ClientAuthenticationMethod.NONE are supported. The issuer \"" - + this.issuer + "\" returned a configuration of [tls_client_auth]"); + assertThatIllegalArgumentException().isThrownBy(() -> registration("")) + .withMessageContaining("Only ClientAuthenticationMethod.BASIC, ClientAuthenticationMethod.POST and " + + "ClientAuthenticationMethod.NONE are supported. The issuer \"" + this.issuer + + "\" returned a configuration of [tls_client_auth]"); } @Test public void issuerWhenOAuth2TokenEndpointAuthMethodsInvalidThenException() { this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("tls_client_auth")); - assertThatThrownBy(() -> registrationOAuth2("", null)).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining( - "Only ClientAuthenticationMethod.BASIC, ClientAuthenticationMethod.POST and ClientAuthenticationMethod.NONE are supported. The issuer \"" - + this.issuer + "\" returned a configuration of [tls_client_auth]"); + assertThatIllegalArgumentException().isThrownBy(() -> registrationOAuth2("", null)) + .withMessageContaining("Only ClientAuthenticationMethod.BASIC, ClientAuthenticationMethod.POST and " + + "ClientAuthenticationMethod.NONE are supported. The issuer \"" + this.issuer + + "\" returned a configuration of [tls_client_auth]"); } @Test public void issuerWhenOAuth2EmptyStringThenMeaningfulErrorMessage() { - assertThatThrownBy(() -> ClientRegistrations.fromIssuerLocation("")) - .hasMessageContaining("issuer cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistrations.fromIssuerLocation("")) + .withMessageContaining("issuer cannot be empty"); } @Test public void issuerWhenEmptyStringThenMeaningfulErrorMessage() { - assertThatThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation("")) - .hasMessageContaining("issuer cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation("")) + .withMessageContaining("issuer cannot be empty"); } @Test @@ -334,9 +335,9 @@ public void issuerWhenOpenIdConfigurationDoesNotMatchThenMeaningfulErrorMessage( MockResponse mockResponse = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); - assertThatThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation(this.issuer)).hasMessageContaining( - "The Issuer \"https://example.com\" provided in the configuration metadata did not match the requested issuer \"" - + this.issuer + "\""); + assertThatIllegalStateException().isThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation(this.issuer)) + .withMessageContaining("The Issuer \"https://example.com\" provided in the configuration metadata did " + + "not match the requested issuer \"" + this.issuer + "\""); } @Test @@ -346,9 +347,9 @@ public void issuerWhenOAuth2ConfigurationDoesNotMatchThenMeaningfulErrorMessage( MockResponse mockResponse = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); this.server.enqueue(mockResponse); - assertThatThrownBy(() -> ClientRegistrations.fromIssuerLocation(this.issuer)).hasMessageContaining( - "The Issuer \"https://example.com\" provided in the configuration metadata did not match the requested issuer \"" - + this.issuer + "\""); + assertThatIllegalStateException().isThrownBy(() -> ClientRegistrations.fromIssuerLocation(this.issuer)) + .withMessageContaining("The Issuer \"https://example.com\" provided in the configuration metadata " + + "did not match the requested issuer \"" + this.issuer + "\""); } private ClientRegistration.Builder registration(String path) throws Exception { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/InMemoryReactiveClientRegistrationRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/InMemoryReactiveClientRegistrationRepositoryTests.java index 92fccfc27fa..9f82055804d 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/InMemoryReactiveClientRegistrationRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/InMemoryReactiveClientRegistrationRepositoryTests.java @@ -24,7 +24,7 @@ import reactor.test.StepVerifier; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch @@ -43,22 +43,21 @@ public void setup() { @Test public void constructorWhenZeroVarArgsThenIllegalArgumentException() { - assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository()); } @Test public void constructorWhenClientRegistrationArrayThenIllegalArgumentException() { ClientRegistration[] registrations = null; - assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations)); } @Test public void constructorWhenClientRegistrationListThenIllegalArgumentException() { List registrations = null; - assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations)); } @Test(expected = IllegalStateException.class) @@ -70,8 +69,8 @@ public void constructorListClientRegistrationWhenDuplicateIdThenIllegalArgumentE @Test public void constructorWhenClientRegistrationIsNullThenIllegalArgumentException() { ClientRegistration registration = null; - assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registration)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registration)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java index fec781af6f4..01909971011 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java @@ -51,7 +51,7 @@ import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -95,7 +95,7 @@ public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() { @Test public void loadUserWhenUserInfoUriIsNullThenThrowOAuth2AuthenticationException() { this.clientRegistration.userInfoUri(null); - StepVerifier.create(this.userService.loadUser(oauth2UserRequest())).expectErrorSatisfies((t) -> assertThat(t) + StepVerifier.create(this.userService.loadUser(oauth2UserRequest())).expectErrorSatisfies((ex) -> assertThat(ex) .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("missing_user_info_uri")) .verify(); } @@ -103,7 +103,7 @@ public void loadUserWhenUserInfoUriIsNullThenThrowOAuth2AuthenticationException( @Test public void loadUserWhenUserNameAttributeNameIsNullThenThrowOAuth2AuthenticationException() { this.clientRegistration.userNameAttributeName(null); - StepVerifier.create(this.userService.loadUser(oauth2UserRequest())).expectErrorSatisfies((t) -> assertThat(t) + StepVerifier.create(this.userService.loadUser(oauth2UserRequest())).expectErrorSatisfies((ex) -> assertThat(ex) .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("missing_user_name_attribute")) .verify(); } @@ -169,23 +169,25 @@ public void loadUserWhenUserInfoSuccessResponseInvalidThenThrowOAuth2Authenticat + " \"address\": \"address\",\n" + " \"email\": \"user1@example.com\"\n"; // "}\n"; // Make the JSON invalid/malformed enqueueApplicationJsonBody(userInfoResponse); - assertThatThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block()) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("invalid_user_info_response"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block()) + .withMessageContaining("invalid_user_info_response"); } @Test public void loadUserWhenUserInfoErrorResponseThenThrowOAuth2AuthenticationException() { this.server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .setResponseCode(500).setBody("{}")); - assertThatThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block()) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("invalid_user_info_response"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block()) + .withMessageContaining("invalid_user_info_response"); } @Test public void loadUserWhenUserInfoUriInvalidThenThrowAuthenticationServiceException() { this.clientRegistration.userInfoUri("https://invalid-provider.com/user"); - assertThatThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block()) - .isInstanceOf(AuthenticationServiceException.class); + assertThatExceptionOfType(AuthenticationServiceException.class) + .isThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block()); } @Test @@ -224,11 +226,11 @@ public void loadUserWhenUserInfoSuccessResponseInvalidContentTypeThenThrowOAuth2 response.setBody("invalid content type"); this.server.enqueue(response); OAuth2UserRequest userRequest = oauth2UserRequest(); - assertThatThrownBy(() -> this.userService.loadUser(userRequest).block()) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining( - "[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource from '" - + userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint() - .getUri() + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.userService.loadUser(userRequest).block()).withMessageContaining( + "[invalid_user_info_response] An error occurred while attempting to " + + "retrieve the UserInfo Resource from '" + userRequest.getClientRegistration() + .getProviderDetails().getUserInfoEndpoint().getUri() + "': " + "response contains invalid content type 'text/plain'"); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestTests.java index 85b13b8d83f..c6fa99ae3e8 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestTests.java @@ -31,7 +31,7 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2UserRequest}. @@ -63,14 +63,12 @@ public void setUp() { @Test public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2UserRequest(null, this.accessToken)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2UserRequest(null, this.accessToken)); } @Test public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2UserRequest(this.clientRegistration, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2UserRequest(this.clientRegistration, null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepositoryTests.java index 3266a7d6535..88e7c57adec 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepositoryTests.java @@ -28,7 +28,7 @@ import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -67,14 +67,14 @@ public void setup() { @Test public void constructorWhenAuthorizedClientServiceIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(null)); } @Test public void setAuthorizedClientRepositoryWhenAuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientRepository.setAnonymousAuthorizedClientRepository(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientRepository.setAnonymousAuthorizedClientRepository(null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolverTests.java index ddcc33cc297..0c2e2b70f98 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolverTests.java @@ -41,7 +41,7 @@ import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.entry; /** @@ -86,20 +86,19 @@ public void setUp() { @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new DefaultOAuth2AuthorizationRequestResolver(null, this.authorizationRequestBaseUri)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> new DefaultOAuth2AuthorizationRequestResolver(null, this.authorizationRequestBaseUri)); } @Test public void constructorWhenAuthorizationRequestBaseUriIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, null)); } @Test public void setAuthorizationRequestCustomizerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.resolver.setAuthorizationRequestCustomizer(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.resolver.setAuthorizationRequestCustomizer(null)); } @Test @@ -135,9 +134,8 @@ public void resolveWhenAuthorizationRequestWithInvalidClientThenThrowIllegalArgu + "-invalid"; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); request.setServletPath(requestUri); - assertThatThrownBy(() -> this.resolver.resolve(request)).isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "Invalid Client Registration with Id: " + clientRegistration.getRegistrationId() + "-invalid"); + assertThatIllegalArgumentException().isThrownBy(() -> this.resolver.resolve(request)).withMessage( + "Invalid Client Registration with Id: " + clientRegistration.getRegistrationId() + "-invalid"); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java index 4610f688c2a..565795fb684 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java @@ -50,8 +50,8 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.BDDMockito.given; @@ -133,44 +133,50 @@ public void onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Auth @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new DefaultOAuth2AuthorizedClientManager(null, this.authorizedClientRepository)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationRepository cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DefaultOAuth2AuthorizedClientManager(null, this.authorizedClientRepository)) + .withMessage("clientRegistrationRepository cannot be null"); } @Test public void constructorWhenOAuth2AuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClientRepository cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null)) + .withMessage("authorizedClientRepository cannot be null"); } @Test public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClientProvider cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null)) + .withMessage("authorizedClientProvider cannot be null"); } @Test public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("contextAttributesMapper cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null)) + .withMessage("contextAttributesMapper cannot be null"); } @Test public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationSuccessHandler cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null)) + .withMessage("authorizationSuccessHandler cannot be null"); } @Test public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationFailureHandler cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null)) + .withMessage("authorizationFailureHandler cannot be null"); } @Test public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.authorize(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizeRequest cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null)) + .withMessage("authorizeRequest cannot be null"); } @Test @@ -178,8 +184,8 @@ public void authorizeWhenHttpServletRequestIsNullThenThrowIllegalArgumentExcepti OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) .build(); - assertThatThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("servletRequest cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest)) + .withMessage("servletRequest cannot be null"); } @Test @@ -187,8 +193,8 @@ public void authorizeWhenHttpServletResponseIsNullThenThrowIllegalArgumentExcept OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) .attribute(HttpServletRequest.class.getName(), this.request).build(); - assertThatThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("servletResponse cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest)) + .withMessage("servletResponse cannot be null"); } @Test @@ -198,9 +204,8 @@ public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentExcep attrs.put(HttpServletRequest.class.getName(), this.request); attrs.put(HttpServletResponse.class.getName(), this.response); }).build(); - assertThatThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Could not find ClientRegistration with id 'invalid-registration-id'"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest)) + .withMessage("Could not find ClientRegistration with id 'invalid-registration-id'"); } @SuppressWarnings("unchecked") @@ -401,7 +406,8 @@ public void reauthorizeWhenErrorCodeMatchThenRemoveAuthorizedClient() { attrs.put(HttpServletRequest.class.getName(), this.request); attrs.put(HttpServletResponse.class.getName(), this.response); }).build(); - assertThatCode(() -> this.authorizedClientManager.authorize(reauthorizeRequest)) + assertThatExceptionOfType(ClientAuthorizationException.class) + .isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest)) .isEqualTo(authorizationException); verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal), any()); @@ -420,7 +426,8 @@ public void reauthorizeWhenErrorCodeDoesNotMatchThenDoNotRemoveAuthorizedClient( attrs.put(HttpServletRequest.class.getName(), this.request); attrs.put(HttpServletResponse.class.getName(), this.response); }).build(); - assertThatCode(() -> this.authorizedClientManager.authorize(reauthorizeRequest)) + assertThatExceptionOfType(ClientAuthorizationException.class) + .isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest)) .isEqualTo(authorizationException); verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal), any()); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManagerTests.java index a80ca4ee9d9..b41e196ba80 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManagerTests.java @@ -51,8 +51,8 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -131,48 +131,52 @@ public void setup() { @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( - () -> new DefaultReactiveOAuth2AuthorizedClientManager(null, this.authorizedClientRepository)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("clientRegistrationRepository cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new DefaultReactiveOAuth2AuthorizedClientManager(null, this.authorizedClientRepository)) + .withMessage("clientRegistrationRepository cannot be null"); } @Test public void constructorWhenOAuth2AuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( - () -> new DefaultReactiveOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("authorizedClientRepository cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new DefaultReactiveOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null)) + .withMessage("authorizedClientRepository cannot be null"); } @Test public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClientProvider cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null)) + .withMessage("authorizedClientProvider cannot be null"); } @Test public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationSuccessHandler cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null)) + .withMessage("authorizationSuccessHandler cannot be null"); } @Test public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationFailureHandler cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null)) + .withMessage("authorizationFailureHandler cannot be null"); } @Test public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("contextAttributesMapper cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null)) + .withMessage("contextAttributesMapper cannot be null"); } @Test public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientManager.authorize(null).block()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("authorizeRequest cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null).block()) + .withMessage("authorizeRequest cannot be null"); } @Test @@ -180,18 +184,18 @@ public void authorizeWhenExchangeIsNullThenThrowIllegalArgumentException() { OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) .build(); - assertThatThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("serverWebExchange cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()) + .withMessage("serverWebExchange cannot be null"); } @Test public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() { OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId("invalid-registration-id").principal(this.principal).build(); - assertThatThrownBy( + assertThatIllegalArgumentException().isThrownBy( () -> this.authorizedClientManager.authorize(authorizeRequest).subscriberContext(this.context).block()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Could not find ClientRegistration with id 'invalid-registration-id'"); + .withMessage("Could not find ClientRegistration with id 'invalid-registration-id'"); } @SuppressWarnings("unchecked") @@ -280,9 +284,9 @@ public void authorizeWhenInvalidTokenThenRemoveAuthorizedClient() { this.clientRegistration.getRegistrationId()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); - assertThatCode( + assertThatExceptionOfType(ClientAuthorizationException.class).isThrownBy( () -> this.authorizedClientManager.authorize(authorizeRequest).subscriberContext(this.context).block()) - .isEqualTo(exception); + .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); @@ -308,9 +312,9 @@ public void authorizeWhenInvalidGrantThenRemoveAuthorizedClient() { this.clientRegistration.getRegistrationId()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); - assertThatCode( + assertThatExceptionOfType(ClientAuthorizationException.class).isThrownBy( () -> this.authorizedClientManager.authorize(authorizeRequest).subscriberContext(this.context).block()) - .isEqualTo(exception); + .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); @@ -336,9 +340,9 @@ public void authorizeWhenServerErrorThenDoNotRemoveAuthorizedClient() { this.clientRegistration.getRegistrationId()); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); - assertThatCode( + assertThatExceptionOfType(ClientAuthorizationException.class).isThrownBy( () -> this.authorizedClientManager.authorize(authorizeRequest).subscriberContext(this.context).block()) - .isEqualTo(exception); + .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); @@ -361,9 +365,9 @@ public void authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedCl new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null)); given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) .willReturn(Mono.error(exception)); - assertThatCode( + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy( () -> this.authorizedClientManager.authorize(authorizeRequest).subscriberContext(this.context).block()) - .isEqualTo(exception); + .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); @@ -389,9 +393,9 @@ public void authorizeWhenOAuth2AuthorizationExceptionAndCustomFailureHandlerThen PublisherProbe authorizationFailureHandlerProbe = PublisherProbe.empty(); this.authorizedClientManager.setAuthorizationFailureHandler( (client, principal, attributes) -> authorizationFailureHandlerProbe.mono()); - assertThatCode( + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy( () -> this.authorizedClientManager.authorize(authorizeRequest).subscriberContext(this.context).block()) - .isEqualTo(exception); + .isEqualTo(exception); verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture()); verify(this.contextAttributesMapper).apply(eq(authorizeRequest)); OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepositoryTests.java index c28af93daa3..ba329f42e94 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepositoryTests.java @@ -30,7 +30,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link HttpSessionOAuth2AuthorizationRequestRepository}. @@ -110,23 +110,23 @@ public void loadAuthorizationRequestWhenSavedAndStateParameterNullThenReturnNull @Test public void saveAuthorizationRequestWhenHttpServletRequestIsNullThenThrowIllegalArgumentException() { OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build(); - assertThatThrownBy(() -> this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, - null, new MockHttpServletResponse())).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizationRequestRepository + .saveAuthorizationRequest(authorizationRequest, null, new MockHttpServletResponse())); } @Test public void saveAuthorizationRequestWhenHttpServletResponseIsNullThenThrowIllegalArgumentException() { OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build(); - assertThatThrownBy(() -> this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, - new MockHttpServletRequest(), null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizationRequestRepository + .saveAuthorizationRequest(authorizationRequest, new MockHttpServletRequest(), null)); } @Test public void saveAuthorizationRequestWhenStateNullThenThrowIllegalArgumentException() { OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().state(null).build(); - assertThatThrownBy(() -> this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, - new MockHttpServletRequest(), new MockHttpServletResponse())) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, + new MockHttpServletRequest(), new MockHttpServletResponse())); } @Test @@ -185,15 +185,14 @@ public void saveAuthorizationRequestWhenNullThenRemoved() { @Test public void removeAuthorizationRequestWhenHttpServletRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizationRequestRepository.removeAuthorizationRequest(null, - new MockHttpServletResponse())).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizationRequestRepository + .removeAuthorizationRequest(null, new MockHttpServletResponse())); } @Test public void removeAuthorizationRequestWhenHttpServletResponseIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizationRequestRepository - .removeAuthorizationRequest(new MockHttpServletRequest(), null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizationRequestRepository + .removeAuthorizationRequest(new MockHttpServletRequest(), null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepositoryTests.java index 7cf152bdbd9..42db8597324 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepositoryTests.java @@ -31,7 +31,7 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -65,8 +65,8 @@ public void setup() { @Test public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientRepository.loadAuthorizedClient(null, null, this.request)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientRepository.loadAuthorizedClient(null, null, this.request)); } @Test @@ -76,8 +76,8 @@ public void loadAuthorizedClientWhenPrincipalNameIsNullThenExceptionNotThrown() @Test public void loadAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientRepository.loadAuthorizedClient(this.registrationId1, null, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientRepository.loadAuthorizedClient(this.registrationId1, null, null)); } @Test @@ -99,9 +99,8 @@ public void loadAuthorizedClientWhenSavedThenReturnAuthorizedClient() { @Test public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( - () -> this.authorizedClientRepository.saveAuthorizedClient(null, null, this.request, this.response)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientRepository.saveAuthorizedClient(null, null, this.request, this.response)); } @Test @@ -115,18 +114,16 @@ public void saveAuthorizedClientWhenAuthenticationIsNullThenExceptionNotThrown() public void saveAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1, mock(OAuth2AccessToken.class)); - assertThatThrownBy( - () -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, null, this.response)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientRepository + .saveAuthorizedClient(authorizedClient, null, null, this.response)); } @Test public void saveAuthorizedClientWhenResponseIsNullThenThrowIllegalArgumentException() { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1, mock(OAuth2AccessToken.class)); - assertThatThrownBy( - () -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, null)); } @Test @@ -146,9 +143,8 @@ public void saveAuthorizedClientWhenSavedThenSavedToSession() { @Test public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( - () -> this.authorizedClientRepository.removeAuthorizedClient(null, null, this.request, this.response)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientRepository.removeAuthorizedClient(null, null, this.request, this.response)); } @Test @@ -158,8 +154,8 @@ public void removeAuthorizedClientWhenPrincipalNameIsNullThenExceptionNotThrown( @Test public void removeAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, - null, this.response)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientRepository + .removeAuthorizedClient(this.registrationId1, null, null, this.response)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java index b77b7439850..20666fa15ee 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java @@ -62,7 +62,7 @@ import org.springframework.util.CollectionUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -121,31 +121,32 @@ public void cleanup() { @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizationCodeGrantFilter(null, this.authorizedClientRepository, - this.authenticationManager)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizationCodeGrantFilter(null, + this.authorizedClientRepository, this.authenticationManager)); } @Test public void constructorWhenAuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizationCodeGrantFilter(this.clientRegistrationRepository, null, - this.authenticationManager)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizationCodeGrantFilter(this.clientRegistrationRepository, null, + this.authenticationManager)); } @Test public void constructorWhenAuthenticationManagerIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizationCodeGrantFilter(this.clientRegistrationRepository, - this.authorizedClientRepository, null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizationCodeGrantFilter(this.clientRegistrationRepository, + this.authorizedClientRepository, null)); } @Test public void setAuthorizationRequestRepositoryWhenAuthorizationRequestRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.filter.setAuthorizationRequestRepository(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthorizationRequestRepository(null)); } @Test public void setRequestCacheWhenRequestCacheIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.filter.setRequestCache(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestCache(null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java index 26020004c65..2827d04e72f 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java @@ -45,7 +45,7 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; @@ -91,31 +91,30 @@ public void setUp() { public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { Constructor constructor = ClassUtils.getConstructorIfAvailable( OAuth2AuthorizationRequestRedirectFilter.class, ClientRegistrationRepository.class); - assertThatThrownBy(() -> constructor.newInstance(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> constructor.newInstance(null)); } @Test public void constructorWhenAuthorizationRequestBaseUriIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository, null)); } @Test public void constructorWhenAuthorizationRequestResolverIsNullThenThrowIllegalArgumentException() { Constructor constructor = ClassUtils.getConstructorIfAvailable( OAuth2AuthorizationRequestRedirectFilter.class, OAuth2AuthorizationRequestResolver.class); - assertThatThrownBy(() -> constructor.newInstance(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> constructor.newInstance(null)); } @Test public void setAuthorizationRequestRepositoryWhenAuthorizationRequestRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.filter.setAuthorizationRequestRepository(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthorizationRequestRepository(null)); } @Test public void setRequestCacheWhenRequestCacheIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.filter.setRequestCache(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestCache(null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java index 2a783cc03ed..3ad39a3877b 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java @@ -59,7 +59,7 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -122,33 +122,34 @@ public void setUp() { @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2LoginAuthenticationFilter(null, this.authorizedClientService)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2LoginAuthenticationFilter(null, this.authorizedClientService)); } @Test public void constructorWhenAuthorizedClientServiceIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository, null)); } @Test public void constructorWhenAuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository, - (OAuth2AuthorizedClientRepository) null, OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository, + (OAuth2AuthorizedClientRepository) null, + OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI)); } @Test public void constructorWhenFilterProcessesUrlIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository, - this.authorizedClientRepository, null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository, + this.authorizedClientRepository, null)); } @Test public void setAuthorizationRequestRepositoryWhenAuthorizationRequestRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.filter.setAuthorizationRequestRepository(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthorizationRequestRepository(null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java index 73cb3d8cff4..7c43ee12607 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java @@ -63,7 +63,9 @@ import org.springframework.web.context.request.ServletWebRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -148,36 +150,37 @@ public void cleanup() { @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null, this.authorizedClientRepository)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null, this.authorizedClientRepository)); } @Test public void constructorWhenOAuth2AuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(this.clientRegistrationRepository, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(this.clientRegistrationRepository, null)); } @Test public void constructorWhenAuthorizedClientManagerIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null)); } @Test public void setClientCredentialsTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.argumentResolver.setClientCredentialsTokenResponseClient(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("clientCredentialsTokenResponseClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.argumentResolver.setClientCredentialsTokenResponseClient(null)) + .withMessage("clientCredentialsTokenResponseClient cannot be null"); } @Test public void setClientCredentialsTokenResponseClientWhenNotDefaultAuthorizedClientManagerThenThrowIllegalStateException() { - assertThatThrownBy(() -> this.argumentResolver - .setClientCredentialsTokenResponseClient(new DefaultClientCredentialsTokenResponseClient())) - .isInstanceOf(IllegalStateException.class).hasMessage( - "The client cannot be set when the constructor used is \"OAuth2AuthorizedClientArgumentResolver(OAuth2AuthorizedClientManager)\". " - + "Instead, use the constructor \"OAuth2AuthorizedClientArgumentResolver(ClientRegistrationRepository, OAuth2AuthorizedClientRepository)\"."); + assertThatIllegalStateException() + .isThrownBy(() -> this.argumentResolver + .setClientCredentialsTokenResponseClient(new DefaultClientCredentialsTokenResponseClient())) + .withMessage("The client cannot be set when the constructor used is " + + "\"OAuth2AuthorizedClientArgumentResolver(OAuth2AuthorizedClientManager)\". " + + "Instead, use the constructor \"OAuth2AuthorizedClientArgumentResolver(ClientRegistrationRepository, " + + "OAuth2AuthorizedClientRepository)\"."); } @Test @@ -210,9 +213,11 @@ public void supportsParameterWhenParameterTypeUnsupportedWithoutAnnotationThenFa @Test public void resolveArgumentWhenRegistrationIdEmptyAndNotOAuth2AuthenticationThenThrowIllegalArgumentException() { MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AuthorizedClient.class); - assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage( - "Unable to resolve the Client Registration Identifier. It must be provided via @RegisteredOAuth2AuthorizedClient(\"client1\") or @RegisteredOAuth2AuthorizedClient(registrationId = \"client1\")."); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null)) + .withMessage("Unable to resolve the Client Registration Identifier. It must be provided via " + + "@RegisteredOAuth2AuthorizedClient(\"client1\") or " + + "@RegisteredOAuth2AuthorizedClient(registrationId = \"client1\")."); } @Test @@ -239,9 +244,10 @@ public void resolveArgumentWhenAuthorizedClientFoundThenResolves() throws Except public void resolveArgumentWhenRegistrationIdInvalidThenThrowIllegalArgumentException() { MethodParameter methodParameter = this.getMethodParameter("registrationIdInvalid", OAuth2AuthorizedClient.class); - assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, - new ServletWebRequest(this.request, this.response), null)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("Could not find ClientRegistration with id 'invalid'"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, + new ServletWebRequest(this.request, this.response), null)) + .withMessage("Could not find ClientRegistration with id 'invalid'"); } @Test @@ -250,9 +256,8 @@ public void resolveArgumentWhenAuthorizedClientNotFoundForAuthorizationCodeClien .willReturn(null); MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class); - assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, - new ServletWebRequest(this.request, this.response), null)) - .isInstanceOf(ClientAuthorizationRequiredException.class); + assertThatExceptionOfType(ClientAuthorizationRequiredException.class).isThrownBy(() -> this.argumentResolver + .resolveArgument(methodParameter, null, new ServletWebRequest(this.request, this.response), null)); } @SuppressWarnings("unchecked") diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java index 4d80f566663..f7599856f42 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java @@ -54,7 +54,7 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -257,8 +257,8 @@ public void requestWhenUnauthorizedThenReAuthorize() { .subscriberContext(Context.of(ServerWebExchange.class, this.exchange)) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); // first try should fail, and remove the cached authorized client - assertThatCode(requestMono::block).isInstanceOfSatisfying(WebClientResponseException.class, - (e) -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED)); + assertThatExceptionOfType(WebClientResponseException.class).isThrownBy(requestMono::block) + .satisfies((ex) -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED)); assertThat(this.server.getRequestCount()).isEqualTo(1); verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any()); verify(this.authorizedClientRepository).removeAuthorizedClient(eq(clientRegistration.getRegistrationId()), diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java index 4f1905c770c..48e4bc29811 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java @@ -96,8 +96,9 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -178,30 +179,31 @@ public void setup() { @Test public void constructorWhenAuthorizedClientManagerIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new ServerOAuth2AuthorizedClientExchangeFilterFunction(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ServerOAuth2AuthorizedClientExchangeFilterFunction(null)); } @Test public void setClientCredentialsTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.function.setClientCredentialsTokenResponseClient(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("clientCredentialsTokenResponseClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.function.setClientCredentialsTokenResponseClient(null)) + .withMessage("clientCredentialsTokenResponseClient cannot be null"); } @Test public void setClientCredentialsTokenResponseClientWhenNotDefaultAuthorizedClientManagerThenThrowIllegalStateException() { - assertThatThrownBy(() -> this.function - .setClientCredentialsTokenResponseClient(new WebClientReactiveClientCredentialsTokenResponseClient())) - .isInstanceOf(IllegalStateException.class).hasMessage( - "The client cannot be set when the constructor used is \"ServerOAuth2AuthorizedClientExchangeFilterFunction(ReactiveOAuth2AuthorizedClientManager)\". " - + "Instead, use the constructor \"ServerOAuth2AuthorizedClientExchangeFilterFunction(ClientRegistrationRepository, OAuth2AuthorizedClientRepository)\"."); + assertThatIllegalStateException() + .isThrownBy(() -> this.function.setClientCredentialsTokenResponseClient( + new WebClientReactiveClientCredentialsTokenResponseClient())) + .withMessage( + "The client cannot be set when the constructor used is \"ServerOAuth2AuthorizedClientExchangeFilterFunction(ReactiveOAuth2AuthorizedClientManager)\". " + + "Instead, use the constructor \"ServerOAuth2AuthorizedClientExchangeFilterFunction(ClientRegistrationRepository, OAuth2AuthorizedClientRepository)\"."); } @Test public void setAccessTokenExpiresSkewWhenNotDefaultAuthorizedClientManagerThenThrowIllegalStateException() { - assertThatThrownBy(() -> this.function.setAccessTokenExpiresSkew(Duration.ofSeconds(30))) - .isInstanceOf(IllegalStateException.class).hasMessage( + assertThatIllegalStateException() + .isThrownBy(() -> this.function.setAccessTokenExpiresSkew(Duration.ofSeconds(30))).withMessage( "The accessTokenExpiresSkew cannot be set when the constructor used is \"ServerOAuth2AuthorizedClientExchangeFilterFunction(ReactiveOAuth2AuthorizedClientManager)\". " + "Instead, use the constructor \"ServerOAuth2AuthorizedClientExchangeFilterFunction(ClientRegistrationRepository, OAuth2AuthorizedClientRepository)\"."); } @@ -405,11 +407,11 @@ public void filterWhenUnauthorizedThenInvokeFailureHandler() { verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture()); assertThat(this.authorizationExceptionCaptor.getValue()) - .isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> { - assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); - assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token"); - assertThat(e).hasNoCause(); - assertThat(e).hasMessageContaining("[invalid_token]"); + .isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> { + assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); + assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token"); + assertThat(ex).hasNoCause(); + assertThat(ex).hasMessageContaining("[invalid_token]"); }); assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class); assertThat(this.attributesCaptor.getValue()) @@ -431,17 +433,18 @@ public void filterWhenUnauthorizedWithWebClientExceptionThenInvokeFailureHandler WebClientResponseException exception = WebClientResponseException.create(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8); ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception); - assertThatCode(() -> this.function.filter(request, throwingExchangeFunction) - .subscriberContext(serverWebExchange()).block()).isEqualTo(exception); + assertThatExceptionOfType(WebClientResponseException.class).isThrownBy(() -> this.function + .filter(request, throwingExchangeFunction).subscriberContext(serverWebExchange()).block()) + .isEqualTo(exception); assertThat(publisherProbe.wasSubscribed()).isTrue(); verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture()); assertThat(this.authorizationExceptionCaptor.getValue()) - .isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> { - assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); - assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token"); - assertThat(e).hasCause(exception); - assertThat(e).hasMessageContaining("[invalid_token]"); + .isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> { + assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); + assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token"); + assertThat(ex).hasCause(exception); + assertThat(ex).hasMessageContaining("[invalid_token]"); }); assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class); assertThat(this.attributesCaptor.getValue()) @@ -466,11 +469,11 @@ public void filterWhenForbiddenThenInvokeFailureHandler() { verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture()); assertThat(this.authorizationExceptionCaptor.getValue()) - .isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> { - assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); - assertThat(e.getError().getErrorCode()).isEqualTo("insufficient_scope"); - assertThat(e).hasNoCause(); - assertThat(e).hasMessageContaining("[insufficient_scope]"); + .isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> { + assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); + assertThat(ex.getError().getErrorCode()).isEqualTo("insufficient_scope"); + assertThat(ex).hasNoCause(); + assertThat(ex).hasMessageContaining("[insufficient_scope]"); }); assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class); assertThat(this.attributesCaptor.getValue()) @@ -492,17 +495,18 @@ public void filterWhenForbiddenWithWebClientExceptionThenInvokeFailureHandler() WebClientResponseException exception = WebClientResponseException.create(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8); ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception); - assertThatCode(() -> this.function.filter(request, throwingExchangeFunction) - .subscriberContext(serverWebExchange()).block()).isEqualTo(exception); + assertThatExceptionOfType(WebClientResponseException.class).isThrownBy(() -> this.function + .filter(request, throwingExchangeFunction).subscriberContext(serverWebExchange()).block()) + .isEqualTo(exception); assertThat(publisherProbe.wasSubscribed()).isTrue(); verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture()); assertThat(this.authorizationExceptionCaptor.getValue()) - .isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> { - assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); - assertThat(e.getError().getErrorCode()).isEqualTo("insufficient_scope"); - assertThat(e).hasCause(exception); - assertThat(e).hasMessageContaining("[insufficient_scope]"); + .isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> { + assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); + assertThat(ex.getError().getErrorCode()).isEqualTo("insufficient_scope"); + assertThat(ex).hasCause(exception); + assertThat(ex).hasMessageContaining("[insufficient_scope]"); }); assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class); assertThat(this.attributesCaptor.getValue()) @@ -533,14 +537,14 @@ public void filterWhenWWWAuthenticateHeaderIncludesErrorThenInvokeFailureHandler verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture()); assertThat(this.authorizationExceptionCaptor.getValue()) - .isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> { - assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); - assertThat(e.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); - assertThat(e.getError().getDescription()) + .isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> { + assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); + assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); + assertThat(ex.getError().getDescription()) .isEqualTo("The request requires higher privileges than provided by the access token."); - assertThat(e.getError().getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); - assertThat(e).hasNoCause(); - assertThat(e).hasMessageContaining(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); + assertThat(ex.getError().getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); + assertThat(ex).hasNoCause(); + assertThat(ex).hasMessageContaining(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); }); assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class); assertThat(this.attributesCaptor.getValue()) @@ -562,8 +566,9 @@ public void filterWhenAuthorizationExceptionThenInvokeFailureHandler() { OAuth2AuthorizationException exception = new OAuth2AuthorizationException( new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, null, null)); ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception); - assertThatCode(() -> this.function.filter(request, throwingExchangeFunction) - .subscriberContext(serverWebExchange()).block()).isEqualTo(exception); + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> this.function + .filter(request, throwingExchangeFunction).subscriberContext(serverWebExchange()).block()) + .isEqualTo(exception); assertThat(publisherProbe.wasSubscribed()).isTrue(); verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture()); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java index 1cdd07b662f..2e3a7934621 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java @@ -105,8 +105,9 @@ import org.springframework.web.reactive.function.client.WebClientResponseException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -202,32 +203,37 @@ public void cleanup() throws Exception { @Test public void constructorWhenAuthorizedClientManagerIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new ServletOAuth2AuthorizedClientExchangeFilterFunction(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new ServletOAuth2AuthorizedClientExchangeFilterFunction(null)); } @Test public void setClientCredentialsTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.function.setClientCredentialsTokenResponseClient(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("clientCredentialsTokenResponseClient cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.function.setClientCredentialsTokenResponseClient(null)) + .withMessage("clientCredentialsTokenResponseClient cannot be null"); } @Test public void setClientCredentialsTokenResponseClientWhenNotDefaultAuthorizedClientManagerThenThrowIllegalStateException() { - assertThatThrownBy(() -> this.function - .setClientCredentialsTokenResponseClient(new DefaultClientCredentialsTokenResponseClient())) - .isInstanceOf(IllegalStateException.class).hasMessage( - "The client cannot be set when the constructor used is \"ServletOAuth2AuthorizedClientExchangeFilterFunction(OAuth2AuthorizedClientManager)\". " - + "Instead, use the constructor \"ServletOAuth2AuthorizedClientExchangeFilterFunction(ClientRegistrationRepository, OAuth2AuthorizedClientRepository)\"."); + assertThatIllegalStateException() + .isThrownBy(() -> this.function + .setClientCredentialsTokenResponseClient(new DefaultClientCredentialsTokenResponseClient())) + .withMessage("The client cannot be set when the constructor used is " + + "\"ServletOAuth2AuthorizedClientExchangeFilterFunction(OAuth2AuthorizedClientManager)\". " + + "Instead, use the constructor \"ServletOAuth2AuthorizedClientExchangeFilterFunction(ClientRegistrationRepository, " + + "OAuth2AuthorizedClientRepository)\"."); } @Test public void setAccessTokenExpiresSkewWhenNotDefaultAuthorizedClientManagerThenThrowIllegalStateException() { - assertThatThrownBy(() -> this.function.setAccessTokenExpiresSkew(Duration.ofSeconds(30))) - .isInstanceOf(IllegalStateException.class).hasMessage( - "The accessTokenExpiresSkew cannot be set when the constructor used is \"ServletOAuth2AuthorizedClientExchangeFilterFunction(OAuth2AuthorizedClientManager)\". " - + "Instead, use the constructor \"ServletOAuth2AuthorizedClientExchangeFilterFunction(ClientRegistrationRepository, OAuth2AuthorizedClientRepository)\"."); + assertThatIllegalStateException() + .isThrownBy(() -> this.function.setAccessTokenExpiresSkew(Duration.ofSeconds(30))) + .isInstanceOf(IllegalStateException.class) + .withMessage("The accessTokenExpiresSkew cannot be set when the constructor used is " + + "\"ServletOAuth2AuthorizedClientExchangeFilterFunction(OAuth2AuthorizedClientManager)\". " + + "Instead, use the constructor \"ServletOAuth2AuthorizedClientExchangeFilterFunction(ClientRegistrationRepository, " + + "OAuth2AuthorizedClientRepository)\"."); } @Test @@ -642,11 +648,11 @@ private void assertHttpStatusInvokesFailureHandler(HttpStatus httpStatus, String verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture()); assertThat(this.authorizationExceptionCaptor.getValue()) - .isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> { - assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); - assertThat(e.getError().getErrorCode()).isEqualTo(expectedErrorCode); - assertThat(e).hasNoCause(); - assertThat(e).hasMessageContaining(expectedErrorCode); + .isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> { + assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); + assertThat(ex.getError().getErrorCode()).isEqualTo(expectedErrorCode); + assertThat(ex).hasNoCause(); + assertThat(ex).hasMessageContaining(expectedErrorCode); }); assertThat(this.authenticationCaptor.getValue().getName()).isEqualTo(authorizedClient.getPrincipalName()); assertThat(this.attributesCaptor.getValue()).containsExactly( @@ -678,14 +684,14 @@ public void filterWhenWWWAuthenticateHeaderIncludesErrorThenInvokeFailureHandler verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture()); assertThat(this.authorizationExceptionCaptor.getValue()) - .isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> { - assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); - assertThat(e.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); - assertThat(e.getError().getDescription()) + .isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> { + assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); + assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); + assertThat(ex.getError().getDescription()) .isEqualTo("The request requires higher privileges than provided by the access token."); - assertThat(e.getError().getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); - assertThat(e).hasNoCause(); - assertThat(e).hasMessageContaining(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); + assertThat(ex.getError().getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); + assertThat(ex).hasNoCause(); + assertThat(ex).hasMessageContaining(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); }); assertThat(this.authenticationCaptor.getValue().getName()).isEqualTo(authorizedClient.getPrincipalName()); assertThat(this.attributesCaptor.getValue()).containsExactly( @@ -721,15 +727,16 @@ private void assertHttpStatusWithWebClientExceptionInvokesFailureHandler(HttpSta httpStatus.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8); ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception); this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); - assertThatCode(() -> this.function.filter(request, throwingExchangeFunction).block()).isEqualTo(exception); + assertThatExceptionOfType(WebClientResponseException.class) + .isThrownBy(() -> this.function.filter(request, throwingExchangeFunction).block()).isEqualTo(exception); verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture()); assertThat(this.authorizationExceptionCaptor.getValue()) - .isInstanceOfSatisfying(ClientAuthorizationException.class, (e) -> { - assertThat(e.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); - assertThat(e.getError().getErrorCode()).isEqualTo(expectedErrorCode); - assertThat(e).hasCause(exception); - assertThat(e).hasMessageContaining(expectedErrorCode); + .isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> { + assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId()); + assertThat(ex.getError().getErrorCode()).isEqualTo(expectedErrorCode); + assertThat(ex).hasCause(exception); + assertThat(ex).hasMessageContaining(expectedErrorCode); }); assertThat(this.authenticationCaptor.getValue().getName()).isEqualTo(authorizedClient.getPrincipalName()); assertThat(this.attributesCaptor.getValue()).containsExactly( @@ -753,15 +760,17 @@ public void filterWhenAuthorizationExceptionThenInvokeFailureHandler() { new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN)); ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(authorizationException); this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); - assertThatCode(() -> this.function.filter(request, throwingExchangeFunction).block()) + assertThatExceptionOfType(OAuth2AuthorizationException.class) + .isThrownBy(() -> this.function.filter(request, throwingExchangeFunction).block()) .isEqualTo(authorizationException); verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture()); assertThat(this.authorizationExceptionCaptor.getValue()) - .isInstanceOfSatisfying(OAuth2AuthorizationException.class, (e) -> { - assertThat(e.getError().getErrorCode()).isEqualTo(authorizationException.getError().getErrorCode()); - assertThat(e).hasNoCause(); - assertThat(e).hasMessageContaining(OAuth2ErrorCodes.INVALID_TOKEN); + .isInstanceOfSatisfying(OAuth2AuthorizationException.class, (ex) -> { + assertThat(ex.getError().getErrorCode()) + .isEqualTo(authorizationException.getError().getErrorCode()); + assertThat(ex).hasNoCause(); + assertThat(ex).hasMessageContaining(OAuth2ErrorCodes.INVALID_TOKEN); }); assertThat(this.authenticationCaptor.getValue().getName()).isEqualTo(authorizedClient.getPrincipalName()); assertThat(this.attributesCaptor.getValue()).containsExactly( diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java index f92100222fb..16a7cd5c5f4 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java @@ -48,7 +48,8 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.anyString; import static org.mockito.BDDMockito.given; @@ -94,20 +95,19 @@ public void setUp() { @Test public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null, this.authorizedClientRepository)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null, this.authorizedClientRepository)); } @Test public void constructorWhenOAuth2AuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(this.clientRegistrationRepository, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(this.clientRegistrationRepository, null)); } @Test public void constructorWhenAuthorizedClientManagerIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null)); } @Test @@ -134,8 +134,8 @@ public void supportsParameterWhenParameterTypeUnsupportedWithoutAnnotationThenFa @Test public void resolveArgumentWhenRegistrationIdEmptyAndNotOAuth2AuthenticationThenThrowIllegalArgumentException() { MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AuthorizedClient.class); - assertThatThrownBy(() -> resolveArgument(methodParameter)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("The clientRegistrationId could not be resolved. Please provide one"); + assertThatIllegalArgumentException().isThrownBy(() -> resolveArgument(methodParameter)) + .withMessage("The clientRegistrationId could not be resolved. Please provide one"); } @Test @@ -169,8 +169,8 @@ public void resolveArgumentWhenOAuth2AuthorizedClientNotFoundThenThrowClientAuth given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any())).willReturn(Mono.empty()); MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class); - assertThatThrownBy(() -> resolveArgument(methodParameter)) - .isInstanceOf(ClientAuthorizationRequiredException.class); + assertThatExceptionOfType(ClientAuthorizationRequiredException.class) + .isThrownBy(() -> resolveArgument(methodParameter)); } private Object resolveArgument(MethodParameter methodParameter) { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests.java index 3e8bbdc757a..9693d71749f 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests.java @@ -30,7 +30,7 @@ import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService; import org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -65,14 +65,14 @@ public void setup() { @Test public void constructorWhenAuthorizedClientServiceIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(null)); } @Test public void setAuthorizedClientRepositoryWhenAuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientRepository.setAnonymousAuthorizedClientRepository(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientRepository.setAnonymousAuthorizedClientRepository(null)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolverTests.java index 54967496b57..a48ffbb194a 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolverTests.java @@ -39,8 +39,8 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.catchThrowableOfType; +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; @@ -65,8 +65,7 @@ public void setup() { @Test public void setAuthorizationRequestCustomizerWhenNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.resolver.setAuthorizationRequestCustomizer(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.resolver.setAuthorizationRequestCustomizer(null)); } @Test @@ -77,9 +76,9 @@ public void resolveWhenNotMatchThenNull() { @Test public void resolveWhenClientRegistrationNotFoundMatchThenBadRequest() { given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty()); - ResponseStatusException expected = catchThrowableOfType(() -> resolve("/oauth2/authorization/not-found-id"), - ResponseStatusException.class); - assertThat(expected.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThatExceptionOfType(ResponseStatusException.class) + .isThrownBy(() -> resolve("/oauth2/authorization/not-found-id")) + .satisfies((ex) -> assertThat(ex.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java index 56f527b658f..b5a1f5c5e72 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java @@ -49,8 +49,8 @@ import org.springframework.web.server.handler.DefaultWebFilterChain; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -90,30 +90,30 @@ public void setup() { @Test public void constructorWhenAuthenticationManagerNullThenIllegalArgumentException() { this.authenticationManager = null; - assertThatCode(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager, - this.clientRegistrationRepository, this.authorizedClientRepository)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager, + this.clientRegistrationRepository, this.authorizedClientRepository)); } @Test public void constructorWhenClientRegistrationRepositoryNullThenIllegalArgumentException() { this.clientRegistrationRepository = null; - assertThatCode(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager, - this.clientRegistrationRepository, this.authorizedClientRepository)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager, + this.clientRegistrationRepository, this.authorizedClientRepository)); } @Test public void constructorWhenAuthorizedClientRepositoryNullThenIllegalArgumentException() { this.authorizedClientRepository = null; - assertThatCode(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager, - this.clientRegistrationRepository, this.authorizedClientRepository)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizationCodeGrantWebFilter(this.authenticationManager, + this.clientRegistrationRepository, this.authorizedClientRepository)); } @Test public void setRequestCacheWhenRequestCacheIsNullThenThrowIllegalArgumentException() { - assertThatCode(() -> this.filter.setRequestCache(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestCache(null)); } @Test @@ -267,10 +267,10 @@ public void filterWhenAuthenticationConverterThrowsOAuth2AuthorizationExceptionT MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse); DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList()); - assertThatThrownBy(() -> this.filter.filter(exchange, chain).block()) - .isInstanceOf(OAuth2AuthenticationException.class) - .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()).extracting("errorCode") - .isEqualTo("client_registration_not_found"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.filter.filter(exchange, chain).block()) + .satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode") + .isEqualTo("client_registration_not_found")); verifyNoInteractions(this.authenticationManager); } @@ -292,10 +292,9 @@ public void filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThe MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse); DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList()); - assertThatThrownBy(() -> this.filter.filter(exchange, chain).block()) - .isInstanceOf(OAuth2AuthenticationException.class) - .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()).extracting("errorCode") - .isEqualTo("authorization_error"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.filter.filter(exchange, chain).block()) + .satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode").isEqualTo("authorization_error")); } private static OAuth2AuthorizationRequest createOAuth2AuthorizationRequest( diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java index f5c6f0c5f8b..a1a7f9e6573 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java @@ -37,7 +37,7 @@ import org.springframework.web.server.handler.FilteringWebHandler; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.verify; @@ -80,8 +80,8 @@ public void setup() { @Test public void constructorWhenClientRegistrationRepositoryNullThenIllegalArgumentException() { this.clientRepository = null; - assertThatThrownBy(() -> new OAuth2AuthorizationRequestRedirectWebFilter(this.clientRepository)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2AuthorizationRequestRedirectWebFilter(this.clientRepository)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java index aed902381d4..a1dfa74248d 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java @@ -39,7 +39,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -85,7 +85,7 @@ public void setup() { @Test public void applyWhenAuthorizationRequestEmptyThenOAuth2AuthorizationException() { given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.empty()); - assertThatThrownBy(() -> applyConverter()).isInstanceOf(OAuth2AuthorizationException.class); + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> applyConverter()); } @Test @@ -93,8 +93,8 @@ public void applyWhenAttributesMissingThenOAuth2AuthorizationException() { this.authorizationRequest.attributes(Map::clear); given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) .willReturn(Mono.just(this.authorizationRequest.build())); - assertThatThrownBy(() -> applyConverter()).isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> applyConverter()) + .withMessageContaining( ServerOAuth2AuthorizationCodeAuthenticationTokenConverter.CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE); } @@ -103,8 +103,8 @@ public void applyWhenClientRegistrationMissingThenOAuth2AuthorizationException() given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) .willReturn(Mono.just(this.authorizationRequest.build())); given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty()); - assertThatThrownBy(() -> applyConverter()).isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining( + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> applyConverter()) + .withMessageContaining( ServerOAuth2AuthorizationCodeAuthenticationTokenConverter.CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/UnAuthenticatedServerOAuth2AuthorizedClientRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/UnAuthenticatedServerOAuth2AuthorizedClientRepositoryTests.java index 23c526bdf30..308c5f03db2 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/UnAuthenticatedServerOAuth2AuthorizedClientRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/UnAuthenticatedServerOAuth2AuthorizedClientRepositoryTests.java @@ -33,7 +33,7 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch @@ -65,25 +65,22 @@ public void setup() { @Test public void loadAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() { this.clientRegistrationId = null; - assertThatThrownBy(() -> this.repository - .loadAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.repository + .loadAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()); } @Test public void loadAuthorizedClientWhenAuthenticationNotNullThenIllegalArgumentException() { this.authentication = new TestingAuthenticationToken("a", "b", "ROLE_USER"); - assertThatThrownBy(() -> this.repository - .loadAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.repository + .loadAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()); } @Test public void loadAuthorizedClientWhenServerWebExchangeNotNullThenIllegalArgumentException() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); - assertThatThrownBy(() -> this.repository - .loadAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.repository + .loadAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()); } @Test @@ -123,50 +120,44 @@ public void loadAuthorizedClientWhenAnonymousThenFound() { @Test public void saveAuthorizedClientWhenAuthorizedClientNullThenIllegalArgumentException() { this.authorizedClient = null; - assertThatThrownBy(() -> this.repository - .saveAuthorizedClient(this.authorizedClient, this.authentication, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.repository + .saveAuthorizedClient(this.authorizedClient, this.authentication, this.exchange).block()); } @Test public void saveAuthorizedClientWhenAuthenticationNotNullThenIllegalArgumentException() { this.authentication = new TestingAuthenticationToken("a", "b", "ROLE_USER"); - assertThatThrownBy(() -> this.repository - .saveAuthorizedClient(this.authorizedClient, this.authentication, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.repository + .saveAuthorizedClient(this.authorizedClient, this.authentication, this.exchange).block()); } @Test public void saveAuthorizedClientWhenServerWebExchangeNotNullThenIllegalArgumentException() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); - assertThatThrownBy(() -> this.repository - .saveAuthorizedClient(this.authorizedClient, this.authentication, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.repository + .saveAuthorizedClient(this.authorizedClient, this.authentication, this.exchange).block()); } // removeAuthorizedClient @Test public void removeAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() { this.clientRegistrationId = null; - assertThatThrownBy(() -> this.repository - .removeAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.repository + .removeAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()); } @Test public void removeAuthorizedClientWhenAuthenticationNotNullThenIllegalArgumentException() { this.authentication = new TestingAuthenticationToken("a", "b", "ROLE_USER"); - assertThatThrownBy(() -> this.repository - .removeAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.repository + .removeAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()); } @Test public void removeAuthorizedClientWhenServerWebExchangeNotNullThenIllegalArgumentException() { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); - assertThatThrownBy(() -> this.repository - .removeAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.repository + .removeAuthorizedClient(this.clientRegistrationId, this.authentication, this.exchange).block()); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionOAuth2ServerAuthorizationRequestRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionOAuth2ServerAuthorizationRequestRepositoryTests.java index 13a50ed5ab7..c2be0f46bfc 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionOAuth2ServerAuthorizationRequestRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionOAuth2ServerAuthorizationRequestRepositoryTests.java @@ -35,7 +35,7 @@ import org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver; import org.springframework.web.server.session.WebSessionManager; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -61,8 +61,7 @@ public class WebSessionOAuth2ServerAuthorizationRequestRepositoryTests { @Test public void loadAuthorizationRequestWhenNullExchangeThenIllegalArgumentException() { this.exchange = null; - assertThatThrownBy(() -> this.repository.loadAuthorizationRequest(this.exchange)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.repository.loadAuthorizationRequest(this.exchange)); } @Test @@ -121,23 +120,23 @@ public void loadAuthorizationRequestWhenMultipleSavedThenAuthorizationRequest() @Test public void saveAuthorizationRequestWhenAuthorizationRequestNullThenThrowsIllegalArgumentException() { this.authorizationRequest = null; - assertThatThrownBy(() -> this.repository.saveAuthorizationRequest(this.authorizationRequest, this.exchange)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.repository.saveAuthorizationRequest(this.authorizationRequest, this.exchange)); assertSessionStartedIs(false); } @Test public void saveAuthorizationRequestWhenExchangeNullThenThrowsIllegalArgumentException() { this.exchange = null; - assertThatThrownBy(() -> this.repository.saveAuthorizationRequest(this.authorizationRequest, this.exchange)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.repository.saveAuthorizationRequest(this.authorizationRequest, this.exchange)); } @Test public void removeAuthorizationRequestWhenExchangeNullThenThrowsIllegalArgumentException() { this.exchange = null; - assertThatThrownBy(() -> this.repository.removeAuthorizationRequest(this.exchange)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.repository.removeAuthorizationRequest(this.exchange)); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionServerOAuth2AuthorizedClientRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionServerOAuth2AuthorizedClientRepositoryTests.java index e24d86bb861..d0bd4714074 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionServerOAuth2AuthorizedClientRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionServerOAuth2AuthorizedClientRepositoryTests.java @@ -27,7 +27,7 @@ import org.springframework.web.server.WebSession; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -52,9 +52,8 @@ public class WebSessionServerOAuth2AuthorizedClientRepositoryTests { @Test public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( - () -> this.authorizedClientRepository.loadAuthorizedClient(null, null, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientRepository.loadAuthorizedClient(null, null, this.exchange).block()); } @Test @@ -64,9 +63,8 @@ public void loadAuthorizedClientWhenPrincipalNameIsNullThenExceptionNotThrown() @Test public void loadAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( - () -> this.authorizedClientRepository.loadAuthorizedClient(this.registrationId1, null, null).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientRepository.loadAuthorizedClient(this.registrationId1, null, null).block()); } @Test @@ -88,9 +86,8 @@ public void loadAuthorizedClientWhenSavedThenReturnAuthorizedClient() { @Test public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( - () -> this.authorizedClientRepository.saveAuthorizedClient(null, null, this.exchange).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientRepository.saveAuthorizedClient(null, null, this.exchange).block()); } @Test @@ -104,9 +101,8 @@ public void saveAuthorizedClientWhenAuthenticationIsNullThenExceptionNotThrown() public void saveAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1, mock(OAuth2AccessToken.class)); - assertThatThrownBy( - () -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, null).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, null).block()); } @Test @@ -121,8 +117,8 @@ public void saveAuthorizedClientWhenSavedThenSavedToSession() { @Test public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.authorizedClientRepository.removeAuthorizedClient(null, null, this.exchange)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.authorizedClientRepository.removeAuthorizedClient(null, null, this.exchange)); } @Test @@ -132,9 +128,8 @@ public void removeAuthorizedClientWhenPrincipalNameIsNullThenExceptionNotThrown( @Test public void removeAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy( - () -> this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, null)); } @Test diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/AuthenticationMethodTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/AuthenticationMethodTests.java index f49f14cbae3..2b4af499036 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/AuthenticationMethodTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/AuthenticationMethodTests.java @@ -19,7 +19,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link AuthenticationMethod}. @@ -30,7 +30,8 @@ public class AuthenticationMethodTests { @Test public void constructorWhenValueIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new AuthenticationMethod(null)).hasMessage("value cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new AuthenticationMethod(null)) + .withMessage("value cannot be empty"); } @Test diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipalTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipalTests.java index 642d1217d0c..5a1940c9457 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipalTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipalTests.java @@ -26,7 +26,7 @@ import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultOAuth2AuthenticatedPrincipal} @@ -43,10 +43,10 @@ public class DefaultOAuth2AuthenticatedPrincipalTests { @Test public void constructorWhenAttributesIsNullOrEmptyThenIllegalArgumentException() { - assertThatCode(() -> new DefaultOAuth2AuthenticatedPrincipal(null, this.authorities)) - .isInstanceOf(IllegalArgumentException.class); - assertThatCode(() -> new DefaultOAuth2AuthenticatedPrincipal(Collections.emptyMap(), this.authorities)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DefaultOAuth2AuthenticatedPrincipal(null, this.authorities)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DefaultOAuth2AuthenticatedPrincipal(Collections.emptyMap(), this.authorities)); } @Test diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DelegatingOAuth2TokenValidatorTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DelegatingOAuth2TokenValidatorTests.java index 5e23cec5d91..ce4fa6b3654 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DelegatingOAuth2TokenValidatorTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DelegatingOAuth2TokenValidatorTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -92,9 +92,8 @@ public void validateWhenAllValidatorsSucceedThenReturnsSuccessfulResult() { @Test public void constructorWhenInvokedWithNullValidatorListThenThrowsIllegalArgumentException() { - assertThatCode(() -> new DelegatingOAuth2TokenValidator<>( - (Collection>) null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingOAuth2TokenValidator<>( + (Collection>) null)); } @Test diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/converter/ClaimTypeConverterTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/converter/ClaimTypeConverterTests.java index d09bff9892f..0b0d9f0acd7 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/converter/ClaimTypeConverterTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/converter/ClaimTypeConverterTests.java @@ -31,7 +31,7 @@ import org.springframework.core.convert.converter.Converter; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ClaimTypeConverter}. @@ -89,15 +89,14 @@ public void setup() { @Test public void constructorWhenConvertersNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new ClaimTypeConverter(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new ClaimTypeConverter(null)); } @Test public void constructorWhenConvertersHasNullConverterThenThrowIllegalArgumentException() { Map> claimTypeConverters = new HashMap<>(); claimTypeConverters.put("claim1", null); - assertThatThrownBy(() -> new ClaimTypeConverter(claimTypeConverters)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new ClaimTypeConverter(claimTypeConverters)); } @Test diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationRequestTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationRequestTests.java index 3855e1eae8f..c823500f34f 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationRequestTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationRequestTests.java @@ -28,8 +28,7 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2AuthorizationRequest}. @@ -51,50 +50,47 @@ public class OAuth2AuthorizationRequestTests { @Test public void buildWhenAuthorizationUriIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizationRequest.authorizationCode().authorizationUri(null) - .clientId(CLIENT_ID).redirectUri(REDIRECT_URI).scopes(SCOPES).state(STATE).build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> OAuth2AuthorizationRequest.authorizationCode().authorizationUri(null) + .clientId(CLIENT_ID).redirectUri(REDIRECT_URI).scopes(SCOPES).state(STATE).build()); } @Test public void buildWhenClientIdIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizationRequest.authorizationCode().authorizationUri(AUTHORIZATION_URI) - .clientId(null).redirectUri(REDIRECT_URI).scopes(SCOPES).state(STATE).build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> OAuth2AuthorizationRequest.authorizationCode().authorizationUri(AUTHORIZATION_URI) + .clientId(null).redirectUri(REDIRECT_URI).scopes(SCOPES).state(STATE).build()); } @Test public void buildWhenRedirectUriIsNullForImplicitThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizationRequest.implicit().authorizationUri(AUTHORIZATION_URI) - .clientId(CLIENT_ID).redirectUri(null).scopes(SCOPES).state(STATE).build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> OAuth2AuthorizationRequest.implicit().authorizationUri(AUTHORIZATION_URI) + .clientId(CLIENT_ID).redirectUri(null).scopes(SCOPES).state(STATE).build()); } @Test public void buildWhenRedirectUriIsNullForAuthorizationCodeThenDoesNotThrowAnyException() { - assertThatCode(() -> OAuth2AuthorizationRequest.authorizationCode().authorizationUri(AUTHORIZATION_URI) - .clientId(CLIENT_ID).redirectUri(null).scopes(SCOPES).state(STATE).build()).doesNotThrowAnyException(); + OAuth2AuthorizationRequest.authorizationCode().authorizationUri(AUTHORIZATION_URI).clientId(CLIENT_ID) + .redirectUri(null).scopes(SCOPES).state(STATE).build(); } @Test public void buildWhenScopesIsNullThenDoesNotThrowAnyException() { - assertThatCode(() -> OAuth2AuthorizationRequest.authorizationCode().authorizationUri(AUTHORIZATION_URI) - .clientId(CLIENT_ID).redirectUri(REDIRECT_URI).scopes(null).state(STATE).build()) - .doesNotThrowAnyException(); + OAuth2AuthorizationRequest.authorizationCode().authorizationUri(AUTHORIZATION_URI).clientId(CLIENT_ID) + .redirectUri(REDIRECT_URI).scopes(null).state(STATE).build(); } @Test public void buildWhenStateIsNullThenDoesNotThrowAnyException() { - assertThatCode(() -> OAuth2AuthorizationRequest.authorizationCode().authorizationUri(AUTHORIZATION_URI) - .clientId(CLIENT_ID).redirectUri(REDIRECT_URI).scopes(SCOPES).state(null).build()) - .doesNotThrowAnyException(); + OAuth2AuthorizationRequest.authorizationCode().authorizationUri(AUTHORIZATION_URI).clientId(CLIENT_ID) + .redirectUri(REDIRECT_URI).scopes(SCOPES).state(null).build(); } @Test public void buildWhenAdditionalParametersEmptyThenDoesNotThrowAnyException() { - assertThatCode(() -> OAuth2AuthorizationRequest.authorizationCode().authorizationUri(AUTHORIZATION_URI) - .clientId(CLIENT_ID).redirectUri(REDIRECT_URI).scopes(SCOPES).state(STATE) - .additionalParameters(Map::clear).build()).doesNotThrowAnyException(); + OAuth2AuthorizationRequest.authorizationCode().authorizationUri(AUTHORIZATION_URI).clientId(CLIENT_ID) + .redirectUri(REDIRECT_URI).scopes(SCOPES).state(STATE).additionalParameters(Map::clear).build(); } @Test @@ -189,7 +185,7 @@ public void buildWhenRequiredParametersSetThenAuthorizationRequestUriIncludesReq @Test public void fromWhenAuthorizationRequestIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> OAuth2AuthorizationRequest.from(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizationRequest.from(null)); } @Test diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationResponseTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationResponseTests.java index d7ba2d2d285..dd7c5e1d9d6 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationResponseTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationResponseTests.java @@ -19,7 +19,6 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; /** * Tests for {@link OAuth2AuthorizationResponse}. @@ -52,9 +51,7 @@ public void buildSuccessResponseWhenRedirectUriIsNullThenThrowIllegalArgumentExc @Test public void buildSuccessResponseWhenStateIsNullThenDoesNotThrowAnyException() { - assertThatCode( - () -> OAuth2AuthorizationResponse.success(AUTH_CODE).redirectUri(REDIRECT_URI).state(null).build()) - .doesNotThrowAnyException(); + OAuth2AuthorizationResponse.success(AUTH_CODE).redirectUri(REDIRECT_URI).state(null).build(); } @Test @@ -84,9 +81,7 @@ public void buildErrorResponseWhenRedirectUriIsNullThenThrowIllegalArgumentExcep @Test public void buildErrorResponseWhenStateIsNullThenDoesNotThrowAnyException() { - assertThatCode( - () -> OAuth2AuthorizationResponse.error(ERROR_CODE).redirectUri(REDIRECT_URI).state(null).build()) - .doesNotThrowAnyException(); + OAuth2AuthorizationResponse.error(ERROR_CODE).redirectUri(REDIRECT_URI).state(null).build(); } @Test diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverterTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverterTests.java index 3a6f98a92f9..0fc466a072d 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverterTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverterTests.java @@ -36,7 +36,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -63,14 +64,13 @@ public void supportsWhenOAuth2AccessTokenResponseThenTrue() { @Test public void setTokenResponseConverterWhenConverterIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.messageConverter.setTokenResponseConverter(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.messageConverter.setTokenResponseConverter(null)); } @Test public void setTokenResponseParametersConverterWhenConverterIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.messageConverter.setTokenResponseParametersConverter(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.messageConverter.setTokenResponseParametersConverter(null)); } @Test @@ -141,9 +141,9 @@ public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableExcept this.messageConverter.setTokenResponseConverter(tokenResponseConverter); String tokenResponse = "{}"; MockClientHttpResponse response = new MockClientHttpResponse(tokenResponse.getBytes(), HttpStatus.OK); - assertThatThrownBy(() -> this.messageConverter.readInternal(OAuth2AccessTokenResponse.class, response)) - .isInstanceOf(HttpMessageNotReadableException.class) - .hasMessageContaining("An error occurred reading the OAuth 2.0 Access Token Response"); + assertThatExceptionOfType(HttpMessageNotReadableException.class) + .isThrownBy(() -> this.messageConverter.readInternal(OAuth2AccessTokenResponse.class, response)) + .withMessageContaining("An error occurred reading the OAuth 2.0 Access Token Response"); } @Test @@ -177,9 +177,9 @@ public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableExcep .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(Instant.now().plusSeconds(3600).toEpochMilli()) .build(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); - assertThatThrownBy(() -> this.messageConverter.writeInternal(accessTokenResponse, outputMessage)) - .isInstanceOf(HttpMessageNotWritableException.class) - .hasMessageContaining("An error occurred writing the OAuth 2.0 Access Token Response"); + assertThatExceptionOfType(HttpMessageNotWritableException.class) + .isThrownBy(() -> this.messageConverter.writeInternal(accessTokenResponse, outputMessage)) + .withMessageContaining("An error occurred writing the OAuth 2.0 Access Token Response"); } } diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2ErrorHttpMessageConverterTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2ErrorHttpMessageConverterTests.java index 0e9dc1ad143..a28b1d890ed 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2ErrorHttpMessageConverterTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2ErrorHttpMessageConverterTests.java @@ -28,7 +28,8 @@ import org.springframework.security.oauth2.core.OAuth2Error; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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; @@ -54,14 +55,12 @@ public void supportsWhenOAuth2ErrorThenTrue() { @Test public void setErrorConverterWhenConverterIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.messageConverter.setErrorConverter(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.messageConverter.setErrorConverter(null)); } @Test public void setErrorParametersConverterWhenConverterIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> this.messageConverter.setErrorParametersConverter(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.messageConverter.setErrorParametersConverter(null)); } @Test @@ -96,9 +95,9 @@ public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableExcept this.messageConverter.setErrorConverter(errorConverter); String errorResponse = "{}"; MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST); - assertThatThrownBy(() -> this.messageConverter.readInternal(OAuth2Error.class, response)) - .isInstanceOf(HttpMessageNotReadableException.class) - .hasMessageContaining("An error occurred reading the OAuth 2.0 Error"); + assertThatExceptionOfType(HttpMessageNotReadableException.class) + .isThrownBy(() -> this.messageConverter.readInternal(OAuth2Error.class, response)) + .withMessageContaining("An error occurred reading the OAuth 2.0 Error"); } @Test @@ -121,9 +120,9 @@ public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableExcep OAuth2Error oauth2Error = new OAuth2Error("unauthorized_client", "The client is not authorized", "https://tools.ietf.org/html/rfc6749#section-5.2"); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); - assertThatThrownBy(() -> this.messageConverter.writeInternal(oauth2Error, outputMessage)) - .isInstanceOf(HttpMessageNotWritableException.class) - .hasMessageContaining("An error occurred writing the OAuth 2.0 Error"); + assertThatExceptionOfType(HttpMessageNotWritableException.class) + .isThrownBy(() -> this.messageConverter.writeInternal(oauth2Error, outputMessage)) + .withMessageContaining("An error occurred writing the OAuth 2.0 Error"); } } diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenBuilderTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenBuilderTests.java index adcce05236c..0b62a74f9b1 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenBuilderTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenBuilderTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OidcUserInfo} @@ -51,8 +51,8 @@ public void expiresAtWhenUsingGenericOrNamedClaimMethodRequiresInstant() { assertThat(idToken.getExpiresAt()).isSameAs(now); idToken = idTokenBuilder.expiresAt(now).build(); assertThat(idToken.getExpiresAt()).isSameAs(now); - assertThatCode(() -> idTokenBuilder.claim(IdTokenClaimNames.EXP, "not an instant").build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> idTokenBuilder.claim(IdTokenClaimNames.EXP, "not an instant").build()); } @Test @@ -63,8 +63,8 @@ public void issuedAtWhenUsingGenericOrNamedClaimMethodRequiresInstant() { assertThat(idToken.getIssuedAt()).isSameAs(now); idToken = idTokenBuilder.issuedAt(now).build(); assertThat(idToken.getIssuedAt()).isSameAs(now); - assertThatCode(() -> idTokenBuilder.claim(IdTokenClaimNames.IAT, "not an instant").build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> idTokenBuilder.claim(IdTokenClaimNames.IAT, "not an instant").build()); } @Test diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/user/OidcUserAuthorityTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/user/OidcUserAuthorityTests.java index d086c3eb999..f139e6c1679 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/user/OidcUserAuthorityTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/user/OidcUserAuthorityTests.java @@ -28,7 +28,6 @@ import org.springframework.security.oauth2.core.oidc.StandardClaimNames; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; /** * Tests for {@link OidcUserAuthority}. @@ -66,7 +65,7 @@ public void constructorWhenIdTokenIsNullThenThrowIllegalArgumentException() { @Test public void constructorWhenUserInfoIsNullThenDoesNotThrowAnyException() { - assertThatCode(() -> new OidcUserAuthority(ID_TOKEN, null)).doesNotThrowAnyException(); + new OidcUserAuthority(ID_TOKEN, null); } @Test(expected = IllegalArgumentException.class) diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2BodyExtractorsTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2BodyExtractorsTests.java index abe976ecc88..754592cf413 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2BodyExtractorsTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2BodyExtractorsTests.java @@ -44,7 +44,7 @@ import org.springframework.web.reactive.function.BodyExtractor; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch @@ -90,8 +90,8 @@ public void oauth2AccessTokenResponseWhenInvalidJsonThenException() { response.getHeaders().setContentType(MediaType.APPLICATION_JSON); response.setBody("{"); Mono result = extractor.extract(response, this.context); - assertThatCode(result::block).isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining("An error occurred parsing the Access Token response"); + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(result::block) + .withMessageContaining("An error occurred parsing the Access Token response"); } @Test @@ -100,8 +100,8 @@ public void oauth2AccessTokenResponseWhenEmptyThenException() { .oauth2AccessTokenResponse(); MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK); Mono result = extractor.extract(response, this.context); - assertThatCode(result::block).isInstanceOf(OAuth2AuthorizationException.class) - .hasMessageContaining("Empty OAuth 2.0 Access Token Response"); + assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(result::block) + .withMessageContaining("Empty OAuth 2.0 Access Token Response"); } @Test diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtBuilderTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtBuilderTests.java index efac7719f7b..4aab4d0e2d0 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtBuilderTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtBuilderTests.java @@ -21,7 +21,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link Jwt.Builder}. @@ -59,8 +59,8 @@ public void expiresAtWhenUsingGenericOrNamedClaimMethodRequiresInstant() { assertThat(jwt.getExpiresAt()).isSameAs(now); jwt = jwtBuilder.expiresAt(now).build(); assertThat(jwt.getExpiresAt()).isSameAs(now); - assertThatCode(() -> jwtBuilder.claim(JwtClaimNames.EXP, "not an instant").build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> jwtBuilder.claim(JwtClaimNames.EXP, "not an instant").build()); } @Test @@ -71,8 +71,8 @@ public void issuedAtWhenUsingGenericOrNamedClaimMethodRequiresInstant() { assertThat(jwt.getIssuedAt()).isSameAs(now); jwt = jwtBuilder.issuedAt(now).build(); assertThat(jwt.getIssuedAt()).isSameAs(now); - assertThatCode(() -> jwtBuilder.claim(JwtClaimNames.IAT, "not an instant").build()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> jwtBuilder.claim(JwtClaimNames.IAT, "not an instant").build()); } @Test diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java index 26e60fed35a..820d73e3226 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java @@ -23,7 +23,7 @@ import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link JwtClaimValidator}. @@ -50,18 +50,17 @@ public void validateWhenClaimFailsTheTestThenReturnsFailure() { @Test public void validateWhenClaimIsNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> new JwtClaimValidator<>(null, test)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new JwtClaimValidator<>(null, test)); } @Test public void validateWhenTestIsNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> new JwtClaimValidator<>(JwtClaimNames.ISS, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new JwtClaimValidator<>(JwtClaimNames.ISS, null)); } @Test public void validateWhenJwtIsNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> this.validator.validate(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.validator.validate(null)); } } diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtDecodersTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtDecodersTests.java index c3206a37f30..7f6b4da77ee 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtDecodersTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtDecodersTests.java @@ -39,7 +39,9 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link JwtDecoders} @@ -91,24 +93,24 @@ public void cleanup() throws Exception { public void issuerWhenResponseIsTypicalThenReturnedDecoderValidatesIssuer() { prepareConfigurationResponse(); JwtDecoder decoder = JwtDecoders.fromOidcIssuerLocation(this.issuer); - assertThatCode(() -> decoder.decode(ISSUER_MISMATCH)).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("The iss claim is not valid"); + assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> decoder.decode(ISSUER_MISMATCH)) + .withMessageContaining("The iss claim is not valid"); } @Test public void issuerWhenOidcFallbackResponseIsTypicalThenReturnedDecoderValidatesIssuer() { prepareConfigurationResponseOidc(); JwtDecoder decoder = JwtDecoders.fromIssuerLocation(this.issuer); - assertThatCode(() -> decoder.decode(ISSUER_MISMATCH)).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("The iss claim is not valid"); + assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> decoder.decode(ISSUER_MISMATCH)) + .withMessageContaining("The iss claim is not valid"); } @Test public void issuerWhenOAuth2ResponseIsTypicalThenReturnedDecoderValidatesIssuer() { prepareConfigurationResponseOAuth2(); JwtDecoder decoder = JwtDecoders.fromIssuerLocation(this.issuer); - assertThatCode(() -> decoder.decode(ISSUER_MISMATCH)).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("The iss claim is not valid"); + assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> decoder.decode(ISSUER_MISMATCH)) + .withMessageContaining("The iss claim is not valid"); } @Test @@ -138,19 +140,20 @@ public void issuerWhenOAuth2ContainsTrailingSlashThenSuccess() { @Test public void issuerWhenResponseIsNonCompliantThenThrowsRuntimeException() { prepareConfigurationResponse("{ \"missing_required_keys\" : \"and_values\" }"); - assertThatCode(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer)).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer)); } @Test public void issuerWhenOidcFallbackResponseIsNonCompliantThenThrowsRuntimeException() { prepareConfigurationResponseOidc("{ \"missing_required_keys\" : \"and_values\" }"); - assertThatCode(() -> JwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer)); } @Test public void issuerWhenOAuth2ResponseIsNonCompliantThenThrowsRuntimeException() { prepareConfigurationResponseOAuth2("{ \"missing_required_keys\" : \"and_values\" }"); - assertThatCode(() -> JwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer)); } // gh-7512 @@ -158,8 +161,8 @@ public void issuerWhenOAuth2ResponseIsNonCompliantThenThrowsRuntimeException() { public void issuerWhenResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException() throws JsonMappingException, JsonProcessingException { prepareConfigurationResponse(this.buildResponseWithMissingJwksUri()); - assertThatCode(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("The public JWK set URI must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer)) + .withMessage("The public JWK set URI must not be null"); } // gh-7512 @@ -167,8 +170,8 @@ public void issuerWhenResponseDoesNotContainJwksUriThenThrowsIllegalArgumentExce public void issuerWhenOidcFallbackResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException() throws JsonMappingException, JsonProcessingException { prepareConfigurationResponseOidc(this.buildResponseWithMissingJwksUri()); - assertThatCode(() -> JwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("The public JWK set URI must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer)) + .isInstanceOf(IllegalArgumentException.class).withMessage("The public JWK set URI must not be null"); } // gh-7512 @@ -176,60 +179,59 @@ public void issuerWhenOidcFallbackResponseDoesNotContainJwksUriThenThrowsIllegal public void issuerWhenOAuth2ResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException() throws JsonMappingException, JsonProcessingException { prepareConfigurationResponseOAuth2(this.buildResponseWithMissingJwksUri()); - assertThatCode(() -> JwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("The public JWK set URI must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer)) + .withMessage("The public JWK set URI must not be null"); } @Test public void issuerWhenResponseIsMalformedThenThrowsRuntimeException() { prepareConfigurationResponse("malformed"); - assertThatCode(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer)).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer)); } @Test public void issuerWhenOidcFallbackResponseIsMalformedThenThrowsRuntimeException() { prepareConfigurationResponseOidc("malformed"); - assertThatCode(() -> JwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer)); } @Test public void issuerWhenOAuth2ResponseIsMalformedThenThrowsRuntimeException() { prepareConfigurationResponseOAuth2("malformed"); - assertThatCode(() -> JwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer)); } @Test public void issuerWhenRespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() { prepareConfigurationResponse(String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer)); - assertThatCode(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer)).isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer)); } @Test public void issuerWhenOidcFallbackRespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() { prepareConfigurationResponseOidc(String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer)); - assertThatCode(() -> JwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer)); } @Test public void issuerWhenOAuth2RespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() { prepareConfigurationResponseOAuth2( String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer)); - assertThatCode(() -> JwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer)); } @Test public void issuerWhenRequestedIssuerIsUnresponsiveThenThrowsIllegalArgumentException() throws Exception { this.server.shutdown(); - assertThatCode(() -> JwtDecoders.fromOidcIssuerLocation("https://issuer")) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> JwtDecoders.fromOidcIssuerLocation("https://issuer")); } @Test public void issuerWhenOidcFallbackRequestedIssuerIsUnresponsiveThenThrowsIllegalArgumentException() throws Exception { this.server.shutdown(); - assertThatCode(() -> JwtDecoders.fromIssuerLocation("https://issuer")) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> JwtDecoders.fromIssuerLocation("https://issuer")); } private void prepareConfigurationResponse() { diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtIssuerValidatorTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtIssuerValidatorTests.java index 501beb5fb9a..5127b086a6a 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtIssuerValidatorTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtIssuerValidatorTests.java @@ -21,7 +21,7 @@ import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Josh Cummings @@ -63,12 +63,12 @@ public void validateWhenIssuerMatchesAndIsNotAUriThenReturnsSuccess() { @Test public void validateWhenJwtIsNullThenThrowsIllegalArgumentException() { - assertThatCode(() -> this.validator.validate(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.validator.validate(null)); } @Test public void constructorWhenNullIssuerIsGivenThenThrowsIllegalArgumentException() { - assertThatCode(() -> new JwtIssuerValidator(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new JwtIssuerValidator(null)); } } diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java index 8cac7c007c7..7f17fb761b3 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java @@ -32,7 +32,7 @@ import org.springframework.security.oauth2.jose.jws.JwsAlgorithms; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests verifying {@link JwtTimestampValidator} @@ -137,12 +137,12 @@ public void validateWhenBothExpiryAndNotBeforeAreValidThenReturnsSuccessfulResul @Test public void setClockWhenInvokedWithNullThenThrowsIllegalArgumentException() { JwtTimestampValidator jwtValidator = new JwtTimestampValidator(); - assertThatCode(() -> jwtValidator.setClock(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> jwtValidator.setClock(null)); } @Test public void constructorWhenInvokedWithNullDurationThenThrowsIllegalArgumentException() { - assertThatCode(() -> new JwtTimestampValidator(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new JwtTimestampValidator(null)); } } diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverterTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverterTests.java index d27b08df2a8..403d5692ea2 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverterTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverterTests.java @@ -31,7 +31,8 @@ import org.springframework.core.convert.converter.Converter; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -169,13 +170,13 @@ public void convertWhenUsingConstructorThenOnlyConvertersInThatMapAreUsedForConv public void convertWhenUsingDefaultsThenFailedConversionThrowsIllegalStateException() { MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap()); Map badIssuer = Collections.singletonMap(JwtClaimNames.ISS, "https://badly formed iss"); - assertThatCode(() -> converter.convert(badIssuer)).isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> converter.convert(badIssuer)); Map badIssuedAt = Collections.singletonMap(JwtClaimNames.IAT, "badly-formed-iat"); - assertThatCode(() -> converter.convert(badIssuedAt)).isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> converter.convert(badIssuedAt)); Map badExpiresAt = Collections.singletonMap(JwtClaimNames.EXP, "badly-formed-exp"); - assertThatCode(() -> converter.convert(badExpiresAt)).isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> converter.convert(badExpiresAt)); Map badNotBefore = Collections.singletonMap(JwtClaimNames.NBF, "badly-formed-nbf"); - assertThatCode(() -> converter.convert(badNotBefore)).isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> converter.convert(badNotBefore)); } // gh-6073 @@ -198,13 +199,12 @@ public void convertWhenIssuerIsOfTypeURLThenConvertsToString() throws Exception @Test public void constructWhenAnyParameterIsNullThenIllegalArgumentException() { - assertThatCode(() -> new MappedJwtClaimSetConverter(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new MappedJwtClaimSetConverter(null)); } @Test public void withDefaultsWhenAnyParameterIsNullThenIllegalArgumentException() { - assertThatCode(() -> MappedJwtClaimSetConverter.withDefaults(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> MappedJwtClaimSetConverter.withDefaults(null)); } } diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java index b0b848f875e..26d7c5f9c94 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java @@ -23,7 +23,6 @@ import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; -import org.assertj.core.api.Assertions; import org.junit.Test; import org.springframework.core.convert.converter.Converter; @@ -38,8 +37,8 @@ import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.BDDMockito.given; @@ -73,30 +72,27 @@ public class NimbusJwtDecoderJwkSupportTests { @Test public void constructorWhenJwkSetUrlIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new NimbusJwtDecoderJwkSupport(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new NimbusJwtDecoderJwkSupport(null)); } @Test public void constructorWhenJwkSetUrlInvalidThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new NimbusJwtDecoderJwkSupport("invalid.com")) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new NimbusJwtDecoderJwkSupport("invalid.com")); } @Test public void constructorWhenJwsAlgorithmIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new NimbusJwtDecoderJwkSupport(JWK_SET_URL, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new NimbusJwtDecoderJwkSupport(JWK_SET_URL, null)); } @Test public void setRestOperationsWhenNullThenThrowIllegalArgumentException() { - Assertions.assertThatThrownBy(() -> this.jwtDecoder.setRestOperations(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.jwtDecoder.setRestOperations(null)); } @Test public void decodeWhenJwtInvalidThenThrowJwtException() { - assertThatThrownBy(() -> this.jwtDecoder.decode("invalid")).isInstanceOf(JwtException.class); + assertThatExceptionOfType(JwtException.class).isThrownBy(() -> this.jwtDecoder.decode("invalid")); } // gh-5168 @@ -109,14 +105,14 @@ public void decodeWhenExpClaimNullThenDoesNotThrowException() { claims.remove(JwtClaimNames.EXP); return claims; }); - assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).doesNotThrowAnyException(); + jwtDecoder.decode(SIGNED_JWT); } // gh-5457 @Test public void decodeWhenPlainJwtThenExceptionDoesNotMentionClass() { - assertThatCode(() -> this.jwtDecoder.decode(UNSIGNED_JWT)).isInstanceOf(JwtException.class) - .hasMessageContaining("Unsupported algorithm of none"); + assertThatExceptionOfType(JwtException.class).isThrownBy(() -> this.jwtDecoder.decode(UNSIGNED_JWT)) + .withMessageContaining("Unsupported algorithm of none"); } @Test @@ -125,8 +121,8 @@ public void decodeWhenJwtIsMalformedThenReturnsStockException() throws Exception server.enqueue(new MockResponse().setBody(JWK_SET)); String jwkSetUrl = server.url("/.well-known/jwks.json").toString(); NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(jwkSetUrl); - assertThatCode(() -> jwtDecoder.decode(MALFORMED_JWT)).isInstanceOf(JwtException.class) - .hasMessage("An error occurred while attempting to decode the Jwt: Malformed payload"); + assertThatExceptionOfType(JwtException.class).isThrownBy(() -> jwtDecoder.decode(MALFORMED_JWT)) + .withMessage("An error occurred while attempting to decode the Jwt: Malformed payload"); server.shutdown(); } } @@ -137,8 +133,8 @@ public void decodeWhenJwkResponseIsMalformedThenReturnsStockException() throws E server.enqueue(new MockResponse().setBody(MALFORMED_JWK_SET)); String jwkSetUrl = server.url("/.well-known/jwks.json").toString(); NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(jwkSetUrl); - assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtException.class) - .hasMessage("An error occurred while attempting to decode the Jwt: Malformed Jwk set"); + assertThatExceptionOfType(JwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)) + .withMessage("An error occurred while attempting to decode the Jwt: Malformed Jwk set"); server.shutdown(); } } @@ -149,8 +145,8 @@ public void decodeWhenJwkEndpointIsUnresponsiveThenReturnsJwtException() throws server.enqueue(new MockResponse().setBody(MALFORMED_JWK_SET)); String jwkSetUrl = server.url("/.well-known/jwks.json").toString(); NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(jwkSetUrl); - assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtException.class) - .hasMessageContaining("An error occurred while attempting to decode the Jwt"); + assertThatExceptionOfType(JwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)) + .withMessageContaining("An error occurred while attempting to decode the Jwt"); server.shutdown(); } } @@ -164,7 +160,7 @@ public void decodeWhenCustomRestOperationsSetThenUsed() throws Exception { NimbusJwtDecoderJwkSupport jwtDecoder = new NimbusJwtDecoderJwkSupport(jwkSetUrl); RestTemplate restTemplate = spy(new RestTemplate()); jwtDecoder.setRestOperations(restTemplate); - assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).doesNotThrowAnyException(); + jwtDecoder.decode(SIGNED_JWT); verify(restTemplate).exchange(any(RequestEntity.class), eq(String.class)); server.shutdown(); } @@ -180,8 +176,8 @@ public void decodeWhenJwtFailsValidationThenReturnsCorrespondingErrorMessage() t OAuth2TokenValidator jwtValidator = mock(OAuth2TokenValidator.class); given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(failure)); decoder.setJwtValidator(jwtValidator); - assertThatCode(() -> decoder.decode(SIGNED_JWT)).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("mock-description"); + assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> decoder.decode(SIGNED_JWT)) + .withMessageContaining("mock-description"); } } @@ -197,9 +193,9 @@ public void decodeWhenJwtValidationHasTwoErrorsThenJwtExceptionMessageShowsFirst OAuth2TokenValidator jwtValidator = mock(OAuth2TokenValidator.class); given(jwtValidator.validate(any(Jwt.class))).willReturn(result); decoder.setJwtValidator(jwtValidator); - assertThatCode(() -> decoder.decode(SIGNED_JWT)).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("mock-description") - .hasFieldOrPropertyWithValue("errors", Arrays.asList(firstFailure, secondFailure)); + assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> decoder.decode(SIGNED_JWT)) + .withMessageContaining("mock-description").satisfies((ex) -> assertThat(ex) + .hasFieldOrPropertyWithValue("errors", Arrays.asList(firstFailure, secondFailure))); } } @@ -220,7 +216,7 @@ public void decodeWhenUsingSignedJwtThenReturnsClaimsGivenByClaimSetConverter() @Test public void setClaimSetConverterWhenIsNullThenThrowsIllegalArgumentException() { - assertThatCode(() -> this.jwtDecoder.setClaimSetConverter(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.jwtDecoder.setClaimSetConverter(null)); } private static RestOperations mockJwkSetResponse(String response) { diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java index fcdd0e2c84e..2c2154e9973 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java @@ -76,8 +76,8 @@ import org.springframework.web.client.RestOperations; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.BDDMockito.given; @@ -128,47 +128,46 @@ public static void keyFactory() throws NoSuchAlgorithmException { @Test public void constructorWhenJwtProcessorIsNullThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> new NimbusJwtDecoder(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new NimbusJwtDecoder(null)); } @Test public void setClaimSetConverterWhenIsNullThenThrowsIllegalArgumentException() { - assertThatCode(() -> this.jwtDecoder.setClaimSetConverter(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.jwtDecoder.setClaimSetConverter(null)); } @Test public void setJwtValidatorWhenNullThenThrowIllegalArgumentException() { - Assertions.assertThatThrownBy(() -> this.jwtDecoder.setJwtValidator(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.jwtDecoder.setJwtValidator(null)); } @Test public void decodeWhenJwtInvalidThenThrowJwtException() { - assertThatThrownBy(() -> this.jwtDecoder.decode("invalid")).isInstanceOf(BadJwtException.class); + assertThatExceptionOfType(JwtException.class).isThrownBy(() -> this.jwtDecoder.decode("invalid")); } // gh-5168 @Test public void decodeWhenExpClaimNullThenDoesNotThrowException() { - assertThatCode(() -> this.jwtDecoder.decode(EMPTY_EXP_CLAIM_JWT)).doesNotThrowAnyException(); + this.jwtDecoder.decode(EMPTY_EXP_CLAIM_JWT); } @Test public void decodeWhenIatClaimNullThenDoesNotThrowException() { - assertThatCode(() -> this.jwtDecoder.decode(SIGNED_JWT)).doesNotThrowAnyException(); + this.jwtDecoder.decode(SIGNED_JWT); } // gh-5457 @Test public void decodeWhenPlainJwtThenExceptionDoesNotMentionClass() { - assertThatCode(() -> this.jwtDecoder.decode(UNSIGNED_JWT)).isInstanceOf(BadJwtException.class) - .hasMessageContaining("Unsupported algorithm of none"); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.jwtDecoder.decode(UNSIGNED_JWT)) + .withMessageContaining("Unsupported algorithm of none"); } @Test public void decodeWhenJwtIsMalformedThenReturnsStockException() { - assertThatCode(() -> this.jwtDecoder.decode(MALFORMED_JWT)).isInstanceOf(BadJwtException.class) - .hasMessage("An error occurred while attempting to decode the Jwt: Malformed payload"); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.jwtDecoder.decode(MALFORMED_JWT)) + .withMessage("An error occurred while attempting to decode the Jwt: Malformed payload"); } @Test @@ -177,8 +176,8 @@ public void decodeWhenJwtFailsValidationThenReturnsCorrespondingErrorMessage() { OAuth2TokenValidator jwtValidator = mock(OAuth2TokenValidator.class); given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(failure)); this.jwtDecoder.setJwtValidator(jwtValidator); - assertThatCode(() -> this.jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("mock-description"); + assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)) + .withMessageContaining("mock-description"); } @Test @@ -189,9 +188,9 @@ public void decodeWhenJwtValidationHasTwoErrorsThenJwtExceptionMessageShowsFirst OAuth2TokenValidator jwtValidator = mock(OAuth2TokenValidator.class); given(jwtValidator.validate(any(Jwt.class))).willReturn(result); this.jwtDecoder.setJwtValidator(jwtValidator); - assertThatCode(() -> this.jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("mock-description") - .hasFieldOrPropertyWithValue("errors", Arrays.asList(firstFailure, secondFailure)); + assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)) + .withMessageContaining("mock-description").satisfies((ex) -> assertThat(ex) + .hasFieldOrPropertyWithValue("errors", Arrays.asList(firstFailure, secondFailure))); } @Test @@ -203,8 +202,8 @@ public void decodeWhenReadingErrorPickTheFirstErrorMessage() { OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second"); OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2); given(jwtValidator.validate(any(Jwt.class))).willReturn(result); - Assertions.assertThatCode(() -> this.jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("mock-description"); + Assertions.assertThatExceptionOfType(JwtValidationException.class) + .isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("mock-description"); } @Test @@ -223,7 +222,7 @@ public void decodeWhenClaimSetConverterFailsThenBadJwtException() { Converter, Map> claimSetConverter = mock(Converter.class); this.jwtDecoder.setClaimSetConverter(claimSetConverter); given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion")); - assertThatCode(() -> this.jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(BadJwtException.class); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)); } @Test @@ -236,9 +235,9 @@ public void decodeWhenSignedThenOk() { @Test public void decodeWhenJwkResponseIsMalformedThenReturnsStockException() { NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(withSigning(MALFORMED_JWK_SET)); - assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtException.class) + assertThatExceptionOfType(JwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)) .isNotInstanceOf(BadJwtException.class) - .hasMessage("An error occurred while attempting to decode the Jwt: Malformed Jwk set"); + .withMessage("An error occurred while attempting to decode the Jwt: Malformed Jwk set"); } @Test @@ -247,9 +246,9 @@ public void decodeWhenJwkEndpointIsUnresponsiveThenReturnsJwtException() throws String jwkSetUri = server.url("/.well-known/jwks.json").toString(); NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build(); server.shutdown(); - assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtException.class) + assertThatExceptionOfType(JwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)) .isNotInstanceOf(BadJwtException.class) - .hasMessageContaining("An error occurred while attempting to decode the Jwt"); + .withMessageContaining("An error occurred while attempting to decode the Jwt"); } } @@ -260,39 +259,38 @@ public void decodeWhenJwkEndpointIsUnresponsiveAndCacheIsConfiguredThenReturnsJw String jwkSetUri = server.url("/.well-known/jwks.json").toString(); NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).cache(cache).build(); server.shutdown(); - assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtException.class) + assertThatExceptionOfType(JwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)) .isNotInstanceOf(BadJwtException.class) - .hasMessageContaining("An error occurred while attempting to decode the Jwt"); + .withMessageContaining("An error occurred while attempting to decode the Jwt"); } } @Test public void withJwkSetUriWhenNullOrEmptyThenThrowsException() { - Assertions.assertThatCode(() -> NimbusJwtDecoder.withJwkSetUri(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> NimbusJwtDecoder.withJwkSetUri(null)); } @Test public void jwsAlgorithmWhenNullThenThrowsException() { NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI); - Assertions.assertThatCode(() -> builder.jwsAlgorithm(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> builder.jwsAlgorithm(null)); } @Test public void restOperationsWhenNullThenThrowsException() { NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI); - Assertions.assertThatCode(() -> builder.restOperations(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> builder.restOperations(null)); } @Test public void cacheWhenNullThenThrowsException() { NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI); - Assertions.assertThatCode(() -> builder.cache(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> builder.cache(null)); } @Test public void withPublicKeyWhenNullThenThrowsException() { - assertThatThrownBy(() -> NimbusJwtDecoder.withPublicKey(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> NimbusJwtDecoder.withPublicKey(null)); } @Test @@ -333,7 +331,7 @@ public void decodeWhenUsingPublicKeyWithKidThenStillUsesKey() throws Exception { public void decodeWhenSignatureMismatchesAlgorithmThenThrowsException() throws Exception { NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.RS512) .build(); - Assertions.assertThatCode(() -> decoder.decode(RS256_SIGNED_JWT)).isInstanceOf(BadJwtException.class); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> decoder.decode(RS256_SIGNED_JWT)); } // gh-8730 @@ -355,21 +353,23 @@ public void withPublicKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes() thro @Test public void withPublicKeyWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> NimbusJwtDecoder.withPublicKey(key()).jwtProcessorCustomizer(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> NimbusJwtDecoder.withPublicKey(key()).jwtProcessorCustomizer(null)) + .withMessage("jwtProcessorCustomizer cannot be null"); } @Test public void withSecretKeyWhenNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> NimbusJwtDecoder.withSecretKey(null)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("secretKey cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> NimbusJwtDecoder.withSecretKey(null)) + .withMessage("secretKey cannot be null"); } @Test public void withSecretKeyWhenMacAlgorithmNullThenThrowsIllegalArgumentException() { SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY; - assertThatThrownBy(() -> NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("macAlgorithm cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(null)) + .withMessage("macAlgorithm cannot be null"); } @Test @@ -391,8 +391,8 @@ public void decodeWhenUsingSecretKeyAndIncorrectAlgorithmThenThrowsJwtException( .expirationTime(Date.from(Instant.now().plusSeconds(60))).build(); SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet); NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS512).build(); - assertThatThrownBy(() -> decoder.decode(signedJWT.serialize())).isInstanceOf(BadJwtException.class) - .hasMessageContaining("Unsupported algorithm of HS256"); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> decoder.decode(signedJWT.serialize())) + .withMessageContaining("Unsupported algorithm of HS256"); } // gh-7056 @@ -425,8 +425,9 @@ public void withSecretKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes() thro @Test public void withSecretKeyWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY; - assertThatThrownBy(() -> NimbusJwtDecoder.withSecretKey(secretKey).jwtProcessorCustomizer(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> NimbusJwtDecoder.withSecretKey(secretKey).jwtProcessorCustomizer(null)) + .withMessage("jwtProcessorCustomizer cannot be null"); } @Test @@ -515,9 +516,9 @@ public void decodeWhenCacheIsConfiguredAndValueLoaderErrorsThenThrowsJwtExceptio .willThrow(new RestClientException("Cannot retrieve JWK Set")); NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations) .cache(cache).build(); - assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtException.class) + assertThatExceptionOfType(JwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)) .isNotInstanceOf(BadJwtException.class) - .hasMessageContaining("An error occurred while attempting to decode the Jwt"); + .withMessageContaining("An error occurred while attempting to decode the Jwt"); } // gh-8730 @@ -530,14 +531,16 @@ public void withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws .jwtProcessorCustomizer( (p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); - assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(BadJwtException.class).hasMessageContaining( - "An error occurred while attempting to decode the Jwt: Required JOSE header \"typ\" (type) parameter is missing"); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)) + .withMessageContaining("An error occurred while attempting to decode the Jwt: " + + "Required JOSE header \"typ\" (type) parameter is missing"); } @Test public void withJwkSetUriWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).jwtProcessorCustomizer(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).jwtProcessorCustomizer(null)) + .withMessage("jwtProcessorCustomizer cannot be null"); } private RSAPublicKey key() throws InvalidKeySpecException { diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java index 164877f9042..a33eb0af3eb 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java @@ -64,8 +64,9 @@ import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.Mockito.mock; @@ -125,8 +126,8 @@ public void cleanup() throws Exception { @Test public void decodeWhenInvalidUrl() { this.decoder = new NimbusReactiveJwtDecoder("https://s"); - assertThatCode(() -> this.decoder.decode(this.messageReadToken).block()) - .isInstanceOf(IllegalStateException.class).hasCauseInstanceOf(UnknownHostException.class); + assertThatIllegalStateException().isThrownBy(() -> this.decoder.decode(this.messageReadToken).block()) + .withCauseInstanceOf(UnknownHostException.class); } @Test @@ -143,7 +144,7 @@ public void decodeWhenRSAPublicKeyThenSuccess() throws Exception { .generatePublic(new X509EncodedKeySpec(bytes)); this.decoder = new NimbusReactiveJwtDecoder(publicKey); String noKeyId = "eyJhbGciOiJSUzI1NiJ9.eyJzY29wZSI6IiIsImV4cCI6OTIyMzM3MjAwNjA5NjM3NX0.hNVuHSUkxdLZrDfqdmKcOi0ggmNaDuB4ZPxPtJl1gwBiXzIGN6Hwl24O2BfBZiHFKUTQDs4_RvzD71mEG3DvUrcKmdYWqIB1l8KNmxQLUDG-cAPIpJmRJgCh50tf8OhOE_Cb9E1HcsOUb47kT9iz-VayNBcmo6BmyZLdEGhsdGBrc3Mkz2dd_0PF38I2Hf_cuSjn9gBjFGtiPEXJvob3PEjVTSx_zvodT8D9p3An1R3YBZf5JSd1cQisrXgDX2k1Jmf7UKKWzgfyCgnEtRWWbsUdPqo3rSEY9GDC1iSQXsFTTC1FT_JJDkwzGf011fsU5O_Ko28TARibmKTCxAKNRQ"; - assertThatCode(() -> this.decoder.decode(noKeyId).block()).doesNotThrowAnyException(); + this.decoder.decode(noKeyId).block(); } @Test @@ -155,45 +156,46 @@ public void decodeWhenIssuedAtThenSuccess() { @Test public void decodeWhenExpiredThenFail() { - assertThatCode(() -> this.decoder.decode(this.expired).block()).isInstanceOf(JwtValidationException.class); + assertThatExceptionOfType(JwtValidationException.class) + .isThrownBy(() -> this.decoder.decode(this.expired).block()); } @Test public void decodeWhenNoPeriodThenFail() { - assertThatCode(() -> this.decoder.decode("").block()).isInstanceOf(BadJwtException.class); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.decoder.decode("").block()); } @Test public void decodeWhenInvalidJwkSetUrlThenFail() { this.decoder = new NimbusReactiveJwtDecoder("http://localhost:1280/certs"); - assertThatCode(() -> this.decoder.decode(this.messageReadToken).block()) - .isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> this.decoder.decode(this.messageReadToken).block()); } @Test public void decodeWhenInvalidSignatureThenFail() { - assertThatCode(() -> this.decoder.decode(this.messageReadToken.substring(0, this.messageReadToken.length() - 2)) - .block()).isInstanceOf(BadJwtException.class); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.decoder + .decode(this.messageReadToken.substring(0, this.messageReadToken.length() - 2)).block()); } @Test public void decodeWhenAlgNoneThenFail() { - assertThatCode(() -> this.decoder.decode( + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.decoder.decode( "ew0KICAiYWxnIjogIm5vbmUiLA0KICAidHlwIjogIkpXVCINCn0.ew0KICAic3ViIjogIjEyMzQ1Njc4OTAiLA0KICAibmFtZSI6ICJKb2huIERvZSIsDQogICJpYXQiOiAxNTE2MjM5MDIyDQp9.") - .block()).isInstanceOf(BadJwtException.class).hasMessage("Unsupported algorithm of none"); + .block()).withMessage("Unsupported algorithm of none"); } @Test public void decodeWhenInvalidAlgMismatchThenFail() { - assertThatCode(() -> this.decoder.decode( + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.decoder.decode( "ew0KICAiYWxnIjogIkVTMjU2IiwNCiAgInR5cCI6ICJKV1QiDQp9.ew0KICAic3ViIjogIjEyMzQ1Njc4OTAiLA0KICAibmFtZSI6ICJKb2huIERvZSIsDQogICJpYXQiOiAxNTE2MjM5MDIyDQp9.") - .block()).isInstanceOf(BadJwtException.class); + .block()); } @Test public void decodeWhenUnsignedTokenThenMessageDoesNotMentionClass() { - assertThatCode(() -> this.decoder.decode(this.unsignedToken).block()).isInstanceOf(BadJwtException.class) - .hasMessage("Unsupported algorithm of none"); + assertThatExceptionOfType(BadJwtException.class) + .isThrownBy(() -> this.decoder.decode(this.unsignedToken).block()) + .withMessage("Unsupported algorithm of none"); } @Test @@ -203,8 +205,9 @@ public void decodeWhenUsingCustomValidatorThenValidatorIsInvoked() { OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri"); OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(error); given(jwtValidator.validate(any(Jwt.class))).willReturn(result); - assertThatCode(() -> this.decoder.decode(this.messageReadToken).block()) - .isInstanceOf(JwtValidationException.class).hasMessageContaining("mock-description"); + assertThatExceptionOfType(JwtValidationException.class) + .isThrownBy(() -> this.decoder.decode(this.messageReadToken).block()) + .withMessageContaining("mock-description"); } @Test @@ -216,8 +219,9 @@ public void decodeWhenReadingErrorPickTheFirstErrorMessage() { OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second"); OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2); given(jwtValidator.validate(any(Jwt.class))).willReturn(result); - assertThatCode(() -> this.decoder.decode(this.messageReadToken).block()) - .isInstanceOf(JwtValidationException.class).hasMessageContaining("mock-description"); + assertThatExceptionOfType(JwtValidationException.class) + .isThrownBy(() -> this.decoder.decode(this.messageReadToken).block()) + .withMessageContaining("mock-description"); } @Test @@ -237,44 +241,44 @@ public void decodeWhenClaimSetConverterFailsThenBadJwtException() { Converter, Map> claimSetConverter = mock(Converter.class); this.decoder.setClaimSetConverter(claimSetConverter); given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion")); - assertThatCode(() -> this.decoder.decode(this.messageReadToken).block()).isInstanceOf(BadJwtException.class); + assertThatExceptionOfType(BadJwtException.class) + .isThrownBy(() -> this.decoder.decode(this.messageReadToken).block()); } @Test public void setJwtValidatorWhenGivenNullThrowsIllegalArgumentException() { - assertThatCode(() -> this.decoder.setJwtValidator(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.decoder.setJwtValidator(null)); } @Test public void setClaimSetConverterWhenNullThrowsIllegalArgumentException() { - assertThatCode(() -> this.decoder.setClaimSetConverter(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.decoder.setClaimSetConverter(null)); } @Test public void withJwkSetUriWhenNullOrEmptyThenThrowsException() { - assertThatCode(() -> NimbusReactiveJwtDecoder.withJwkSetUri(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> NimbusReactiveJwtDecoder.withJwkSetUri(null)); } @Test public void jwsAlgorithmWhenNullThenThrowsException() { NimbusReactiveJwtDecoder.JwkSetUriReactiveJwtDecoderBuilder builder = NimbusReactiveJwtDecoder .withJwkSetUri(this.jwkSetUri); - assertThatCode(() -> builder.jwsAlgorithm(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> builder.jwsAlgorithm(null)); } @Test public void withJwkSetUriWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { - assertThatCode( + assertThatIllegalArgumentException().isThrownBy( () -> NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).jwtProcessorCustomizer(null).build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("jwtProcessorCustomizer cannot be null"); + .withMessage("jwtProcessorCustomizer cannot be null"); } @Test public void restOperationsWhenNullThenThrowsException() { NimbusReactiveJwtDecoder.JwkSetUriReactiveJwtDecoderBuilder builder = NimbusReactiveJwtDecoder .withJwkSetUri(this.jwkSetUri); - assertThatCode(() -> builder.webClient(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> builder.webClient(null)); } // gh-5603 @@ -295,26 +299,26 @@ public void withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType() { .jwtProcessorCustomizer( (p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); - assertThatCode(() -> decoder.decode(this.messageReadToken).block()).isInstanceOf(BadJwtException.class) - .hasRootCauseMessage("Required JOSE header \"typ\" (type) parameter is missing"); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> decoder.decode(this.messageReadToken).block()) + .havingRootCause().withMessage("Required JOSE header \"typ\" (type) parameter is missing"); } @Test public void withPublicKeyWhenNullThenThrowsException() { - assertThatThrownBy(() -> NimbusReactiveJwtDecoder.withPublicKey(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> NimbusReactiveJwtDecoder.withPublicKey(null)); } @Test public void buildWhenSignatureAlgorithmMismatchesKeyTypeThenThrowsException() { - assertThatCode(() -> NimbusReactiveJwtDecoder.withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.ES256) - .build()).isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> NimbusReactiveJwtDecoder.withPublicKey(key()) + .signatureAlgorithm(SignatureAlgorithm.ES256).build()); } @Test public void buildWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { - assertThatCode(() -> NimbusReactiveJwtDecoder.withPublicKey(key()).jwtProcessorCustomizer(null).build()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> NimbusReactiveJwtDecoder.withPublicKey(key()).jwtProcessorCustomizer(null).build()) + .withMessage("jwtProcessorCustomizer cannot be null"); } @Test @@ -334,7 +338,7 @@ public void decodeWhenUsingPublicKeyWithRs512ThenSuccessfullyDecodes() throws Ex public void decodeWhenSignatureMismatchesAlgorithmThenThrowsException() throws Exception { NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withPublicKey(key()) .signatureAlgorithm(SignatureAlgorithm.RS512).build(); - assertThatCode(() -> decoder.decode(this.rsa256).block()).isInstanceOf(BadJwtException.class); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> decoder.decode(this.rsa256).block()); } // gh-8730 @@ -344,21 +348,20 @@ public void withPublicKeyWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws .jwtProcessorCustomizer( (p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); - assertThatCode(() -> decoder.decode(this.rsa256).block()) - .isInstanceOf(BadJwtException.class) - .hasRootCauseMessage("Required JOSE header \"typ\" (type) parameter is missing"); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> decoder.decode(this.rsa256).block()) + .havingRootCause().withMessage("Required JOSE header \"typ\" (type) parameter is missing"); } @Test public void withJwkSourceWhenNullThenThrowsException() { - assertThatCode(() -> NimbusReactiveJwtDecoder.withJwkSource(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> NimbusReactiveJwtDecoder.withJwkSource(null)); } @Test public void withJwkSourceWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { - assertThatCode(() -> NimbusReactiveJwtDecoder.withJwkSource((jwt) -> Flux.empty()).jwtProcessorCustomizer(null) - .build()).isInstanceOf(IllegalArgumentException.class) - .hasMessage("jwtProcessorCustomizer cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> NimbusReactiveJwtDecoder + .withJwkSource((jwt) -> Flux.empty()).jwtProcessorCustomizer(null).build()) + .withMessage("jwtProcessorCustomizer cannot be null"); } @Test @@ -375,28 +378,31 @@ public void withJwkSourceWhenUsingCustomTypeHeaderThenRefuseOmittedType() { .jwtProcessorCustomizer( (p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); - assertThatCode(() -> decoder.decode(this.messageReadToken).block()).isInstanceOf(BadJwtException.class) - .hasRootCauseMessage("Required JOSE header \"typ\" (type) parameter is missing"); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> decoder.decode(this.messageReadToken).block()) + .havingRootCause().withMessage("Required JOSE header \"typ\" (type) parameter is missing"); } @Test public void withSecretKeyWhenSecretKeyNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> NimbusReactiveJwtDecoder.withSecretKey(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("secretKey cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> NimbusReactiveJwtDecoder.withSecretKey(null)) + .withMessage("secretKey cannot be null"); } @Test public void withSecretKeyWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY; - assertThatThrownBy(() -> NimbusReactiveJwtDecoder.withSecretKey(secretKey).jwtProcessorCustomizer(null).build()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> NimbusReactiveJwtDecoder.withSecretKey(secretKey).jwtProcessorCustomizer(null).build()) + .withMessage("jwtProcessorCustomizer cannot be null"); } @Test public void withSecretKeyWhenMacAlgorithmNullThenThrowsIllegalArgumentException() { SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY; - assertThatThrownBy(() -> NimbusReactiveJwtDecoder.withSecretKey(secretKey).macAlgorithm(null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("macAlgorithm cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> NimbusReactiveJwtDecoder.withSecretKey(secretKey).macAlgorithm(null)) + .withMessage("macAlgorithm cannot be null"); } @Test @@ -419,8 +425,8 @@ public void withSecretKeyWhenUsingCustomTypeHeaderThenRefuseOmittedType() { .jwtProcessorCustomizer( (p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); - assertThatCode(() -> decoder.decode(this.messageReadToken).block()).isInstanceOf(BadJwtException.class) - .hasRootCauseMessage("Required JOSE header \"typ\" (type) parameter is missing"); + assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> decoder.decode(this.messageReadToken).block()) + .havingRootCause().withMessage("Required JOSE header \"typ\" (type) parameter is missing"); } @Test @@ -431,8 +437,8 @@ public void decodeWhenSecretKeyAndAlgorithmMismatchThenThrowsJwtException() thro .expirationTime(Date.from(Instant.now().plusSeconds(60))).build(); SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet); this.decoder = NimbusReactiveJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS512).build(); - assertThatThrownBy(() -> this.decoder.decode(signedJWT.serialize()).block()) - .isInstanceOf(BadJwtException.class); + assertThatExceptionOfType(BadJwtException.class) + .isThrownBy(() -> this.decoder.decode(signedJWT.serialize()).block()); } @Test diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecodersTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecodersTests.java index bd106ef99a6..57a7c37c63d 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecodersTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecodersTests.java @@ -38,7 +38,9 @@ import org.springframework.http.MediaType; import org.springframework.web.util.UriComponentsBuilder; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * Tests for {@link ReactiveJwtDecoders} @@ -91,43 +93,48 @@ public void cleanup() throws Exception { public void issuerWhenResponseIsTypicalThenReturnedDecoderValidatesIssuer() { prepareConfigurationResponse(); ReactiveJwtDecoder decoder = ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer); - assertThatCode(() -> decoder.decode(ISSUER_MISMATCH).block()).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("The iss claim is not valid"); + assertThatExceptionOfType(JwtValidationException.class) + .isThrownBy(() -> decoder.decode(ISSUER_MISMATCH).block()) + .withMessageContaining("The iss claim is not valid"); } @Test public void issuerWhenOidcFallbackResponseIsTypicalThenReturnedDecoderValidatesIssuer() { prepareConfigurationResponseOidc(); ReactiveJwtDecoder decoder = ReactiveJwtDecoders.fromIssuerLocation(this.issuer); - assertThatCode(() -> decoder.decode(ISSUER_MISMATCH).block()).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("The iss claim is not valid"); + assertThatExceptionOfType(JwtValidationException.class) + .isThrownBy(() -> decoder.decode(ISSUER_MISMATCH).block()) + .withMessageContaining("The iss claim is not valid"); } @Test public void issuerWhenOAuth2ResponseIsTypicalThenReturnedDecoderValidatesIssuer() { prepareConfigurationResponseOAuth2(); ReactiveJwtDecoder decoder = ReactiveJwtDecoders.fromIssuerLocation(this.issuer); - assertThatCode(() -> decoder.decode(ISSUER_MISMATCH).block()).isInstanceOf(JwtValidationException.class) - .hasMessageContaining("The iss claim is not valid"); + assertThatExceptionOfType(JwtValidationException.class) + .isThrownBy(() -> decoder.decode(ISSUER_MISMATCH).block()) + .withMessageContaining("The iss claim is not valid"); } @Test public void issuerWhenResponseIsNonCompliantThenThrowsRuntimeException() { prepareConfigurationResponse("{ \"missing_required_keys\" : \"and_values\" }"); - assertThatCode(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer)) - .isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer)); } @Test public void issuerWhenOidcFallbackResponseIsNonCompliantThenThrowsRuntimeException() { prepareConfigurationResponseOidc("{ \"missing_required_keys\" : \"and_values\" }"); - assertThatCode(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)); } @Test public void issuerWhenOAuth2ResponseIsNonCompliantThenThrowsRuntimeException() { prepareConfigurationResponseOAuth2("{ \"missing_required_keys\" : \"and_values\" }"); - assertThatCode(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)); } // gh-7512 @@ -135,8 +142,8 @@ public void issuerWhenOAuth2ResponseIsNonCompliantThenThrowsRuntimeException() { public void issuerWhenResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException() throws JsonMappingException, JsonProcessingException { prepareConfigurationResponse(this.buildResponseWithMissingJwksUri()); - assertThatCode(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("The public JWK set URI must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer)) + .withMessage("The public JWK set URI must not be null"); } // gh-7512 @@ -144,8 +151,8 @@ public void issuerWhenResponseDoesNotContainJwksUriThenThrowsIllegalArgumentExce public void issuerWhenOidcFallbackResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException() throws JsonMappingException, JsonProcessingException { prepareConfigurationResponseOidc(this.buildResponseWithMissingJwksUri()); - assertThatCode(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("The public JWK set URI must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)) + .withMessage("The public JWK set URI must not be null"); } // gh-7512 @@ -153,64 +160,62 @@ public void issuerWhenOidcFallbackResponseDoesNotContainJwksUriThenThrowsIllegal public void issuerWhenOAuth2ResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException() throws JsonMappingException, JsonProcessingException { prepareConfigurationResponseOAuth2(this.buildResponseWithMissingJwksUri()); - assertThatCode(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("The public JWK set URI must not be null"); + assertThatIllegalArgumentException().isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)) + .withMessage("The public JWK set URI must not be null"); } @Test public void issuerWhenResponseIsMalformedThenThrowsRuntimeException() { prepareConfigurationResponse("malformed"); - assertThatCode(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer)) - .isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer)); } @Test public void issuerWhenOidcFallbackResponseIsMalformedThenThrowsRuntimeException() { prepareConfigurationResponseOidc("malformed"); - assertThatCode(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)); } @Test public void issuerWhenOAuth2ResponseIsMalformedThenThrowsRuntimeException() { prepareConfigurationResponseOAuth2("malformed"); - assertThatCode(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)); } @Test public void issuerWhenRespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() { prepareConfigurationResponse(String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer)); - assertThatCode(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer)) - .isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer)); } @Test public void issuerWhenOidcFallbackRespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() { prepareConfigurationResponseOidc(String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer)); - assertThatCode(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)) - .isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)); } @Test public void issuerWhenOAuth2RespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() { prepareConfigurationResponseOAuth2( String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer)); - assertThatCode(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)) - .isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer)); } @Test public void issuerWhenRequestedIssuerIsUnresponsiveThenThrowsIllegalArgumentException() throws Exception { this.server.shutdown(); - assertThatCode(() -> ReactiveJwtDecoders.fromOidcIssuerLocation("https://issuer")) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> ReactiveJwtDecoders.fromOidcIssuerLocation("https://issuer")); } @Test public void issuerWhenOidcFallbackRequestedIssuerIsUnresponsiveThenThrowsIllegalArgumentException() throws Exception { this.server.shutdown(); - assertThatCode(() -> ReactiveJwtDecoders.fromIssuerLocation("https://issuer")) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation("https://issuer")); } private void prepareConfigurationResponse() { diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationTokenTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationTokenTests.java index e8c520ed09a..edc5a8077c3 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationTokenTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationTokenTests.java @@ -19,7 +19,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link BearerTokenAuthenticationToken} @@ -30,14 +30,14 @@ public class BearerTokenAuthenticationTokenTests { @Test public void constructorWhenTokenIsNullThenThrowsException() { - assertThatCode(() -> new BearerTokenAuthenticationToken(null)).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("token cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenAuthenticationToken(null)) + .withMessageContaining("token cannot be empty"); } @Test public void constructorWhenTokenIsEmptyThenThrowsException() { - assertThatCode(() -> new BearerTokenAuthenticationToken("")).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("token cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenAuthenticationToken("")) + .withMessageContaining("token cannot be empty"); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorTests.java index b095788d940..2eb36f38bf1 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorTests.java @@ -21,7 +21,7 @@ import org.springframework.http.HttpStatus; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link BearerTokenError} @@ -53,20 +53,20 @@ public void constructorWithErrorCodeWhenErrorCodeIsValidThenCreated() { @Test public void constructorWithErrorCodeAndHttpStatusWhenErrorCodeIsNullThenThrowIllegalArgumentException() { - assertThatCode(() -> new BearerTokenError(null, TEST_HTTP_STATUS, null, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("errorCode cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenError(null, TEST_HTTP_STATUS, null, null)) + .withMessage("errorCode cannot be empty"); } @Test public void constructorWithErrorCodeAndHttpStatusWhenErrorCodeIsEmptyThenThrowIllegalArgumentException() { - assertThatCode(() -> new BearerTokenError("", TEST_HTTP_STATUS, null, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("errorCode cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenError("", TEST_HTTP_STATUS, null, null)) + .withMessage("errorCode cannot be empty"); } @Test public void constructorWithErrorCodeAndHttpStatusWhenHttpStatusIsNullThenThrowIllegalArgumentException() { - assertThatCode(() -> new BearerTokenError(TEST_ERROR_CODE, null, null, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("httpStatus cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE, null, null, null)) + .withMessage("httpStatus cannot be null"); } @Test @@ -82,48 +82,52 @@ public void constructorWithAllParametersWhenAllParametersAreValidThenCreated() { @Test public void constructorWithAllParametersWhenErrorCodeIsNullThenThrowIllegalArgumentException() { - assertThatCode(() -> new BearerTokenError(null, TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("errorCode cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new BearerTokenError(null, TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE)) + .withMessage("errorCode cannot be empty"); } @Test public void constructorWithAllParametersWhenErrorCodeIsEmptyThenThrowIllegalArgumentException() { - assertThatCode(() -> new BearerTokenError("", TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("errorCode cannot be empty"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new BearerTokenError("", TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE)) + .withMessage("errorCode cannot be empty"); } @Test public void constructorWithAllParametersWhenHttpStatusIsNullThenThrowIllegalArgumentException() { - assertThatCode(() -> new BearerTokenError(TEST_ERROR_CODE, null, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("httpStatus cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE, null, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE)) + .withMessage("httpStatus cannot be null"); } @Test public void constructorWithAllParametersWhenErrorCodeIsInvalidThenThrowIllegalArgumentException() { - assertThatCode(() -> new BearerTokenError(TEST_ERROR_CODE + "\"", TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI, - TEST_SCOPE)).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("errorCode") - .hasMessageContaining("RFC 6750"); + assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE + "\"", + TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE)).withMessageContaining("errorCode") + .withMessageContaining("RFC 6750"); } @Test public void constructorWithAllParametersWhenDescriptionIsInvalidThenThrowIllegalArgumentException() { - assertThatCode(() -> new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, TEST_DESCRIPTION + "\"", TEST_URI, - TEST_SCOPE)).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("description") - .hasMessageContaining("RFC 6750"); + assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, + TEST_DESCRIPTION + "\"", TEST_URI, TEST_SCOPE)).withMessageContaining("description") + .withMessageContaining("RFC 6750"); } @Test public void constructorWithAllParametersWhenErrorUriIsInvalidThenThrowIllegalArgumentException() { - assertThatCode(() -> new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI + "\"", - TEST_SCOPE)).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("errorUri") - .hasMessageContaining("RFC 6750"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, TEST_DESCRIPTION, + TEST_URI + "\"", TEST_SCOPE)) + .withMessageContaining("errorUri").withMessageContaining("RFC 6750"); } @Test public void constructorWithAllParametersWhenScopeIsInvalidThenThrowIllegalArgumentException() { - assertThatCode(() -> new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI, - TEST_SCOPE + "\"")).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("scope") - .hasMessageContaining("RFC 6750"); + assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, + TEST_DESCRIPTION, TEST_URI, TEST_SCOPE + "\"")).withMessageContaining("scope") + .withMessageContaining("RFC 6750"); } } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTests.java index 3a77bbb8997..9808b19d5b7 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTests.java @@ -36,7 +36,7 @@ import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link BearerTokenAuthentication} @@ -90,14 +90,14 @@ public void getNameWhenTokenHasUsernameThenReturnsUsernameAttribute() { @Test public void constructorWhenTokenIsNullThenThrowsException() { - assertThatCode(() -> new BearerTokenAuthentication(this.principal, null, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("token cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenAuthentication(this.principal, null, null)) + .withMessageContaining("token cannot be null"); } @Test public void constructorWhenCredentialIsNullThenThrowsException() { - assertThatCode(() -> new BearerTokenAuthentication(null, this.token, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("principal cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new BearerTokenAuthentication(null, this.token, null)) + .withMessageContaining("principal cannot be null"); } @Test @@ -140,7 +140,7 @@ public void toStringWhenAttributesContainsURLThenDoesNotFail() throws Exception JSONObject attributes = new JSONObject(Collections.singletonMap("iss", new URL("https://idp.example.com"))); OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(attributes, null); BearerTokenAuthentication token = new BearerTokenAuthentication(principal, this.token, null); - assertThatCode(token::toString).doesNotThrowAnyException(); + token.toString(); } } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java index 2501d67a4ae..5c6e9c78a97 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java @@ -36,7 +36,7 @@ import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -76,8 +76,8 @@ public void authenticateWhenJwtDecodesThenAuthenticationHasAttributesContainedIn public void authenticateWhenJwtDecodeFailsThenRespondsWithInvalidToken() { BearerTokenAuthenticationToken token = this.authentication(); given(this.jwtDecoder.decode("token")).willThrow(BadJwtException.class); - assertThatCode(() -> this.provider.authenticate(token)) - .matches((failed) -> failed instanceof OAuth2AuthenticationException) + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.provider.authenticate(token)) .matches(errorCode(BearerTokenErrorCodes.INVALID_TOKEN)); } @@ -85,8 +85,9 @@ public void authenticateWhenJwtDecodeFailsThenRespondsWithInvalidToken() { public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGenericOne() { BearerTokenAuthenticationToken token = this.authentication(); given(this.jwtDecoder.decode(token.getToken())).willThrow(new BadJwtException("with \"invalid\" chars")); - assertThatCode(() -> this.provider.authenticate(token)).isInstanceOf(OAuth2AuthenticationException.class) - .hasFieldOrPropertyWithValue("error.description", "Invalid token"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.provider.authenticate(token)) + .satisfies((ex) -> assertThat(ex).hasFieldOrPropertyWithValue("error.description", "Invalid token")); } // gh-7785 @@ -94,7 +95,7 @@ public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGe public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() { BearerTokenAuthenticationToken token = this.authentication(); given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set")); - assertThatCode(() -> this.provider.authenticate(token)).isInstanceOf(AuthenticationException.class) + assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.provider.authenticate(token)) .isNotInstanceOf(OAuth2AuthenticationException.class); } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationTokenTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationTokenTests.java index 417c2354b30..dcd487b2d3b 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationTokenTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationTokenTests.java @@ -28,7 +28,7 @@ import org.springframework.security.oauth2.jwt.Jwt; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link JwtAuthenticationToken} @@ -54,8 +54,8 @@ public void getNameWhenJwtHasNoSubjectThenReturnsNull() { @Test public void constructorWhenJwtIsNullThenThrowsException() { - assertThatCode(() -> new JwtAuthenticationToken(null)).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("token cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new JwtAuthenticationToken(null)) + .withMessageContaining("token cannot be null"); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java index bd793b0f149..dbfeedbf422 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java @@ -41,7 +41,8 @@ import org.springframework.security.oauth2.jwt.JwtClaimNames; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -85,8 +86,9 @@ public void resolveWhenUsingUntrustedIssuerThenException() { "other", "issuers"); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Bearer " + this.jwt); - assertThatCode(() -> authenticationManagerResolver.resolve(request)) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(request)) + .withMessageContaining("Invalid issuer"); } @Test @@ -106,14 +108,16 @@ public void resolveWhenUsingExternalSourceThenRespondsToChanges() { Map authenticationManagers = new HashMap<>(); JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( authenticationManagers::get); - assertThatCode(() -> authenticationManagerResolver.resolve(request)) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(request)) + .withMessageContaining("Invalid issuer"); AuthenticationManager authenticationManager = mock(AuthenticationManager.class); authenticationManagers.put("trusted", authenticationManager); assertThat(authenticationManagerResolver.resolve(request)).isSameAs(authenticationManager); authenticationManagers.clear(); - assertThatCode(() -> authenticationManagerResolver.resolve(request)) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(request)) + .withMessageContaining("Invalid issuer"); } @Test @@ -122,8 +126,9 @@ public void resolveWhenBearerTokenMalformedThenException() { "trusted"); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Bearer jwt"); - assertThatCode(() -> authenticationManagerResolver.resolve(request)) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageNotContaining("Invalid issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(request)) + .withMessageNotContaining("Invalid issuer"); } @Test @@ -132,8 +137,9 @@ public void resolveWhenBearerTokenNoIssuerThenException() { "trusted"); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Bearer " + this.noIssuer); - assertThatCode(() -> authenticationManagerResolver.resolve(request)) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Missing issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(request)) + .withMessageContaining("Missing issuer"); } @Test @@ -142,22 +148,22 @@ public void resolveWhenBearerTokenEvilThenGenericException() { "trusted"); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Bearer " + this.evil); - assertThatCode(() -> authenticationManagerResolver.resolve(request)) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessage("Invalid issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(request)).withMessage("Invalid issuer"); } @Test public void constructorWhenNullOrEmptyIssuersThenException() { - assertThatCode(() -> new JwtIssuerAuthenticationManagerResolver((Collection) null)) - .isInstanceOf(IllegalArgumentException.class); - assertThatCode(() -> new JwtIssuerAuthenticationManagerResolver(Collections.emptyList())) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JwtIssuerAuthenticationManagerResolver((Collection) null)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JwtIssuerAuthenticationManagerResolver(Collections.emptyList())); } @Test public void constructorWhenNullAuthenticationManagerResolverThenException() { - assertThatCode(() -> new JwtIssuerAuthenticationManagerResolver((AuthenticationManagerResolver) null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JwtIssuerAuthenticationManagerResolver((AuthenticationManagerResolver) null)); } private String jwt(String claim, String value) { diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java index 12df1edc95d..7d290b39e2d 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java @@ -43,7 +43,8 @@ import org.springframework.security.oauth2.jwt.JwtClaimNames; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -86,8 +87,9 @@ public void resolveWhenUsingUntrustedIssuerThenException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( "other", "issuers"); MockServerWebExchange exchange = withBearerToken(this.jwt); - assertThatCode(() -> authenticationManagerResolver.resolve(exchange).block()) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(exchange).block()) + .withMessageContaining("Invalid issuer"); } @Test @@ -105,14 +107,16 @@ public void resolveWhenUsingExternalSourceThenRespondsToChanges() { Map authenticationManagers = new HashMap<>(); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( (issuer) -> Mono.justOrEmpty(authenticationManagers.get(issuer))); - assertThatCode(() -> authenticationManagerResolver.resolve(exchange).block()) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(exchange).block()) + .withMessageContaining("Invalid issuer"); ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class); authenticationManagers.put("trusted", authenticationManager); assertThat(authenticationManagerResolver.resolve(exchange).block()).isSameAs(authenticationManager); authenticationManagers.clear(); - assertThatCode(() -> authenticationManagerResolver.resolve(exchange).block()) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Invalid issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(exchange).block()) + .withMessageContaining("Invalid issuer"); } @Test @@ -120,8 +124,9 @@ public void resolveWhenBearerTokenMalformedThenException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( "trusted"); MockServerWebExchange exchange = withBearerToken("jwt"); - assertThatCode(() -> authenticationManagerResolver.resolve(exchange).block()) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageNotContaining("Invalid issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(exchange).block()) + .withMessageNotContaining("Invalid issuer"); } @Test @@ -129,8 +134,9 @@ public void resolveWhenBearerTokenNoIssuerThenException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( "trusted"); MockServerWebExchange exchange = withBearerToken(this.noIssuer); - assertThatCode(() -> authenticationManagerResolver.resolve(exchange).block()) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("Missing issuer"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(exchange).block()) + .withMessageContaining("Missing issuer"); } @Test @@ -138,23 +144,22 @@ public void resolveWhenBearerTokenEvilThenGenericException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( "trusted"); MockServerWebExchange exchange = withBearerToken(this.evil); - assertThatCode(() -> authenticationManagerResolver.resolve(exchange).block()) - .isInstanceOf(OAuth2AuthenticationException.class).hasMessage("Invalid token"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> authenticationManagerResolver.resolve(exchange).block()).withMessage("Invalid token"); } @Test public void constructorWhenNullOrEmptyIssuersThenException() { - assertThatCode(() -> new JwtIssuerReactiveAuthenticationManagerResolver((Collection) null)) - .isInstanceOf(IllegalArgumentException.class); - assertThatCode(() -> new JwtIssuerReactiveAuthenticationManagerResolver(Collections.emptyList())) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JwtIssuerReactiveAuthenticationManagerResolver((Collection) null)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JwtIssuerReactiveAuthenticationManagerResolver(Collections.emptyList())); } @Test public void constructorWhenNullAuthenticationManagerResolverThenException() { - assertThatCode( - () -> new JwtIssuerReactiveAuthenticationManagerResolver((ReactiveAuthenticationManagerResolver) null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> new JwtIssuerReactiveAuthenticationManagerResolver((ReactiveAuthenticationManagerResolver) null)); } private String jwt(String claim, String value) { diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java index cb1dddb456e..bfafa2cfc36 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java @@ -36,7 +36,8 @@ import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -63,8 +64,7 @@ public void setup() { @Test public void constructorWhenJwtDecoderNullThenIllegalArgumentException() { this.jwtDecoder = null; - assertThatCode(() -> new JwtReactiveAuthenticationManager(this.jwtDecoder)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new JwtReactiveAuthenticationManager(this.jwtDecoder)); } @Test @@ -84,8 +84,8 @@ public void authenticateWhenEmptyJwtThenEmpty() { public void authenticateWhenJwtExceptionThenOAuth2AuthenticationException() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(any())).willReturn(Mono.error(new BadJwtException("Oops"))); - assertThatCode(() -> this.manager.authenticate(token).block()) - .isInstanceOf(OAuth2AuthenticationException.class); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.manager.authenticate(token).block()); } // gh-7549 @@ -93,8 +93,9 @@ public void authenticateWhenJwtExceptionThenOAuth2AuthenticationException() { public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGenericOne() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(token.getToken())).willThrow(new BadJwtException("with \"invalid\" chars")); - assertThatCode(() -> this.manager.authenticate(token).block()).isInstanceOf(OAuth2AuthenticationException.class) - .hasFieldOrPropertyWithValue("error.description", "Invalid token"); + assertThatExceptionOfType(OAuth2AuthenticationException.class) + .isThrownBy(() -> this.manager.authenticate(token).block()) + .satisfies((ex) -> assertThat(ex).hasFieldOrPropertyWithValue("error.description", "Invalid token")); } // gh-7785 @@ -102,7 +103,8 @@ public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGe public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set")); - assertThatCode(() -> this.manager.authenticate(token).block()).isInstanceOf(AuthenticationException.class) + assertThatExceptionOfType(AuthenticationException.class) + .isThrownBy(() -> this.manager.authenticate(token).block()) .isNotInstanceOf(OAuth2AuthenticationException.class); } @@ -110,7 +112,7 @@ public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() public void authenticateWhenNotJwtExceptionThenPropagates() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(any())).willReturn(Mono.error(new RuntimeException("Oops"))); - assertThatCode(() -> this.manager.authenticate(token).block()).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.manager.authenticate(token).block()); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java index 85ec86bdb5d..950dbd1579e 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java @@ -35,7 +35,8 @@ import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -91,13 +92,13 @@ public void authenticateWhenIntrospectionEndpointThrowsExceptionThenInvalidToken OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class); given(introspector.introspect(any())).willThrow(new OAuth2IntrospectionException("with \"invalid\" chars")); OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector); - assertThatCode(() -> provider.authenticate(new BearerTokenAuthenticationToken("token"))) - .isInstanceOf(AuthenticationServiceException.class); + assertThatExceptionOfType(AuthenticationServiceException.class) + .isThrownBy(() -> provider.authenticate(new BearerTokenAuthenticationToken("token"))); } @Test public void constructorWhenIntrospectionClientIsNullThenIllegalArgumentException() { - assertThatCode(() -> new OpaqueTokenAuthenticationProvider(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new OpaqueTokenAuthenticationProvider(null)); } } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java index a0fb4238351..b5417853eaa 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java @@ -36,7 +36,8 @@ import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -93,14 +94,13 @@ public void authenticateWhenIntrospectionEndpointThrowsExceptionThenInvalidToken given(introspector.introspect(any())) .willReturn(Mono.error(new OAuth2IntrospectionException("with \"invalid\" chars"))); OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector); - assertThatCode(() -> provider.authenticate(new BearerTokenAuthenticationToken("token")).block()) - .isInstanceOf(AuthenticationServiceException.class); + assertThatExceptionOfType(AuthenticationServiceException.class) + .isThrownBy(() -> provider.authenticate(new BearerTokenAuthenticationToken("token")).block()); } @Test public void constructorWhenIntrospectionClientIsNullThenIllegalArgumentException() { - assertThatCode(() -> new OpaqueTokenReactiveAuthenticationManager(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new OpaqueTokenReactiveAuthenticationManager(null)); } } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java index 4e858e8c7d3..be83779eed0 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java @@ -43,8 +43,8 @@ import org.springframework.web.client.RestOperations; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; 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.BDDMockito.given; @@ -126,8 +126,8 @@ public void introspectWhenBadClientCredentialsThenError() throws IOException { String introspectUri = server.url("/introspect").toString(); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(introspectUri, CLIENT_ID, "wrong"); - assertThatCode(() -> introspectionClient.introspect("token")) - .isInstanceOf(OAuth2IntrospectionException.class); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token")); } } @@ -137,8 +137,8 @@ public void introspectWhenInactiveTokenThenInvalidToken() { OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INACTIVE); - assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class) - .extracting("message").isEqualTo("Provided token isn't active"); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token")).withMessage("Provided token isn't active"); } @Test @@ -167,8 +167,8 @@ public void introspectWhenIntrospectionEndpointThrowsExceptionThenInvalidToken() restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) .willThrow(new IllegalStateException("server was unresponsive")); - assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class) - .extracting("message").isEqualTo("server was unresponsive"); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token")).withMessage("server was unresponsive"); } @Test @@ -177,7 +177,8 @@ public void introspectWhenIntrospectionEndpointReturnsMalformedResponseThenInval OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(response("malformed")); - assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token")); } @Test @@ -186,7 +187,8 @@ public void introspectWhenIntrospectionTokenReturnsInvalidResponseThenInvalidTok OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INVALID); - assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token")); } @Test @@ -195,7 +197,8 @@ public void introspectWhenIntrospectionTokenReturnsMalformedIssuerResponseThenIn OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_ISSUER); - assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token")); } // gh-7563 @@ -213,26 +216,26 @@ public void introspectWhenIntrospectionTokenReturnsMalformedScopeThenEmptyAuthor @Test public void constructorWhenIntrospectionUriIsNullThenIllegalArgumentException() { - assertThatCode(() -> new NimbusOpaqueTokenIntrospector(null, CLIENT_ID, CLIENT_SECRET)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new NimbusOpaqueTokenIntrospector(null, CLIENT_ID, CLIENT_SECRET)); } @Test public void constructorWhenClientIdIsNullThenIllegalArgumentException() { - assertThatCode(() -> new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, null, CLIENT_SECRET)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, null, CLIENT_SECRET)); } @Test public void constructorWhenClientSecretIsNullThenIllegalArgumentException() { - assertThatCode(() -> new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, CLIENT_ID, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, CLIENT_ID, null)); } @Test public void constructorWhenRestOperationsIsNullThenIllegalArgumentException() { - assertThatCode(() -> new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, null)); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java index 8d452e608ca..9e9036a964e 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java @@ -41,7 +41,8 @@ import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +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.spy; @@ -104,8 +105,9 @@ public void authenticateWhenBadClientCredentialsThenAuthenticationException() th String introspectUri = server.url("/introspect").toString(); NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector( introspectUri, CLIENT_ID, "wrong"); - assertThatCode(() -> introspectionClient.introspect("token").block()) - .isInstanceOf(OAuth2IntrospectionException.class); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token").block()); + } } @@ -114,9 +116,9 @@ public void authenticateWhenInactiveTokenThenInvalidToken() { WebClient webClient = mockResponse(INACTIVE_RESPONSE); NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector( INTROSPECTION_URL, webClient); - assertThatCode(() -> introspectionClient.introspect("token").block()) - .isInstanceOf(BadOpaqueTokenException.class).extracting("message") - .isEqualTo("Provided token isn't active"); + assertThatExceptionOfType(BadOpaqueTokenException.class) + .isThrownBy(() -> introspectionClient.introspect("token").block()) + .withMessage("Provided token isn't active"); } @Test @@ -141,9 +143,9 @@ public void authenticateWhenIntrospectionEndpointThrowsExceptionThenInvalidToken WebClient webClient = mockResponse(new IllegalStateException("server was unresponsive")); NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector( INTROSPECTION_URL, webClient); - assertThatCode(() -> introspectionClient.introspect("token").block()) - .isInstanceOf(OAuth2IntrospectionException.class).extracting("message") - .isEqualTo("server was unresponsive"); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token").block()) + .withMessage("server was unresponsive"); } @Test @@ -151,8 +153,8 @@ public void authenticateWhenIntrospectionEndpointReturnsMalformedResponseThenInv WebClient webClient = mockResponse("malformed"); NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector( INTROSPECTION_URL, webClient); - assertThatCode(() -> introspectionClient.introspect("token").block()) - .isInstanceOf(OAuth2IntrospectionException.class); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token").block()); } @Test @@ -160,8 +162,8 @@ public void authenticateWhenIntrospectionTokenReturnsInvalidResponseThenInvalidT WebClient webClient = mockResponse(INVALID_RESPONSE); NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector( INTROSPECTION_URL, webClient); - assertThatCode(() -> introspectionClient.introspect("token").block()) - .isInstanceOf(OAuth2IntrospectionException.class); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token").block()); } @Test @@ -169,32 +171,32 @@ public void authenticateWhenIntrospectionTokenReturnsMalformedIssuerResponseThen WebClient webClient = mockResponse(MALFORMED_ISSUER_RESPONSE); NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector( INTROSPECTION_URL, webClient); - assertThatCode(() -> introspectionClient.introspect("token").block()) - .isInstanceOf(OAuth2IntrospectionException.class); + assertThatExceptionOfType(OAuth2IntrospectionException.class) + .isThrownBy(() -> introspectionClient.introspect("token").block()); } @Test public void constructorWhenIntrospectionUriIsEmptyThenIllegalArgumentException() { - assertThatCode(() -> new NimbusReactiveOpaqueTokenIntrospector("", CLIENT_ID, CLIENT_SECRET)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new NimbusReactiveOpaqueTokenIntrospector("", CLIENT_ID, CLIENT_SECRET)); } @Test public void constructorWhenClientIdIsEmptyThenIllegalArgumentException() { - assertThatCode(() -> new NimbusReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, "", CLIENT_SECRET)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new NimbusReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, "", CLIENT_SECRET)); } @Test public void constructorWhenClientSecretIsNullThenIllegalArgumentException() { - assertThatCode(() -> new NimbusReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, CLIENT_ID, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new NimbusReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, CLIENT_ID, null)); } @Test public void constructorWhenRestOperationsIsNullThenIllegalArgumentException() { - assertThatCode(() -> new NimbusReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new NimbusReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, null)); } private WebClient mockResponse(String response) { diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionAuthenticatedPrincipalTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionAuthenticatedPrincipalTests.java index 705683350d0..bb96cb17ec3 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionAuthenticatedPrincipalTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionAuthenticatedPrincipalTests.java @@ -31,7 +31,7 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2IntrospectionAuthenticatedPrincipal} @@ -108,10 +108,10 @@ public class OAuth2IntrospectionAuthenticatedPrincipalTests { @Test public void constructorWhenAttributesIsNullOrEmptyThenIllegalArgumentException() { - assertThatCode(() -> new OAuth2IntrospectionAuthenticatedPrincipal(null, AUTHORITIES)) - .isInstanceOf(IllegalArgumentException.class); - assertThatCode(() -> new OAuth2IntrospectionAuthenticatedPrincipal(Collections.emptyMap(), AUTHORITIES)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2IntrospectionAuthenticatedPrincipal(null, AUTHORITIES)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new OAuth2IntrospectionAuthenticatedPrincipal(Collections.emptyMap(), AUTHORITIES)); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPointTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPointTests.java index 9b7d1b474b0..93e112e2681 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPointTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPointTests.java @@ -28,7 +28,6 @@ import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; /** * Tests for {@link BearerTokenAuthenticationEntryPoint}. @@ -150,7 +149,7 @@ public void commenceWhenInsufficientScopeAndRealmSetThenStatus403AndHeaderWithEr @Test public void setRealmNameWhenNullRealmNameThenNoExceptionThrown() { - assertThatCode(() -> this.authenticationEntryPoint.setRealmName(null)).doesNotThrowAnyException(); + this.authenticationEntryPoint.setRealmName(null); } } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java index 8607a3b41f2..d7fd4a091cc 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java @@ -42,7 +42,7 @@ import org.springframework.security.web.authentication.AuthenticationFailureHandler; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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.verify; @@ -157,30 +157,29 @@ public void doFilterWhenAuthenticationFailsWithCustomHandlerThenPropagatesError( @Test public void setAuthenticationEntryPointWhenNullThenThrowsException() { BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(this.authenticationManager); - assertThatCode(() -> filter.setAuthenticationEntryPoint(null)).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("authenticationEntryPoint cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> filter.setAuthenticationEntryPoint(null)) + .withMessageContaining("authenticationEntryPoint cannot be null"); } @Test public void setBearerTokenResolverWhenNullThenThrowsException() { BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(this.authenticationManager); - assertThatCode(() -> filter.setBearerTokenResolver(null)).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("bearerTokenResolver cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> filter.setBearerTokenResolver(null)) + .withMessageContaining("bearerTokenResolver cannot be null"); } @Test public void constructorWhenNullAuthenticationManagerThenThrowsException() { - assertThatCode(() -> new BearerTokenAuthenticationFilter((AuthenticationManager) null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("authenticationManager cannot be null"); + assertThatIllegalArgumentException() + .isThrownBy(() -> new BearerTokenAuthenticationFilter((AuthenticationManager) null)) + .withMessageContaining("authenticationManager cannot be null"); } @Test public void constructorWhenNullAuthenticationManagerResolverThenThrowsException() { - assertThatCode( + assertThatIllegalArgumentException().isThrownBy( () -> new BearerTokenAuthenticationFilter((AuthenticationManagerResolver) null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("authenticationManagerResolver cannot be null"); + .withMessageContaining("authenticationManagerResolver cannot be null"); } private BearerTokenAuthenticationFilter addMocks(BearerTokenAuthenticationFilter filter) { diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolverTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolverTests.java index f1e0d6621f8..e80ec201af2 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolverTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolverTests.java @@ -25,7 +25,7 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link DefaultBearerTokenResolver}. @@ -93,16 +93,16 @@ public void resolveWhenHeaderWithWrongSchemeIsPresentThenTokenIsNotResolved() { public void resolveWhenHeaderWithMissingTokenIsPresentThenAuthenticationExceptionIsThrown() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Bearer "); - assertThatCode(() -> this.resolver.resolve(request)).isInstanceOf(OAuth2AuthenticationException.class) - .hasMessageContaining(("Bearer token is malformed")); + assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request)) + .withMessageContaining(("Bearer token is malformed")); } @Test public void resolveWhenHeaderWithInvalidCharactersIsPresentThenAuthenticationExceptionIsThrown() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Bearer an\"invalid\"token"); - assertThatCode(() -> this.resolver.resolve(request)).isInstanceOf(OAuth2AuthenticationException.class) - .hasMessageContaining(("Bearer token is malformed")); + assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request)) + .withMessageContaining(("Bearer token is malformed")); } @Test @@ -112,8 +112,8 @@ public void resolveWhenValidHeaderIsPresentTogetherWithFormParameterThenAuthenti request.setMethod("POST"); request.setContentType("application/x-www-form-urlencoded"); request.addParameter("access_token", TEST_TOKEN); - assertThatCode(() -> this.resolver.resolve(request)).isInstanceOf(OAuth2AuthenticationException.class) - .hasMessageContaining("Found multiple bearer tokens in the request"); + assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request)) + .withMessageContaining("Found multiple bearer tokens in the request"); } @Test @@ -122,16 +122,16 @@ public void resolveWhenValidHeaderIsPresentTogetherWithQueryParameterThenAuthent request.addHeader("Authorization", "Bearer " + TEST_TOKEN); request.setMethod("GET"); request.addParameter("access_token", TEST_TOKEN); - assertThatCode(() -> this.resolver.resolve(request)).isInstanceOf(OAuth2AuthenticationException.class) - .hasMessageContaining("Found multiple bearer tokens in the request"); + assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request)) + .withMessageContaining("Found multiple bearer tokens in the request"); } @Test public void resolveWhenRequestContainsTwoAccessTokenParametersThenAuthenticationExceptionIsThrown() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("access_token", "token1", "token2"); - assertThatCode(() -> this.resolver.resolve(request)).isInstanceOf(OAuth2AuthenticationException.class) - .hasMessageContaining("Found multiple bearer tokens in the request"); + assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request)) + .withMessageContaining("Found multiple bearer tokens in the request"); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolverTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolverTests.java index 69365fb8794..3db97ecd6dd 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolverTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolverTests.java @@ -21,7 +21,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link HeaderBearerTokenResolver} @@ -38,14 +38,14 @@ public class HeaderBearerTokenResolverTests { @Test public void constructorWhenHeaderNullThenThrowIllegalArgumentException() { - assertThatCode(() -> new HeaderBearerTokenResolver(null)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("header cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new HeaderBearerTokenResolver(null)) + .withMessage("header cannot be empty"); } @Test public void constructorWhenHeaderEmptyThenThrowIllegalArgumentException() { - assertThatCode(() -> new HeaderBearerTokenResolver("")).isInstanceOf(IllegalArgumentException.class) - .hasMessage("header cannot be empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new HeaderBearerTokenResolver("")) + .withMessage("header cannot be empty"); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandlerTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandlerTests.java index cbfc5e942b0..04686c34096 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandlerTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandlerTests.java @@ -30,7 +30,6 @@ import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; /** * Tests for {@link BearerTokenAccessDeniedHandlerTests} @@ -85,7 +84,7 @@ public void handleWhenOAuth2AuthenticatedThenStatus403AndAuthHeaderWithInsuffici @Test public void setRealmNameWhenNullRealmNameThenNoExceptionThrown() { - assertThatCode(() -> this.accessDeniedHandler.setRealmName(null)).doesNotThrowAnyException(); + this.accessDeniedHandler.setRealmName(null); } static class TestingOAuth2TokenAuthenticationToken diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandlerTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandlerTests.java index 79980fb63cc..1b6ce1662c6 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandlerTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandlerTests.java @@ -33,7 +33,6 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -86,7 +85,7 @@ public void handleWhenOAuth2AuthenticatedThenStatus403AndAuthHeaderWithInsuffici @Test public void setRealmNameWhenNullRealmNameThenNoExceptionThrown() { - assertThatCode(() -> this.accessDeniedHandler.setRealmName(null)).doesNotThrowAnyException(); + this.accessDeniedHandler.setRealmName(null); } static class TestingOAuth2TokenAuthenticationToken diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverterTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverterTests.java index 21e6bbd4dd2..c050bf5772b 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverterTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverterTests.java @@ -31,8 +31,7 @@ import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Rob Winch @@ -80,12 +79,13 @@ public void resolveWhenCustomDefinedHeaderIsValidAndPresentThenTokenIsResolved() public void resolveWhenValidHeaderIsEmptyStringThenTokenIsResolved() { MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION, "Bearer "); - OAuth2AuthenticationException expected = catchThrowableOfType(() -> convertToToken(request), - OAuth2AuthenticationException.class); - BearerTokenError error = (BearerTokenError) expected.getError(); - assertThat(error.getErrorCode()).isEqualTo(BearerTokenErrorCodes.INVALID_TOKEN); - assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); - assertThat(error.getHttpStatus()).isEqualTo(HttpStatus.UNAUTHORIZED); + assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> convertToToken(request)) + .satisfies((ex) -> { + BearerTokenError error = (BearerTokenError) ex.getError(); + assertThat(error.getErrorCode()).isEqualTo(BearerTokenErrorCodes.INVALID_TOKEN); + assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); + assertThat(error.getHttpStatus()).isEqualTo(HttpStatus.UNAUTHORIZED); + }); } @Test @@ -112,16 +112,16 @@ public void resolveWhenHeaderWithWrongSchemeIsPresentThenTokenIsNotResolved() { public void resolveWhenHeaderWithMissingTokenIsPresentThenAuthenticationExceptionIsThrown() { MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION, "Bearer "); - assertThatCode(() -> convertToToken(request)).isInstanceOf(OAuth2AuthenticationException.class) - .hasMessageContaining(("Bearer token is malformed")); + assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> convertToToken(request)) + .withMessageContaining(("Bearer token is malformed")); } @Test public void resolveWhenHeaderWithInvalidCharactersIsPresentThenAuthenticationExceptionIsThrown() { MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION, "Bearer an\"invalid\"token"); - assertThatCode(() -> convertToToken(request)).isInstanceOf(OAuth2AuthenticationException.class) - .hasMessageContaining(("Bearer token is malformed")); + assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> convertToToken(request)) + .withMessageContaining(("Bearer token is malformed")); } // gh-8865 @@ -129,15 +129,15 @@ public void resolveWhenHeaderWithInvalidCharactersIsPresentThenAuthenticationExc public void resolveWhenHeaderWithInvalidCharactersIsPresentAndNotSubscribedThenNoneExceptionIsThrown() { MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION, "Bearer an\"invalid\"token"); - assertThatCode(() -> this.converter.convert(MockServerWebExchange.from(request))).doesNotThrowAnyException(); + this.converter.convert(MockServerWebExchange.from(request)); } @Test public void resolveWhenValidHeaderIsPresentTogetherWithQueryParameterThenAuthenticationExceptionIsThrown() { MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest.get("/") .queryParam("access_token", TEST_TOKEN).header(HttpHeaders.AUTHORIZATION, "Bearer " + TEST_TOKEN); - assertThatCode(() -> convertToToken(request)).isInstanceOf(OAuth2AuthenticationException.class) - .hasMessageContaining("Found multiple bearer tokens in the request"); + assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> convertToToken(request)) + .withMessageContaining("Found multiple bearer tokens in the request"); } @Test @@ -153,12 +153,13 @@ public void resolveWhenQueryParameterIsPresentAndSupportedThenTokenIsResolved() public void resolveWhenQueryParameterIsEmptyAndSupportedThenOAuth2AuthenticationException() { this.converter.setAllowUriQueryParameter(true); MockServerHttpRequest.BaseBuilder request = MockServerHttpRequest.get("/").queryParam("access_token", ""); - OAuth2AuthenticationException expected = catchThrowableOfType(() -> convertToToken(request), - OAuth2AuthenticationException.class); - BearerTokenError error = (BearerTokenError) expected.getError(); - assertThat(error.getErrorCode()).isEqualTo(BearerTokenErrorCodes.INVALID_TOKEN); - assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); - assertThat(error.getHttpStatus()).isEqualTo(HttpStatus.UNAUTHORIZED); + assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> convertToToken(request)) + .satisfies((ex) -> { + BearerTokenError error = (BearerTokenError) ex.getError(); + assertThat(error.getErrorCode()).isEqualTo(BearerTokenErrorCodes.INVALID_TOKEN); + assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); + assertThat(error.getHttpStatus()).isEqualTo(HttpStatus.UNAUTHORIZED); + }); } @Test diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AnonymousPayloadInterceptorTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AnonymousPayloadInterceptorTests.java index d6a5dbe45de..67465ccc210 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AnonymousPayloadInterceptorTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AnonymousPayloadInterceptorTests.java @@ -33,7 +33,7 @@ import org.springframework.security.rsocket.api.PayloadExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rob Winch @@ -54,28 +54,28 @@ public void setup() { @Test public void constructorKeyWhenKeyNullThenException() { String key = null; - assertThatCode(() -> new AnonymousPayloadInterceptor(key)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousPayloadInterceptor(key)); } @Test public void constructorKeyPrincipalAuthoritiesWhenKeyNullThenException() { String key = null; - assertThatCode(() -> new AnonymousPayloadInterceptor(key, "principal", - AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousPayloadInterceptor(key, "principal", + AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); } @Test public void constructorKeyPrincipalAuthoritiesWhenPrincipalNullThenException() { Object principal = null; - assertThatCode(() -> new AnonymousPayloadInterceptor("key", principal, - AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousPayloadInterceptor("key", principal, + AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); } @Test public void constructorKeyPrincipalAuthoritiesWhenAuthoritiesNullThenException() { List authorities = null; - assertThatCode(() -> new AnonymousPayloadInterceptor("key", "principal", authorities)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AnonymousPayloadInterceptor("key", "principal", authorities)); } @Test diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java index a448aeaf96d..03fe470bd2d 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java @@ -53,7 +53,7 @@ import org.springframework.util.MimeTypeUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -76,7 +76,7 @@ public class AuthenticationPayloadInterceptorTests { @Test public void constructorWhenAuthenticationManagerNullThenException() { - assertThatCode(() -> new AuthenticationPayloadInterceptor(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new AuthenticationPayloadInterceptor(null)); } @Test diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocketTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocketTests.java index bae021271c9..3a153b8c615 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocketTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocketTests.java @@ -51,7 +51,8 @@ import org.springframework.util.MimeTypeUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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.BDDMockito.given; @@ -94,22 +95,22 @@ public class PayloadInterceptorRSocketTests { public void constructorWhenNullDelegateThenException() { this.delegate = null; List interceptors = Arrays.asList(this.interceptor); - assertThatCode(() -> new PayloadInterceptorRSocket(this.delegate, interceptors, this.metadataMimeType, - this.dataMimeType)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new PayloadInterceptorRSocket(this.delegate, interceptors, + this.metadataMimeType, this.dataMimeType)); } @Test public void constructorWhenNullInterceptorsThenException() { List interceptors = null; - assertThatCode(() -> new PayloadInterceptorRSocket(this.delegate, interceptors, this.metadataMimeType, - this.dataMimeType)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new PayloadInterceptorRSocket(this.delegate, interceptors, + this.metadataMimeType, this.dataMimeType)); } @Test public void constructorWhenEmptyInterceptorsThenException() { List interceptors = Collections.emptyList(); - assertThatCode(() -> new PayloadInterceptorRSocket(this.delegate, interceptors, this.metadataMimeType, - this.dataMimeType)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new PayloadInterceptorRSocket(this.delegate, interceptors, + this.metadataMimeType, this.dataMimeType)); } // single interceptor @@ -177,7 +178,8 @@ public void requestResponseWhenInterceptorErrorsThenDelegateNotInvoked() { given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected)); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); - assertThatCode(() -> interceptor.requestResponse(this.payload).block()).isEqualTo(expected); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> interceptor.requestResponse(this.payload).block()).isEqualTo(expected); verify(this.interceptor).intercept(this.exchange.capture(), any()); assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload); verifyZeroInteractions(this.delegate); @@ -376,7 +378,8 @@ public void fireAndForgetWhenInterceptor1ErrorsThenInterceptor2AndDelegateNotInv given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected)); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType); - assertThatCode(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected); verify(this.interceptor).intercept(this.exchange.capture(), any()); assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload); verifyZeroInteractions(this.interceptor2); @@ -390,7 +393,8 @@ public void fireAndForgetWhenInterceptor2ErrorsThenInterceptor2AndDelegateNotInv given(this.interceptor2.intercept(any(), any())).willReturn(Mono.error(expected)); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType); - assertThatCode(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected); verify(this.interceptor).intercept(this.exchange.capture(), any()); assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload); verify(this.interceptor2).intercept(any(), any()); diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorTests.java index 13a2e87b025..4c3722a1e97 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorTests.java @@ -43,7 +43,7 @@ import org.springframework.security.rsocket.api.PayloadInterceptor; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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.times; @@ -83,25 +83,28 @@ public void setup() { @Test public void constructorWhenNullDelegateThenException() { this.delegate = null; - assertThatCode(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors)); } @Test public void constructorWhenNullInterceptorsThenException() { this.interceptors = null; - assertThatCode(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors)); } @Test public void constructorWhenEmptyInterceptorsThenException() { this.interceptors = Collections.emptyList(); - assertThatCode(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PayloadSocketAcceptor(this.delegate, this.interceptors)); } @Test public void acceptWhenDataMimeTypeNullThenException() { - assertThatCode(() -> this.acceptor.accept(this.setupPayload, this.rSocket).block()) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.acceptor.accept(this.setupPayload, this.rSocket).block()); } @Test diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/OpenSamlInitializationServiceTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/OpenSamlInitializationServiceTests.java index 85bb9bbb487..7e7cb5a0d10 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/OpenSamlInitializationServiceTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/OpenSamlInitializationServiceTests.java @@ -23,7 +23,7 @@ import org.springframework.security.saml2.Saml2Exception; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link OpenSamlInitializationService} @@ -37,8 +37,9 @@ public void initializeWhenInvokedMultipleTimesThenInitializesOnce() { OpenSamlInitializationService.initialize(); XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); assertThat(registry.getParserPool()).isNotNull(); - assertThatCode(() -> OpenSamlInitializationService.requireInitialize((r) -> { - })).isInstanceOf(Saml2Exception.class).hasMessageContaining("OpenSAML was already initialized previously"); + assertThatExceptionOfType(Saml2Exception.class) + .isThrownBy(() -> OpenSamlInitializationService.requireInitialize((r) -> { + })).withMessageContaining("OpenSAML was already initialized previously"); } } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/DefaultSaml2AuthenticatedPrincipalTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/DefaultSaml2AuthenticatedPrincipalTests.java index 8cd0297599b..c91651ef245 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/DefaultSaml2AuthenticatedPrincipalTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/DefaultSaml2AuthenticatedPrincipalTests.java @@ -26,7 +26,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; public class DefaultSaml2AuthenticatedPrincipalTests { @@ -43,14 +43,14 @@ public void createDefaultSaml2AuthenticatedPrincipal() { public void createDefaultSaml2AuthenticatedPrincipalWhenNameNullThenException() { Map> attributes = new LinkedHashMap<>(); attributes.put("email", Arrays.asList("john.doe@example.com", "doe.john@example.com")); - assertThatCode(() -> new DefaultSaml2AuthenticatedPrincipal(null, attributes)) - .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("name cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new DefaultSaml2AuthenticatedPrincipal(null, attributes)) + .withMessageContaining("name cannot be null"); } @Test public void createDefaultSaml2AuthenticatedPrincipalWhenAttributesNullThenException() { - assertThatCode(() -> new DefaultSaml2AuthenticatedPrincipal("user", null)) - .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("attributes cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new DefaultSaml2AuthenticatedPrincipal("user", null)) + .withMessageContaining("attributes cannot be null"); } @Test diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java index a0095ca7a91..6669b6af479 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java @@ -69,7 +69,7 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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.atLeastOnce; @@ -397,16 +397,14 @@ public void authenticateWhenValidationContextCustomizedThenUsers() { @Test public void setValidationContextConverterWhenNullThenIllegalArgument() { - assertThatCode(() -> this.provider.setValidationContextConverter(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.provider.setValidationContextConverter(null)); } @Test public void setConditionValidatorsWhenNullOrEmptyThenIllegalArgument() { - assertThatCode(() -> this.provider.setConditionValidators(null)).isInstanceOf(IllegalArgumentException.class); - - assertThatCode(() -> this.provider.setConditionValidators(Collections.emptyList())) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.provider.setConditionValidators(null)); + assertThatIllegalArgumentException() + .isThrownBy(() -> this.provider.setConditionValidators(Collections.emptyList())); } private T build(QName qName) { diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java index 7884be64e34..f3fe17c471e 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java @@ -39,7 +39,7 @@ import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -189,8 +189,7 @@ public void createRedirectAuthenticationRequestWhenAuthnRequestConsumerThenUses( @Test public void setAuthnRequestConsumerResolverWhenNullThenException() { - assertThatCode(() -> this.factory.setAuthnRequestConsumerResolver(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.factory.setAuthnRequestConsumerResolver(null)); } @Test diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests.java index c0c10518827..30ce7e32616 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests.java @@ -30,7 +30,7 @@ import org.springframework.security.saml2.Saml2Exception; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests { @@ -63,17 +63,18 @@ public void setup() { public void readWhenMissingIDPSSODescriptorThenException() { MockClientHttpResponse response = new MockClientHttpResponse( (String.format(ENTITY_DESCRIPTOR_TEMPLATE, "")).getBytes(), HttpStatus.OK); - assertThatCode(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) - .isInstanceOf(Saml2Exception.class) - .hasMessageContaining("Metadata response is missing the necessary IDPSSODescriptor element"); + assertThatExceptionOfType(Saml2Exception.class) + .isThrownBy(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) + .withMessageContaining("Metadata response is missing the necessary IDPSSODescriptor element"); } @Test public void readWhenMissingVerificationKeyThenException() { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, "")); MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); - assertThatCode(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) - .isInstanceOf(Saml2Exception.class).hasMessageContaining( + assertThatExceptionOfType(Saml2Exception.class) + .isThrownBy(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) + .withMessageContaining( "Metadata response is missing verification certificates, necessary for verifying SAML assertions"); } @@ -82,8 +83,9 @@ public void readWhenMissingSingleSignOnServiceThenException() { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"signing\""))); MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); - assertThatCode(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) - .isInstanceOf(Saml2Exception.class).hasMessageContaining( + assertThatExceptionOfType(Saml2Exception.class) + .isThrownBy(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) + .withMessageContaining( "Metadata response is missing a SingleSignOnService, necessary for sending AuthnRequests"); } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationsTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationsTests.java index 52c08c80aea..3c64c8e6536 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationsTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationsTests.java @@ -23,7 +23,7 @@ import org.springframework.security.saml2.Saml2Exception; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link RelyingPartyRegistration} @@ -106,8 +106,8 @@ public void fromMetadataLocationWhenUnresolvableThenSaml2Exception() throws Exce server.enqueue(new MockResponse().setBody(IDP_SSO_DESCRIPTOR_PAYLOAD).setResponseCode(200)); String url = server.url("/").toString(); server.shutdown(); - assertThatCode(() -> RelyingPartyRegistrations.fromMetadataLocation(url)) - .isInstanceOf(Saml2Exception.class); + assertThatExceptionOfType(Saml2Exception.class) + .isThrownBy(() -> RelyingPartyRegistrations.fromMetadataLocation(url)); } } @@ -116,8 +116,8 @@ public void fromMetadataLocationWhenMalformedResponseThenSaml2Exception() throws try (MockWebServer server = new MockWebServer()) { server.enqueue(new MockResponse().setBody("malformed").setResponseCode(200)); String url = server.url("/").toString(); - assertThatCode(() -> RelyingPartyRegistrations.fromMetadataLocation(url)) - .isInstanceOf(Saml2Exception.class); + assertThatExceptionOfType(Saml2Exception.class) + .isThrownBy(() -> RelyingPartyRegistrations.fromMetadataLocation(url)); } } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java index a5eac420d25..6079de5bcb9 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java @@ -39,7 +39,7 @@ import org.springframework.web.util.UriUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -185,13 +185,13 @@ public void doFilterWhenCustomAuthenticationRequestFactoryThenUses() throws Exce @Test public void setRequestMatcherWhenNullThenException() { Saml2WebSsoAuthenticationRequestFilter filter = new Saml2WebSsoAuthenticationRequestFilter(this.repository); - assertThatCode(() -> filter.setRedirectMatcher(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> filter.setRedirectMatcher(null)); } @Test public void setAuthenticationRequestFactoryWhenNullThenException() { Saml2WebSsoAuthenticationRequestFilter filter = new Saml2WebSsoAuthenticationRequestFilter(this.repository); - assertThatCode(() -> filter.setAuthenticationRequestFactory(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> filter.setAuthenticationRequestFactory(null)); } @Test diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolverTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolverTests.java index 9f916f59740..41418978c4f 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolverTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolverTests.java @@ -25,7 +25,7 @@ import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultRelyingPartyRegistrationResolver} @@ -71,8 +71,7 @@ public void resolveWhenRequestIsMissingRegistrationIdThenNull() { @Test public void constructorWhenNullRelyingPartyRegistrationThenIllegalArgument() { - assertThatCode(() -> new DefaultRelyingPartyRegistrationResolver(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new DefaultRelyingPartyRegistrationResolver(null)); } } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolverTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolverTests.java index f39b50ff4e9..1905a0db3bd 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolverTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolverTests.java @@ -25,7 +25,7 @@ import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultSaml2AuthenticationRequestContextResolver} @@ -94,8 +94,7 @@ public void resolveWhenAssertionConsumerServiceUrlTemplateContainsBaseUrlThenRes @Test public void resolveWhenRelyingPartyNullThenException() { - assertThatCode(() -> this.authenticationRequestContextResolver.resolve(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.authenticationRequestContextResolver.resolve(null)); } } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java index a3a969b2f77..91038de6ae8 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java @@ -37,7 +37,7 @@ import org.springframework.web.util.UriUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -102,7 +102,7 @@ public void convertWhenGetRequestThenInflates() { @Test public void constructorWhenResolverIsNullThenIllegalArgument() { - assertThatCode(() -> new Saml2AuthenticationTokenConverter(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new Saml2AuthenticationTokenConverter(null)); } @Test diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java index 602e3dba48d..12e024a3a14 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java @@ -31,7 +31,7 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -117,7 +117,7 @@ public void doFilterWhenCustomRequestMatcherThenUses() throws Exception { @Test public void setRequestMatcherWhenNullThenIllegalArgument() { - assertThatCode(() -> this.filter.setRequestMatcher(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestMatcher(null)); } } diff --git a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java index 902ea2a0fa5..8990a7101e3 100644 --- a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java +++ b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java @@ -44,7 +44,7 @@ import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -76,8 +76,9 @@ public void setup() { @Test public void oauth2ClientWhenUsingDefaultsThenException() throws Exception { WebHttpHandlerBuilder builder = WebHttpHandlerBuilder.webHandler(new DispatcherHandler()); - assertThatCode(() -> SecurityMockServerConfigurers.mockOAuth2Client().beforeServerCreated(builder)) - .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("ClientRegistration"); + assertThatIllegalArgumentException() + .isThrownBy(() -> SecurityMockServerConfigurers.mockOAuth2Client().beforeServerCreated(builder)) + .withMessageContaining("ClientRegistration"); } @Test diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java index 3483c3105cf..ce6557f374f 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java @@ -49,7 +49,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -93,8 +93,9 @@ public void cleanup() { @Test public void oauth2ClientWhenUsingDefaultsThenException() throws Exception { - assertThatCode(() -> oauth2Client().postProcessRequest(new MockHttpServletRequest())) - .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("ClientRegistration"); + assertThatIllegalArgumentException() + .isThrownBy(() -> oauth2Client().postProcessRequest(new MockHttpServletRequest())) + .withMessageContaining("ClientRegistration"); } @Test diff --git a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java index 62a9a127ff1..29fa3d9447e 100644 --- a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java @@ -47,7 +47,7 @@ import org.springframework.security.web.savedrequest.SavedRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willThrow; @@ -282,8 +282,8 @@ public void doFilterWhenResponseCommittedThenRethrowsException() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint); - assertThatThrownBy(() -> filter.doFilter(request, response, chain)).isInstanceOf(ServletException.class) - .hasCauseInstanceOf(AccessDeniedException.class); + assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain)) + .withCauseInstanceOf(AccessDeniedException.class); verifyZeroInteractions(this.mockEntryPoint); } diff --git a/web/src/test/java/org/springframework/security/web/access/intercept/RequestKeyTests.java b/web/src/test/java/org/springframework/security/web/access/intercept/RequestKeyTests.java index 37211f6fa26..a311caa459b 100644 --- a/web/src/test/java/org/springframework/security/web/access/intercept/RequestKeyTests.java +++ b/web/src/test/java/org/springframework/security/web/access/intercept/RequestKeyTests.java @@ -19,7 +19,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Luke Taylor @@ -64,8 +64,8 @@ public void keysWithDifferentUrlsAreNotEquals() { */ @Test public void keysWithNullUrlFailsAssertion() { - assertThatThrownBy(() -> new RequestKey(null, null)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("url cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new RequestKey(null, null)) + .withMessage("url cannot be null"); } } diff --git a/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserGrantedAuthorityTests.java b/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserGrantedAuthorityTests.java index 0ccd0937cb0..b1e5752b09f 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserGrantedAuthorityTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserGrantedAuthorityTests.java @@ -18,7 +18,7 @@ import org.junit.Test; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Clement Ng @@ -26,20 +26,16 @@ */ public class SwitchUserGrantedAuthorityTests { - /** - */ @Test public void authorityWithNullRoleFailsAssertion() { - assertThatThrownBy(() -> new SwitchUserGrantedAuthority(null, null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("role cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new SwitchUserGrantedAuthority(null, null)) + .withMessage("role cannot be null"); } - /** - */ @Test public void authorityWithNullSourceFailsAssertion() { - assertThatThrownBy(() -> new SwitchUserGrantedAuthority("role", null)) - .isInstanceOf(IllegalArgumentException.class).hasMessage("source cannot be null"); + assertThatIllegalArgumentException().isThrownBy(() -> new SwitchUserGrantedAuthority("role", null)) + .withMessage("source cannot be null"); } } diff --git a/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java b/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java index 93a753af168..7d82c0b7c7d 100644 --- a/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java +++ b/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java @@ -37,7 +37,8 @@ import org.springframework.web.filter.DelegatingFilterProxy; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -145,10 +146,9 @@ protected String getDispatcherWebApplicationContextSuffix() { @Test public void onStartupWhenSpringSecurityFilterChainAlreadyRegisteredThenException() { ServletContext context = mock(ServletContext.class); - assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { - }.onStartup(context)).isInstanceOf(IllegalStateException.class) - .hasMessage("Duplicate Filter registration for 'springSecurityFilterChain'. " - + "Check to ensure the Filter is only configured once."); + assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { + }.onStartup(context)).withMessage("Duplicate Filter registration for 'springSecurityFilterChain'. " + + "Check to ensure the Filter is only configured once."); } @Test @@ -182,13 +182,15 @@ public void onStartupWhenDuplicateFilterInsertedThenException() { FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); - assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { + assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { + @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(context, filter1); } - }.onStartup(context)).isInstanceOf(IllegalStateException.class).hasMessage( - "Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once."); + + }.onStartup(context)).withMessage( + "Duplicate Filter registration for 'object'. Check to ensure the Filter is only configured once."); assertProxyDefaults(proxyCaptor.getValue()); verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*"); verify(context).addFilter(anyString(), eq(filter1)); @@ -200,13 +202,14 @@ public void onStartupWhenInsertFiltersEmptyThenException() { FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); - assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { + assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { + @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(context); } - }.onStartup(context)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("filters cannot be null or empty"); + + }.onStartup(context)).withMessage("filters cannot be null or empty"); assertProxyDefaults(proxyCaptor.getValue()); } @@ -218,13 +221,14 @@ public void onStartupWhenNullFilterInsertedThenException() { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); given(context.addFilter(anyString(), eq(filter))).willReturn(registration); - assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { + assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { + @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(context, filter, null); } - }.onStartup(context)).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("filters cannot contain null values"); + + }.onStartup(context)).withMessageContaining("filters cannot contain null values"); verify(context, times(2)).addFilter(anyString(), any(Filter.class)); } @@ -258,12 +262,14 @@ public void onStartupWhenDuplicateFilterAppendedThenException() { FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); - assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { + assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { + @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { appendFilters(context, filter1); } - }.onStartup(context)).isInstanceOf(IllegalStateException.class).hasMessage( + + }.onStartup(context)).withMessage( "Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once."); assertProxyDefaults(proxyCaptor.getValue()); verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*"); @@ -276,13 +282,14 @@ public void onStartupWhenAppendFiltersEmptyThenException() { FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); - assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { + assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { + @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { appendFilters(context); } - }.onStartup(context)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("filters cannot be null or empty"); + + }.onStartup(context)).withMessage("filters cannot be null or empty"); assertProxyDefaults(proxyCaptor.getValue()); } @@ -294,13 +301,14 @@ public void onStartupWhenNullFilterAppendedThenException() { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); given(context.addFilter(anyString(), eq(filter))).willReturn(registration); - assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { + assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() { + @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { appendFilters(context, filter, null); } - }.onStartup(context)).isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("filters cannot contain null values"); + + }.onStartup(context)).withMessageContaining("filters cannot contain null values"); verify(context, times(2)).addFilter(anyString(), any(Filter.class)); } diff --git a/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java b/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java index a09c7a9e2ea..eb38bdabd25 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java @@ -26,8 +26,7 @@ import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.fail; /** @@ -46,32 +45,32 @@ public class StrictHttpFirewallTests { @Test public void getFirewalledRequestWhenInvalidMethodThenThrowsRequestRejectedException() { this.request.setMethod("INVALID"); - assertThatThrownBy(() -> this.firewall.getFirewalledRequest(this.request)) - .isInstanceOf(RequestRejectedException.class); + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } // blocks XST attacks @Test public void getFirewalledRequestWhenTraceMethodThenThrowsRequestRejectedException() { this.request.setMethod(HttpMethod.TRACE.name()); - assertThatThrownBy(() -> this.firewall.getFirewalledRequest(this.request)) - .isInstanceOf(RequestRejectedException.class); + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test // blocks XST attack if request is forwarded to a Microsoft IIS web server public void getFirewalledRequestWhenTrackMethodThenThrowsRequestRejectedException() { this.request.setMethod("TRACK"); - assertThatThrownBy(() -> this.firewall.getFirewalledRequest(this.request)) - .isInstanceOf(RequestRejectedException.class); + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test // HTTP methods are case sensitive public void getFirewalledRequestWhenLowercaseGetThenThrowsRequestRejectedException() { this.request.setMethod("get"); - assertThatThrownBy(() -> this.firewall.getFirewalledRequest(this.request)) - .isInstanceOf(RequestRejectedException.class); + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } @Test @@ -79,7 +78,7 @@ public void getFirewalledRequestWhenAllowedThenNoException() { List allowedMethods = Arrays.asList("DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"); for (String allowedMethod : allowedMethods) { this.request = new MockHttpServletRequest(allowedMethod, ""); - assertThatCode(() -> this.firewall.getFirewalledRequest(this.request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(this.request); } } @@ -87,7 +86,7 @@ public void getFirewalledRequestWhenAllowedThenNoException() { public void getFirewalledRequestWhenInvalidMethodAndAnyMethodThenNoException() { this.firewall.setUnsafeAllowAnyHttpMethod(true); this.request.setMethod("INVALID"); - assertThatCode(() -> this.firewall.getFirewalledRequest(this.request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(this.request); } @Test @@ -419,7 +418,7 @@ public void getFirewalledRequestWhenAllowUrlLowerCaseEncodedDoubleSlashThenNoExc request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b//c"); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -431,7 +430,7 @@ public void getFirewalledRequestWhenAllowUrlUpperCaseEncodedDoubleSlashThenNoExc request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b//c"); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -443,7 +442,7 @@ public void getFirewalledRequestWhenAllowUrlLowerCaseAndUpperCaseEncodedDoubleSl request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b//c"); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -455,7 +454,7 @@ public void getFirewalledRequestWhenAllowUrlUpperCaseAndLowerCaseEncodedDoubleSl request.setContextPath("/context-root"); request.setServletPath(""); request.setPathInfo("/a/b//c"); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -464,7 +463,7 @@ public void getFirewalledRequestWhenRemoveFromUpperCaseEncodedUrlBlacklistThenNo MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2F%2Fc"); this.firewall.getEncodedUrlBlacklist().removeAll(Arrays.asList("%2F%2F")); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -473,7 +472,7 @@ public void getFirewalledRequestWhenRemoveFromLowerCaseEncodedUrlBlacklistThenNo MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2f%2fc"); this.firewall.getEncodedUrlBlacklist().removeAll(Arrays.asList("%2f%2f")); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -482,7 +481,7 @@ public void getFirewalledRequestWhenRemoveFromLowerCaseAndUpperCaseEncodedUrlBla MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2f%2Fc"); this.firewall.getEncodedUrlBlacklist().removeAll(Arrays.asList("%2f%2F")); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -491,7 +490,7 @@ public void getFirewalledRequestWhenRemoveFromUpperCaseAndLowerCaseEncodedUrlBla MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2F%2fc"); this.firewall.getEncodedUrlBlacklist().removeAll(Arrays.asList("%2F%2f")); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -499,7 +498,7 @@ public void getFirewalledRequestWhenRemoveFromDecodedUrlBlacklistThenNoException MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setPathInfo("/a/b//c"); this.firewall.getDecodedUrlBlacklist().removeAll(Arrays.asList("//")); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } // blocklist @@ -509,7 +508,7 @@ public void getFirewalledRequestWhenRemoveFromUpperCaseEncodedUrlBlocklistThenNo MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2F%2Fc"); this.firewall.getEncodedUrlBlocklist().removeAll(Arrays.asList("%2F%2F")); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -518,7 +517,7 @@ public void getFirewalledRequestWhenRemoveFromLowerCaseEncodedUrlBlocklistThenNo MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2f%2fc"); this.firewall.getEncodedUrlBlocklist().removeAll(Arrays.asList("%2f%2f")); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -527,7 +526,7 @@ public void getFirewalledRequestWhenRemoveFromLowerCaseAndUpperCaseEncodedUrlBlo MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2f%2Fc"); this.firewall.getEncodedUrlBlocklist().removeAll(Arrays.asList("%2f%2F")); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -536,7 +535,7 @@ public void getFirewalledRequestWhenRemoveFromUpperCaseAndLowerCaseEncodedUrlBlo MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setRequestURI("/context-root/a/b%2F%2fc"); this.firewall.getEncodedUrlBlocklist().removeAll(Arrays.asList("%2F%2f")); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test @@ -544,14 +543,14 @@ public void getFirewalledRequestWhenRemoveFromDecodedUrlBlocklistThenNoException MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); request.setPathInfo("/a/b//c"); this.firewall.getDecodedUrlBlocklist().removeAll(Arrays.asList("//")); - assertThatCode(() -> this.firewall.getFirewalledRequest(request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(request); } @Test public void getFirewalledRequestWhenTrustedDomainThenNoException() { this.request.addHeader("Host", "example.org"); this.firewall.setAllowedHostnames((hostname) -> hostname.equals("example.org")); - assertThatCode(() -> this.firewall.getFirewalledRequest(this.request)).doesNotThrowAnyException(); + this.firewall.getFirewalledRequest(this.request); } @Test(expected = RequestRejectedException.class) diff --git a/web/src/test/java/org/springframework/security/web/header/writers/CompositeHeaderWriterTests.java b/web/src/test/java/org/springframework/security/web/header/writers/CompositeHeaderWriterTests.java index 52f69284abc..3f57db42ac1 100644 --- a/web/src/test/java/org/springframework/security/web/header/writers/CompositeHeaderWriterTests.java +++ b/web/src/test/java/org/springframework/security/web/header/writers/CompositeHeaderWriterTests.java @@ -26,7 +26,7 @@ import org.springframework.security.web.header.HeaderWriter; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -52,8 +52,7 @@ public void writeHeadersWhenConfiguredWithDelegatesThenInvokesEach() { @Test public void constructorWhenPassingEmptyListThenThrowsException() { - assertThatCode(() -> new CompositeHeaderWriter(Collections.emptyList())) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> new CompositeHeaderWriter(Collections.emptyList())); } } diff --git a/web/src/test/java/org/springframework/security/web/header/writers/FeaturePolicyHeaderWriterTests.java b/web/src/test/java/org/springframework/security/web/header/writers/FeaturePolicyHeaderWriterTests.java index 8c62dbd1c59..5a886989627 100644 --- a/web/src/test/java/org/springframework/security/web/header/writers/FeaturePolicyHeaderWriterTests.java +++ b/web/src/test/java/org/springframework/security/web/header/writers/FeaturePolicyHeaderWriterTests.java @@ -23,7 +23,7 @@ import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link FeaturePolicyHeaderWriter}. @@ -59,14 +59,14 @@ public void writeHeadersFeaturePolicyDefault() { @Test public void createWriterWithNullDirectivesShouldThrowException() { - assertThatThrownBy(() -> new FeaturePolicyHeaderWriter(null)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("policyDirectives must not be null or empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new FeaturePolicyHeaderWriter(null)) + .withMessage("policyDirectives must not be null or empty"); } @Test public void createWriterWithEmptyDirectivesShouldThrowException() { - assertThatThrownBy(() -> new FeaturePolicyHeaderWriter("")).isInstanceOf(IllegalArgumentException.class) - .hasMessage("policyDirectives must not be null or empty"); + assertThatIllegalArgumentException().isThrownBy(() -> new FeaturePolicyHeaderWriter("")) + .withMessage("policyDirectives must not be null or empty"); } @Test diff --git a/web/src/test/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolverTests.java b/web/src/test/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolverTests.java index d7d5a915cd5..ccbdb47b56b 100644 --- a/web/src/test/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolverTests.java +++ b/web/src/test/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolverTests.java @@ -40,7 +40,7 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -183,7 +183,7 @@ public void resolveArgumentWhenErrorOnInvalidTypeExplicitTrue() { given(this.authentication.getPrincipal()).willReturn("user"); Mono argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); - assertThatThrownBy(() -> argument.block()).isInstanceOf(ClassCastException.class); + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> argument.block()); } void authenticationPrincipal(@AuthenticationPrincipal String principal, diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/CookieRequestCacheTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/CookieRequestCacheTests.java index 4b24012da9a..9572f9e012b 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/CookieRequestCacheTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/CookieRequestCacheTests.java @@ -27,7 +27,7 @@ import org.springframework.mock.web.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Zeeshan Adnan @@ -61,8 +61,7 @@ public void saveRequestWhenMatchesThenSavedRequestInACookieOnResponse() { @Test public void setRequestMatcherWhenRequestMatcherIsSetNullThenThrowsIllegalArgumentException() { CookieRequestCache cookieRequestCache = new CookieRequestCache(); - assertThatThrownBy(() -> cookieRequestCache.setRequestMatcher(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> cookieRequestCache.setRequestMatcher(null)); } @Test diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcherTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcherTests.java index 6addc3d8ad2..314dff71077 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcherTests.java @@ -29,7 +29,8 @@ import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -82,13 +83,13 @@ public void matchesWhenErrorThenReturnFalse() { @Test public void matchesWhenNullThenThrowsException() { given(this.converter.convert(any())).willReturn(null); - assertThatCode(() -> this.matcher.matches(this.exchange).block()).isInstanceOf(NullPointerException.class); + assertThatNullPointerException().isThrownBy(() -> this.matcher.matches(this.exchange).block()); } @Test public void matchesWhenExceptionThenPropagates() { given(this.converter.convert(any())).willThrow(RuntimeException.class); - assertThatCode(() -> this.matcher.matches(this.exchange).block()).isInstanceOf(RuntimeException.class); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.matcher.matches(this.exchange).block()); } } diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandlerTests.java index 5c3e1a63197..744289b5a9c 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandlerTests.java @@ -33,7 +33,7 @@ import org.springframework.security.web.server.WebFilterExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -68,16 +68,14 @@ public void setup() { @Test public void constructorWhenNullThenIllegalArgumentException() { - assertThatThrownBy( - () -> new DelegatingServerAuthenticationSuccessHandler((ServerAuthenticationSuccessHandler[]) null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> new DelegatingServerAuthenticationSuccessHandler((ServerAuthenticationSuccessHandler[]) null)); } @Test public void constructorWhenEmptyThenIllegalArgumentException() { - assertThatThrownBy( - () -> new DelegatingServerAuthenticationSuccessHandler(new ServerAuthenticationSuccessHandler[0])) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy( + () -> new DelegatingServerAuthenticationSuccessHandler(new ServerAuthenticationSuccessHandler[0])); } @Test diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandlerTests.java index 0f42d12f4dd..81a0d2f1feb 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandlerTests.java @@ -34,7 +34,7 @@ import org.springframework.security.web.server.WebFilterExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -71,23 +71,23 @@ public void setup() { @Test public void constructorWhenNullVargsThenIllegalArgumentException() { - assertThatThrownBy(() -> new DelegatingServerLogoutHandler((ServerLogoutHandler[]) null)) - .isExactlyInstanceOf(IllegalArgumentException.class).hasMessage("delegates cannot be null or empty") - .hasNoCause(); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingServerLogoutHandler((ServerLogoutHandler[]) null)) + .withMessage("delegates cannot be null or empty").withNoCause(); } @Test public void constructorWhenNullListThenIllegalArgumentException() { - assertThatThrownBy(() -> new DelegatingServerLogoutHandler((List) null)) - .isExactlyInstanceOf(IllegalArgumentException.class).hasMessage("delegates cannot be null or empty") - .hasNoCause(); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingServerLogoutHandler((List) null)) + .withMessage("delegates cannot be null or empty").withNoCause(); } @Test public void constructorWhenEmptyThenIllegalArgumentException() { - assertThatThrownBy(() -> new DelegatingServerLogoutHandler(new ServerLogoutHandler[0])) - .isExactlyInstanceOf(IllegalArgumentException.class).hasMessage("delegates cannot be null or empty") - .hasNoCause(); + assertThatIllegalArgumentException() + .isThrownBy(() -> new DelegatingServerLogoutHandler(new ServerLogoutHandler[0])) + .withMessage("delegates cannot be null or empty").withNoCause(); } @Test diff --git a/web/src/test/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilterTests.java index 38cf2bf2140..e7d06172682 100644 --- a/web/src/test/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilterTests.java @@ -32,7 +32,8 @@ import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +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; @@ -110,8 +111,7 @@ public void filterWhenRequestIsInsecureThenPortMapperRemapsPort() { @Test public void filterWhenRequestIsInsecureAndNoPortMappingThenThrowsIllegalState() { ServerWebExchange exchange = get("http://localhost:1234"); - assertThatCode(() -> this.filter.filter(exchange, this.chain).block()) - .isInstanceOf(IllegalStateException.class); + assertThatIllegalStateException().isThrownBy(() -> this.filter.filter(exchange, this.chain).block()); } @Test @@ -124,13 +124,12 @@ public void filterWhenInsecureRequestHasAPathThenRedirects() { @Test public void setRequiresTransportSecurityMatcherWhenSetWithNullValueThenThrowsIllegalArgument() { - assertThatCode(() -> this.filter.setRequiresHttpsRedirectMatcher(null)) - .isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequiresHttpsRedirectMatcher(null)); } @Test public void setPortMapperWhenSetWithNullValueThenThrowsIllegalArgument() { - assertThatCode(() -> this.filter.setPortMapper(null)).isInstanceOf(IllegalArgumentException.class); + assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setPortMapper(null)); } private String redirectedUrl(ServerWebExchange exchange) { diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java index 1ef1c66f2e3..281661e02c1 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/IpAddressMatcherTests.java @@ -22,7 +22,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Luke Taylor @@ -92,18 +92,17 @@ public void zeroMaskMatchesAnything() { @Test public void ipv4RequiredAddressMaskTooLongThenIllegalArgumentException() { String ipv4AddressWithTooLongMask = "192.168.1.104/33"; - assertThatCode(() -> new IpAddressMatcher(ipv4AddressWithTooLongMask)) - .isInstanceOf(IllegalArgumentException.class).hasMessage( - String.format("IP address %s is too short for bitmask of " + "length %d", "192.168.1.104", 33)); + assertThatIllegalArgumentException().isThrownBy(() -> new IpAddressMatcher(ipv4AddressWithTooLongMask)) + .withMessage(String.format("IP address %s is too short for bitmask of length %d", "192.168.1.104", 33)); } // SEC-2576 @Test public void ipv6RequiredAddressMaskTooLongThenIllegalArgumentException() { String ipv6AddressWithTooLongMask = "fe80::21f:5bff:fe33:bd68/129"; - assertThatCode(() -> new IpAddressMatcher(ipv6AddressWithTooLongMask)) - .isInstanceOf(IllegalArgumentException.class).hasMessage(String.format( - "IP address %s is too short for bitmask of " + "length %d", "fe80::21f:5bff:fe33:bd68", 129)); + assertThatIllegalArgumentException().isThrownBy(() -> new IpAddressMatcher(ipv6AddressWithTooLongMask)) + .withMessage(String.format("IP address %s is too short for bitmask of length %d", + "fe80::21f:5bff:fe33:bd68", 129)); } }