瀏覽代碼

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
Phillip Webb 5 年之前
父節點
當前提交
319d3364aa
共有 100 個文件被更改,包括 1150 次插入1057 次删除
  1. 6 4
      config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/HelloRSocketITests.java
  2. 14 11
      config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerConnectionITests.java
  3. 15 12
      config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerITests.java
  4. 3 3
      config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/SimpleAuthenticationITests.java
  5. 8 9
      config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java
  6. 6 4
      config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java
  7. 13 11
      config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java
  8. 7 6
      config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityExpressionHandlerTests.java
  9. 33 33
      config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityTests.java
  10. 5 4
      config/src/test/java/org/springframework/security/config/annotation/method/configuration/SampleEnableGlobalMethodSecurityTests.java
  11. 2 3
      config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java
  12. 1 2
      config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java
  13. 18 12
      config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java
  14. 13 14
      config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java
  15. 3 3
      config/src/test/java/org/springframework/security/config/annotation/web/configurers/CorsConfigurerTests.java
  16. 7 5
      config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java
  17. 9 8
      config/src/test/java/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurerTests.java
  18. 10 7
      config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java
  19. 19 13
      config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.java
  20. 7 6
      config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.java
  21. 4 4
      config/src/test/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.java
  22. 11 6
      config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java
  23. 6 4
      config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java
  24. 26 20
      config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java
  25. 8 7
      config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java
  26. 3 3
      config/src/test/java/org/springframework/security/config/crypto/RsaKeyConversionServicePostProcessorTests.java
  27. 5 5
      config/src/test/java/org/springframework/security/config/http/AccessDeniedConfigTests.java
  28. 5 5
      config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java
  29. 4 3
      config/src/test/java/org/springframework/security/config/http/HttpCorsConfigTests.java
  30. 50 51
      config/src/test/java/org/springframework/security/config/http/HttpHeadersConfigTests.java
  31. 9 9
      config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java
  32. 7 8
      config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java
  33. 7 5
      config/src/test/java/org/springframework/security/config/http/MultiHttpBlockConfigTests.java
  34. 15 15
      config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java
  35. 3 3
      config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java
  36. 13 12
      config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java
  37. 3 4
      config/src/test/java/org/springframework/security/config/web/server/FormLoginTests.java
  38. 6 5
      config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java
  39. 49 42
      config/src/test/java/org/springframework/security/config/websocket/WebSocketMessageBrokerConfigTests.java
  40. 3 4
      core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java
  41. 2 2
      core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java
  42. 5 9
      core/src/test/java/org/springframework/security/authentication/jaas/JaasGrantedAuthorityTests.java
  43. 3 5
      core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTests.java
  44. 3 2
      core/src/test/java/org/springframework/security/jackson2/SecurityJackson2ModulesTests.java
  45. 20 18
      crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java
  46. 8 0
      etc/checkstyle/checkstyle.xml
  47. 3 9
      ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java
  48. 3 3
      ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerModifyPasswordTests.java
  49. 5 5
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeOAuth2AuthorizedClientProviderTests.java
  50. 5 5
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests.java
  51. 26 23
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java
  52. 39 23
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java
  53. 13 11
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java
  54. 13 11
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java
  55. 7 7
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java
  56. 7 7
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java
  57. 4 3
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java
  58. 23 29
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java
  59. 39 29
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java
  60. 10 7
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizationContextTests.java
  61. 11 10
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizeRequestTests.java
  62. 5 5
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientIdTests.java
  63. 8 7
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java
  64. 13 11
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java
  65. 13 11
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java
  66. 8 7
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java
  67. 16 14
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java
  68. 16 14
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java
  69. 11 11
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java
  70. 12 12
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationTokenTests.java
  71. 4 4
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java
  72. 13 15
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManagerTests.java
  73. 26 24
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultAuthorizationCodeTokenResponseClientTests.java
  74. 25 23
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultClientCredentialsTokenResponseClientTests.java
  75. 16 16
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultPasswordTokenResponseClientTests.java
  76. 17 17
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultRefreshTokenTokenResponseClientTests.java
  77. 4 5
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java
  78. 19 14
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestTests.java
  79. 10 7
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestTests.java
  80. 11 9
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java
  81. 6 6
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClientTests.java
  82. 19 20
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactivePasswordTokenResponseClientTests.java
  83. 18 18
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveRefreshTokenTokenResponseClientTests.java
  84. 7 7
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java
  85. 3 3
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java
  86. 3 3
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java
  87. 6 5
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java
  88. 3 3
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java
  89. 22 19
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java
  90. 20 21
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java
  91. 4 5
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenValidatorTests.java
  92. 20 21
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java
  93. 7 8
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java
  94. 7 7
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestTests.java
  95. 4 7
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java
  96. 3 5
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandlerTests.java
  97. 3 5
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java
  98. 27 29
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java
  99. 28 27
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java
  100. 8 9
      oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/InMemoryReactiveClientRegistrationRepositoryTests.java

+ 6 - 4
config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/HelloRSocketITests.java

@@ -20,6 +20,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.List;
 
 
 import io.rsocket.RSocketFactory;
 import io.rsocket.RSocketFactory;
+import io.rsocket.exceptions.RejectedSetupException;
 import io.rsocket.frame.decoder.PayloadDecoder;
 import io.rsocket.frame.decoder.PayloadDecoder;
 import io.rsocket.transport.netty.server.CloseableChannel;
 import io.rsocket.transport.netty.server.CloseableChannel;
 import io.rsocket.transport.netty.server.TcpServerTransport;
 import io.rsocket.transport.netty.server.TcpServerTransport;
@@ -46,7 +47,7 @@ import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringRunner;
 import org.springframework.test.context.junit4.SpringRunner;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * @author Rob Winch
@@ -87,10 +88,11 @@ public class HelloRSocketITests {
 		this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies())
 		this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies())
 				.connectTcp("localhost", this.server.address().getPort()).block();
 				.connectTcp("localhost", this.server.address().getPort()).block();
 		String data = "rob";
 		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
 		// FIXME: https://github.com/rsocket/rsocket-java/issues/686
-		// .isInstanceOf(RejectedSetupException.class);
 		assertThat(this.controller.payloads).isEmpty();
 		assertThat(this.controller.payloads).isEmpty();
 	}
 	}
 
 

+ 14 - 11
config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerConnectionITests.java

@@ -21,6 +21,7 @@ import java.util.List;
 
 
 import io.rsocket.RSocketFactory;
 import io.rsocket.RSocketFactory;
 import io.rsocket.exceptions.ApplicationErrorException;
 import io.rsocket.exceptions.ApplicationErrorException;
+import io.rsocket.exceptions.RejectedSetupException;
 import io.rsocket.frame.decoder.PayloadDecoder;
 import io.rsocket.frame.decoder.PayloadDecoder;
 import io.rsocket.transport.netty.server.CloseableChannel;
 import io.rsocket.transport.netty.server.CloseableChannel;
 import io.rsocket.transport.netty.server.TcpServerTransport;
 import io.rsocket.transport.netty.server.TcpServerTransport;
@@ -49,7 +50,7 @@ import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringRunner;
 import org.springframework.test.context.junit4.SpringRunner;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * @author Rob Winch
@@ -103,8 +104,8 @@ public class RSocketMessageHandlerConnectionITests {
 		UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
 		UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
 		this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
 		this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
 				.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
 				.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
 	@Test
@@ -137,10 +138,11 @@ public class RSocketMessageHandlerConnectionITests {
 	public void connectWhenNotAuthenticated() {
 	public void connectWhenNotAuthenticated() {
 		this.requester = requester().connectTcp(this.server.address().getHostName(), this.server.address().getPort())
 		this.requester = requester().connectTcp(this.server.address().getHostName(), this.server.address().getPort())
 				.block();
 				.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
 		// FIXME: https://github.com/rsocket/rsocket-java/issues/686
-		// .isInstanceOf(RejectedSetupException.class);
 	}
 	}
 
 
 	@Test
 	@Test
@@ -148,10 +150,11 @@ public class RSocketMessageHandlerConnectionITests {
 		UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("evil", "password");
 		UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("evil", "password");
 		this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
 		this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
 				.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
 				.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
 		// FIXME: https://github.com/rsocket/rsocket-java/issues/686
-		// .isInstanceOf(RejectedSetupException.class);
 	}
 	}
 
 
 	@Test
 	@Test
@@ -159,8 +162,8 @@ public class RSocketMessageHandlerConnectionITests {
 		UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
 		UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
 		this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
 		this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
 				.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
 				.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
 	@Test

+ 15 - 12
config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/RSocketMessageHandlerITests.java

@@ -52,7 +52,7 @@ import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringRunner;
 import org.springframework.test.context.junit4.SpringRunner;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * @author Rob Winch
@@ -96,8 +96,9 @@ public class RSocketMessageHandlerITests {
 	@Test
 	@Test
 	public void retrieveMonoWhenSecureThenDenied() throws Exception {
 	public void retrieveMonoWhenSecureThenDenied() throws Exception {
 		String data = "rob";
 		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();
 		assertThat(this.controller.payloads).isEmpty();
 	}
 	}
 
 
@@ -105,10 +106,11 @@ public class RSocketMessageHandlerITests {
 	public void retrieveMonoWhenAuthenticationFailedThenException() throws Exception {
 	public void retrieveMonoWhenAuthenticationFailedThenException() throws Exception {
 		String data = "rob";
 		String data = "rob";
 		UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("invalid", "password");
 		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();
 		assertThat(this.controller.payloads).isEmpty();
 	}
 	}
 
 
@@ -134,9 +136,10 @@ public class RSocketMessageHandlerITests {
 	@Test
 	@Test
 	public void retrieveFluxWhenDataFluxAndSecureThenDenied() throws Exception {
 	public void retrieveFluxWhenDataFluxAndSecureThenDenied() throws Exception {
 		Flux<String> data = Flux.just("a", "b", "c");
 		Flux<String> 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();
 		assertThat(this.controller.payloads).isEmpty();
 	}
 	}
 
 
@@ -152,9 +155,9 @@ public class RSocketMessageHandlerITests {
 	@Test
 	@Test
 	public void retrieveFluxWhenDataStringAndSecureThenDenied() throws Exception {
 	public void retrieveFluxWhenDataStringAndSecureThenDenied() throws Exception {
 		String data = "a";
 		String data = "a";
-		assertThatCode(
+		assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(
 				() -> this.requester.route("secure.hello").data(data).retrieveFlux(String.class).collectList().block())
 				() -> 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();
 		assertThat(this.controller.payloads).isEmpty();
 	}
 	}
 
 

+ 3 - 3
config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/SimpleAuthenticationITests.java

@@ -52,7 +52,7 @@ import org.springframework.util.MimeType;
 import org.springframework.util.MimeTypeUtils;
 import org.springframework.util.MimeTypeUtils;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * @author Rob Winch
@@ -93,8 +93,8 @@ public class SimpleAuthenticationITests {
 		this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies())
 		this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies())
 				.connectTcp("localhost", this.server.address().getPort()).block();
 				.connectTcp("localhost", this.server.address().getPort()).block();
 		String data = "rob";
 		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();
 		assertThat(this.controller.payloads).isEmpty();
 	}
 	}
 
 

+ 8 - 9
config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java

@@ -63,7 +63,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.security.provisioning.InMemoryUserDetailsManager;
 import org.springframework.security.provisioning.InMemoryUserDetailsManager;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.startsWith;
 import static org.mockito.ArgumentMatchers.startsWith;
@@ -165,9 +165,8 @@ public class AuthenticationConfigurationTests {
 				new BootGlobalAuthenticationConfigurerAdapter()));
 				new BootGlobalAuthenticationConfigurerAdapter()));
 		AuthenticationManager authenticationManager = config.getAuthenticationManager();
 		AuthenticationManager authenticationManager = config.getAuthenticationManager();
 		authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
 		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
 	@Test
@@ -207,8 +206,8 @@ public class AuthenticationConfigurationTests {
 				.getAuthenticationManager();
 				.getAuthenticationManager();
 		given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
 		given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
 		am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
 		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
 	@Test
@@ -222,8 +221,8 @@ public class AuthenticationConfigurationTests {
 		given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
 		given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
 				User.withUserDetails(user).build());
 				User.withUserDetails(user).build());
 		am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
 		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
 	@Test
@@ -291,7 +290,7 @@ public class AuthenticationConfigurationTests {
 		this.spring.register(AuthenticationConfigurationSubclass.class).autowire();
 		this.spring.register(AuthenticationConfigurationSubclass.class).autowire();
 		AuthenticationManagerBuilder ap = this.spring.getContext().getBean(AuthenticationManagerBuilder.class);
 		AuthenticationManagerBuilder ap = this.spring.getContext().getBean(AuthenticationManagerBuilder.class);
 		this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
 		this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
-		assertThatThrownBy(ap::build).isInstanceOf(AlreadyBuiltException.class);
+		assertThatExceptionOfType(AlreadyBuiltException.class).isThrownBy(ap::build);
 	}
 	}
 
 
 	@EnableGlobalMethodSecurity(securedEnabled = true)
 	@EnableGlobalMethodSecurity(securedEnabled = true)

+ 6 - 4
config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java

@@ -35,7 +35,7 @@ import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringRunner;
 import org.springframework.test.context.junit4.SpringRunner;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.reset;
@@ -73,9 +73,11 @@ public class EnableReactiveMethodSecurityTests {
 
 
 	@Test
 	@Test
 	public void notPublisherPreAuthorizeFindByIdThenThrowsIllegalStateException() {
 	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
 	@Test

+ 13 - 11
config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java

@@ -61,7 +61,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
 import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
 import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -125,7 +125,8 @@ public class GlobalMethodSecurityConfigurationTests {
 		this.spring.register(CustomTrustResolverConfig.class).autowire();
 		this.spring.register(CustomTrustResolverConfig.class).autowire();
 		AuthenticationTrustResolver trustResolver = this.spring.getContext().getBean(AuthenticationTrustResolver.class);
 		AuthenticationTrustResolver trustResolver = this.spring.getContext().getBean(AuthenticationTrustResolver.class);
 		given(trustResolver.isAnonymous(any())).willReturn(true, false);
 		given(trustResolver.isAnonymous(any())).willReturn(true, false);
-		assertThatThrownBy(() -> this.service.preAuthorizeNotAnonymous()).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class)
+				.isThrownBy(() -> this.service.preAuthorizeNotAnonymous());
 		this.service.preAuthorizeNotAnonymous();
 		this.service.preAuthorizeNotAnonymous();
 		verify(trustResolver, atLeastOnce()).isAnonymous(any());
 		verify(trustResolver, atLeastOnce()).isAnonymous(any());
 	}
 	}
@@ -136,7 +137,7 @@ public class GlobalMethodSecurityConfigurationTests {
 	public void defaultWebSecurityExpressionHandlerHasBeanResolverSet() {
 	public void defaultWebSecurityExpressionHandlerHasBeanResolverSet() {
 		this.spring.register(ExpressionHandlerHasBeanResolverSetConfig.class).autowire();
 		this.spring.register(ExpressionHandlerHasBeanResolverSetConfig.class).autowire();
 		Authz authz = this.spring.getContext().getBean(Authz.class);
 		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);
 		this.service.preAuthorizeBean(true);
 	}
 	}
 
 
@@ -144,7 +145,7 @@ public class GlobalMethodSecurityConfigurationTests {
 	@WithMockUser
 	@WithMockUser
 	public void methodSecuritySupportsAnnotaitonsOnInterfaceParamerNames() {
 	public void methodSecuritySupportsAnnotaitonsOnInterfaceParamerNames() {
 		this.spring.register(MethodSecurityServiceConfig.class).autowire();
 		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");
 		this.service.postAnnotation("grant");
 		// no exception
 		// no exception
 	}
 	}
@@ -157,7 +158,8 @@ public class GlobalMethodSecurityConfigurationTests {
 		given(permission.hasPermission(any(), eq("something"), eq("read"))).willReturn(true, false);
 		given(permission.hasPermission(any(), eq("something"), eq("read"))).willReturn(true, false);
 		this.service.hasPermission("something");
 		this.service.hasPermission("something");
 		// no exception
 		// no exception
-		assertThatThrownBy(() -> this.service.hasPermission("something")).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class)
+				.isThrownBy(() -> this.service.hasPermission("something"));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -171,7 +173,7 @@ public class GlobalMethodSecurityConfigurationTests {
 	@WithMockUser
 	@WithMockUser
 	public void enableGlobalMethodSecurityWorksOnSuperclass() {
 	public void enableGlobalMethodSecurityWorksOnSuperclass() {
 		this.spring.register(ChildConfig.class).autowire();
 		this.spring.register(ChildConfig.class).autowire();
-		assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
 	}
 	}
 
 
 	// SEC-2479
 	// SEC-2479
@@ -186,7 +188,7 @@ public class GlobalMethodSecurityConfigurationTests {
 				child.register(Sec2479ChildConfig.class);
 				child.register(Sec2479ChildConfig.class);
 				child.refresh();
 				child.refresh();
 				this.spring.context(child).autowire();
 				this.spring.context(child).autowire();
-				assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
+				assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
 			}
 			}
 		}
 		}
 	}
 	}
@@ -228,7 +230,7 @@ public class GlobalMethodSecurityConfigurationTests {
 	@WithMockUser
 	@WithMockUser
 	public void preAuthorizeBeanSpel() {
 	public void preAuthorizeBeanSpel() {
 		this.spring.register(PreAuthorizeBeanSpelConfig.class).autowire();
 		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);
 		this.service.preAuthorizeBean(true);
 	}
 	}
 
 
@@ -237,7 +239,7 @@ public class GlobalMethodSecurityConfigurationTests {
 	@WithMockUser
 	@WithMockUser
 	public void roleHierarchy() {
 	public void roleHierarchy() {
 		this.spring.register(RoleHierarchyConfig.class).autowire();
 		this.spring.register(RoleHierarchyConfig.class).autowire();
-		assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
 		this.service.preAuthorizeAdmin();
 		this.service.preAuthorizeAdmin();
 	}
 	}
 
 
@@ -247,7 +249,7 @@ public class GlobalMethodSecurityConfigurationTests {
 		this.spring.register(CustomGrantedAuthorityConfig.class).autowire();
 		this.spring.register(CustomGrantedAuthorityConfig.class).autowire();
 		CustomGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
 		CustomGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
 				.getBean(CustomGrantedAuthorityConfig.CustomAuthorityService.class);
 				.getBean(CustomGrantedAuthorityConfig.CustomAuthorityService.class);
-		assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
 		customService.customPrefixRoleUser();
 		customService.customPrefixRoleUser();
 		// no exception
 		// no exception
 	}
 	}
@@ -258,7 +260,7 @@ public class GlobalMethodSecurityConfigurationTests {
 		this.spring.register(EmptyRolePrefixGrantedAuthorityConfig.class).autowire();
 		this.spring.register(EmptyRolePrefixGrantedAuthorityConfig.class).autowire();
 		EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
 		EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
 				.getBean(EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService.class);
 				.getBean(EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService.class);
-		assertThatThrownBy(() -> this.service.securedUser()).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.securedUser());
 		customService.emptyPrefixRoleUser();
 		customService.emptyPrefixRoleUser();
 		// no exception
 		// no exception
 	}
 	}

+ 7 - 6
config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityExpressionHandlerTests.java

@@ -33,8 +33,8 @@ import org.springframework.security.test.context.annotation.SecurityTestExecutio
 import org.springframework.security.test.context.support.WithMockUser;
 import org.springframework.security.test.context.support.WithMockUser;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 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
  * @author Rob Winch
@@ -54,16 +54,17 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPreAuthorizesAccordingly() {
 	public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPreAuthorizesAccordingly() {
 		this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
 		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
 	@Test
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPostAuthorizesAccordingly() {
 	public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPostAuthorizesAccordingly() {
 		this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
 		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)
 	@EnableGlobalMethodSecurity(prePostEnabled = true)

+ 33 - 33
config/src/test/java/org/springframework/security/config/annotation/method/configuration/NamespaceGlobalMethodSecurityTests.java

@@ -57,8 +57,7 @@ import org.springframework.security.test.context.support.WithMockUser;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * @author Rob Winch
@@ -78,32 +77,32 @@ public class NamespaceGlobalMethodSecurityTests {
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenCustomAccessDecisionManagerThenAuthorizes() {
 	public void methodSecurityWhenCustomAccessDecisionManagerThenAuthorizes() {
 		this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
 		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
 	@Test
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenCustomAfterInvocationManagerThenAuthorizes() {
 	public void methodSecurityWhenCustomAfterInvocationManagerThenAuthorizes() {
 		this.spring.register(CustomAfterInvocationManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
 		this.spring.register(CustomAfterInvocationManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
-		assertThatThrownBy(() -> this.service.preAuthorizePermitAll()).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorizePermitAll());
 	}
 	}
 
 
 	@Test
 	@Test
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenCustomAuthenticationManagerThenAuthorizes() {
 	public void methodSecurityWhenCustomAuthenticationManagerThenAuthorizes() {
 		this.spring.register(CustomAuthenticationConfig.class, MethodSecurityServiceConfig.class).autowire();
 		this.spring.register(CustomAuthenticationConfig.class, MethodSecurityServiceConfig.class).autowire();
-		assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(UnsupportedOperationException.class);
+		assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.preAuthorize());
 	}
 	}
 
 
 	@Test
 	@Test
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenJsr250EnabledThenAuthorizes() {
 	public void methodSecurityWhenJsr250EnabledThenAuthorizes() {
 		this.spring.register(Jsr250Config.class, MethodSecurityServiceConfig.class).autowire();
 		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
 	@Test
@@ -111,9 +110,9 @@ public class NamespaceGlobalMethodSecurityTests {
 	public void methodSecurityWhenCustomMethodSecurityMetadataSourceThenAuthorizes() {
 	public void methodSecurityWhenCustomMethodSecurityMetadataSourceThenAuthorizes() {
 		this.spring.register(CustomMethodSecurityMetadataSourceConfig.class, MethodSecurityServiceConfig.class)
 		this.spring.register(CustomMethodSecurityMetadataSourceConfig.class, MethodSecurityServiceConfig.class)
 				.autowire();
 				.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
 	@Test
@@ -144,7 +143,7 @@ public class NamespaceGlobalMethodSecurityTests {
 		this.spring.register(CustomOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
 		this.spring.register(CustomOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
 		assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
 		assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
 				.getOrder()).isEqualTo(-135);
 				.getOrder()).isEqualTo(-135);
-		assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -153,7 +152,7 @@ public class NamespaceGlobalMethodSecurityTests {
 		this.spring.register(DefaultOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
 		this.spring.register(DefaultOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
 		assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
 		assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
 				.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
 				.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
-		assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(UnsupportedOperationException.class);
+		assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -163,25 +162,25 @@ public class NamespaceGlobalMethodSecurityTests {
 				.autowire();
 				.autowire();
 		assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
 		assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
 				.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
 				.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
-		assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(UnsupportedOperationException.class);
+		assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250());
 	}
 	}
 
 
 	@Test
 	@Test
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenPrePostEnabledThenPreAuthorizes() {
 	public void methodSecurityWhenPrePostEnabledThenPreAuthorizes() {
 		this.spring.register(PreAuthorizeConfig.class, MethodSecurityServiceConfig.class).autowire();
 		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
 	@Test
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenPrePostEnabledAndCustomGlobalMethodSecurityConfigurationThenPreAuthorizes() {
 	public void methodSecurityWhenPrePostEnabledAndCustomGlobalMethodSecurityConfigurationThenPreAuthorizes() {
 		this.spring.register(PreAuthorizeExtendsGMSCConfig.class, MethodSecurityServiceConfig.class).autowire();
 		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
 	@Test
@@ -190,7 +189,7 @@ public class NamespaceGlobalMethodSecurityTests {
 		this.spring.register(ProxyTargetClassConfig.class, MethodSecurityServiceConfig.class).autowire();
 		this.spring.register(ProxyTargetClassConfig.class, MethodSecurityServiceConfig.class).autowire();
 		// make sure service was actually proxied
 		// make sure service was actually proxied
 		assertThat(this.service.getClass().getInterfaces()).doesNotContain(MethodSecurityService.class);
 		assertThat(this.service.getClass().getInterfaces()).doesNotContain(MethodSecurityService.class);
-		assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -198,7 +197,7 @@ public class NamespaceGlobalMethodSecurityTests {
 	public void methodSecurityWhenDefaultProxyThenWiresToInterface() {
 	public void methodSecurityWhenDefaultProxyThenWiresToInterface() {
 		this.spring.register(DefaultProxyConfig.class, MethodSecurityServiceConfig.class).autowire();
 		this.spring.register(DefaultProxyConfig.class, MethodSecurityServiceConfig.class).autowire();
 		assertThat(this.service.getClass().getInterfaces()).contains(MethodSecurityService.class);
 		assertThat(this.service.getClass().getInterfaces()).contains(MethodSecurityService.class);
-		assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -213,26 +212,27 @@ public class NamespaceGlobalMethodSecurityTests {
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenSecuredEnabledThenSecures() {
 	public void methodSecurityWhenSecuredEnabledThenSecures() {
 		this.spring.register(SecuredConfig.class, MethodSecurityServiceConfig.class).autowire();
 		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
 	@Test
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenMissingEnableAnnotationThenShowsHelpfulError() {
 	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
 	@Test
 	@WithMockUser
 	@WithMockUser
 	public void methodSecurityWhenImportingGlobalMethodSecurityConfigurationSubclassThenAuthorizes() {
 	public void methodSecurityWhenImportingGlobalMethodSecurityConfigurationSubclassThenAuthorizes() {
 		this.spring.register(ImportSubclassGMSCConfig.class, MethodSecurityServiceConfig.class).autowire();
 		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)
 	@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)

+ 5 - 4
config/src/test/java/org/springframework/security/config/annotation/method/configuration/SampleEnableGlobalMethodSecurityTests.java

@@ -35,7 +35,7 @@ import org.springframework.security.core.Authentication;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.core.context.SecurityContextHolder;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * Demonstrate the samples
@@ -62,15 +62,16 @@ public class SampleEnableGlobalMethodSecurityTests {
 		this.spring.register(SampleWebSecurityConfig.class).autowire();
 		this.spring.register(SampleWebSecurityConfig.class).autowire();
 		assertThat(this.methodSecurityService.secured()).isNull();
 		assertThat(this.methodSecurityService.secured()).isNull();
 		assertThat(this.methodSecurityService.jsr250()).isNull();
 		assertThat(this.methodSecurityService.jsr250()).isNull();
-		assertThatThrownBy(() -> this.methodSecurityService.preAuthorize()).isInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(AccessDeniedException.class)
+				.isThrownBy(() -> this.methodSecurityService.preAuthorize());
 	}
 	}
 
 
 	@Test
 	@Test
 	public void customPermissionHandler() {
 	public void customPermissionHandler() {
 		this.spring.register(CustomPermissionEvaluatorWebSecurityConfig.class).autowire();
 		this.spring.register(CustomPermissionEvaluatorWebSecurityConfig.class).autowire();
 		assertThat(this.methodSecurityService.hasPermission("allowed")).isNull();
 		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)
 	@EnableGlobalMethodSecurity(prePostEnabled = true)

+ 2 - 3
config/src/test/java/org/springframework/security/config/annotation/sec2758/Sec2758Tests.java

@@ -44,7 +44,6 @@ import org.springframework.test.web.servlet.MockMvc;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RestController;
 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.request.MockMvcRequestBuilders.get;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
 
@@ -76,8 +75,8 @@ public class Sec2758Tests {
 	@Test
 	@Test
 	public void methodSecurityWhenNullifyingRolePrefixThenPassivityRestored() {
 	public void methodSecurityWhenNullifyingRolePrefixThenPassivityRestored() {
 		this.spring.register(SecurityConfig.class).autowire();
 		this.spring.register(SecurityConfig.class).autowire();
-		assertThatCode(() -> this.service.doJsr250()).doesNotThrowAnyException();
-		assertThatCode(() -> this.service.doPreAuthorize()).doesNotThrowAnyException();
+		this.service.doJsr250();
+		this.service.doPreAuthorize();
 	}
 	}
 
 
 	@EnableWebSecurity
 	@EnableWebSecurity

+ 1 - 2
config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java

@@ -56,7 +56,6 @@ import org.springframework.web.accept.HeaderContentNegotiationStrategy;
 import org.springframework.web.filter.OncePerRequestFilter;
 import org.springframework.web.filter.OncePerRequestFilter;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.assertThatExceptionOfType;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -142,7 +141,7 @@ public class WebSecurityConfigurerAdapterTests {
 	public void loadConfigWhenUserDetailsServiceHasCircularReferenceThenStillLoads() {
 	public void loadConfigWhenUserDetailsServiceHasCircularReferenceThenStillLoads() {
 		this.spring.register(RequiresUserDetailsServiceConfig.class, UserDetailsServiceConfig.class).autowire();
 		this.spring.register(RequiresUserDetailsServiceConfig.class, UserDetailsServiceConfig.class).autowire();
 		MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class);
 		MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class);
-		assertThatCode(() -> myFilter.userDetailsService.loadUserByUsername("user")).doesNotThrowAnyException();
+		myFilter.userDetailsService.loadUserByUsername("user");
 		assertThatExceptionOfType(UsernameNotFoundException.class)
 		assertThatExceptionOfType(UsernameNotFoundException.class)
 				.isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin"));
 				.isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin"));
 	}
 	}

+ 18 - 12
config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java

@@ -21,6 +21,7 @@ import javax.servlet.http.HttpServletRequest;
 import org.junit.Rule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.Test;
 
 
+import org.springframework.beans.factory.BeanCreationException;
 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
 import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
 import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -46,7 +47,7 @@ import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 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.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -131,32 +132,37 @@ public class OAuth2ClientConfigurationTests {
 	// gh-5321
 	// gh-5321
 	@Test
 	@Test
 	public void loadContextWhenOAuth2AuthorizedClientRepositoryRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() {
 	public void loadContextWhenOAuth2AuthorizedClientRepositoryRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() {
-		assertThatThrownBy(
+		assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
 				() -> this.spring.register(OAuth2AuthorizedClientRepositoryRegisteredTwiceConfig.class).autowire())
 				() -> 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");
 								+ "' but found 2: authorizedClientRepository1,authorizedClientRepository2");
 	}
 	}
 
 
 	@Test
 	@Test
 	public void loadContextWhenClientRegistrationRepositoryNotRegisteredThenThrowNoSuchBeanDefinitionException() {
 	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");
 						"No qualifying bean of type '" + ClientRegistrationRepository.class.getName() + "' available");
 	}
 	}
 
 
 	@Test
 	@Test
 	public void loadContextWhenClientRegistrationRepositoryRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() {
 	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
 	@Test
 	public void loadContextWhenAccessTokenResponseClientRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() {
 	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");
 						"expected single matching bean but found 2: accessTokenResponseClient1,accessTokenResponseClient2");
 	}
 	}
 
 

+ 13 - 14
config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java

@@ -61,7 +61,7 @@ import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.bind.annotation.RestController;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -128,11 +128,11 @@ public class WebSecurityConfigurationTests {
 
 
 	@Test
 	@Test
 	public void loadConfigWhenWebSecurityConfigurersHaveSameOrderThenThrowBeanCreationException() {
 	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
 	@Test
@@ -155,10 +155,9 @@ public class WebSecurityConfigurationTests {
 
 
 	@Test
 	@Test
 	public void loadConfigWhenSecurityExpressionHandlerIsNullThenException() {
 	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
 	@Test
@@ -250,10 +249,10 @@ public class WebSecurityConfigurationTests {
 
 
 	@Test
 	@Test
 	public void loadConfigWhenBothAdapterAndFilterChainConfiguredThenException() {
 	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.");
 
 
 	}
 	}
 
 

+ 3 - 3
config/src/test/java/org/springframework/security/config/annotation/web/configurers/CorsConfigurerTests.java

@@ -42,7 +42,7 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
 import org.springframework.web.filter.CorsFilter;
 import org.springframework.web.filter.CorsFilter;
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 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.security.config.Customizer.withDefaults;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
 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.request.MockMvcRequestBuilders.options;
@@ -65,8 +65,8 @@ public class CorsConfigurerTests {
 
 
 	@Test
 	@Test
 	public void configureWhenNoMvcThenException() {
 	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");
 						"Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext");
 	}
 	}
 
 

+ 7 - 5
config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java

@@ -52,7 +52,7 @@ import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.servlet.support.RequestDataValueProcessor;
 import org.springframework.web.servlet.support.RequestDataValueProcessor;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.ArgumentMatchers.isNull;
 import static org.mockito.ArgumentMatchers.isNull;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -343,8 +343,9 @@ public class CsrfConfigurerTests {
 	// SEC-2749
 	// SEC-2749
 	@Test
 	@Test
 	public void configureWhenRequireCsrfProtectionMatcherNullThenException() {
 	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
 	@Test
@@ -356,8 +357,9 @@ public class CsrfConfigurerTests {
 
 
 	@Test
 	@Test
 	public void getWhenNullAuthenticationStrategyThenException() {
 	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
 	@Test

+ 9 - 8
config/src/test/java/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurerTests.java

@@ -56,7 +56,7 @@ import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RestController;
 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.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.spy;
@@ -84,9 +84,9 @@ public class ExpressionUrlAuthorizationConfigurerTests {
 
 
 	@Test
 	@Test
 	public void configureWhenHasRoleStartingWithStringRoleThenException() {
 	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'");
 						"role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_USER'");
 	}
 	}
 
 
@@ -98,15 +98,16 @@ public class ExpressionUrlAuthorizationConfigurerTests {
 
 
 	@Test
 	@Test
 	public void configureWhenAuthorizedRequestsAndNoRequestsThenException() {
 	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())");
 						"At least one mapping is required (i.e. authorizeRequests().anyRequest().authenticated())");
 	}
 	}
 
 
 	@Test
 	@Test
 	public void configureWhenAnyRequestIncompleteMappingThenException() {
 	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
 	@Test

+ 10 - 7
config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.java

@@ -36,7 +36,7 @@ import org.springframework.test.web.servlet.MockMvc;
 import org.springframework.test.web.servlet.MvcResult;
 import org.springframework.test.web.servlet.MvcResult;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.security.config.Customizer.withDefaults;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
 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.header;
@@ -320,14 +320,16 @@ public class HeadersConfigurerTests {
 
 
 	@Test
 	@Test
 	public void configureWhenContentSecurityPolicyEmptyThenException() {
 	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
 	@Test
 	public void configureWhenContentSecurityPolicyEmptyInLambdaThenException() {
 	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
 	@Test
@@ -381,8 +383,9 @@ public class HeadersConfigurerTests {
 
 
 	@Test
 	@Test
 	public void configureWhenFeaturePolicyEmptyThenException() {
 	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
 	@Test

+ 19 - 13
config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.java

@@ -36,7 +36,7 @@ import org.springframework.security.web.authentication.logout.LogoutSuccessHandl
 import org.springframework.security.web.util.matcher.RequestMatcher;
 import org.springframework.security.web.util.matcher.RequestMatcher;
 import org.springframework.test.web.servlet.MockMvc;
 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.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.spy;
@@ -66,26 +66,30 @@ public class LogoutConfigurerTests {
 
 
 	@Test
 	@Test
 	public void configureWhenDefaultLogoutSuccessHandlerForHasNullLogoutHandlerThenException() {
 	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
 	@Test
 	public void configureWhenDefaultLogoutSuccessHandlerForHasNullLogoutHandlerInLambdaThenException() {
 	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
 	@Test
 	public void configureWhenDefaultLogoutSuccessHandlerForHasNullMatcherThenException() {
 	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
 	@Test
 	public void configureWhenDefaultLogoutSuccessHandlerForHasNullMatcherInLambdaThenException() {
 	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
 	@Test
@@ -161,14 +165,16 @@ public class LogoutConfigurerTests {
 	// SEC-3170
 	// SEC-3170
 	@Test
 	@Test
 	public void configureWhenLogoutHandlerNullThenException() {
 	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
 	@Test
 	public void configureWhenLogoutHandlerNullInLambdaThenException() {
 	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
 	// SEC-3170

+ 7 - 6
config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.java

@@ -33,7 +33,7 @@ import org.springframework.security.web.firewall.HttpFirewall;
 import org.springframework.security.web.firewall.RequestRejectedException;
 import org.springframework.security.web.firewall.RequestRejectedException;
 import org.springframework.test.web.servlet.MockMvc;
 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;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
 
 
 /**
 /**
@@ -54,21 +54,22 @@ public class NamespaceHttpFirewallTests {
 	@Test
 	@Test
 	public void requestWhenPathContainsDoubleDotsThenBehaviorMatchesNamespace() {
 	public void requestWhenPathContainsDoubleDotsThenBehaviorMatchesNamespace() {
 		this.rule.register(HttpFirewallConfig.class).autowire();
 		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
 	@Test
 	public void requestWithCustomFirewallThenBehaviorMatchesNamespace() {
 	public void requestWithCustomFirewallThenBehaviorMatchesNamespace() {
 		this.rule.register(CustomHttpFirewallConfig.class).autowire();
 		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
 	@Test
 	public void requestWithCustomFirewallBeanThenBehaviorMatchesNamespace() {
 	public void requestWithCustomFirewallBeanThenBehaviorMatchesNamespace() {
 		this.rule.register(CustomHttpFirewallBeanConfig.class).autowire();
 		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
 	@EnableWebSecurity

+ 4 - 4
config/src/test/java/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.java

@@ -27,7 +27,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
 import org.springframework.security.config.test.SpringTestRule;
 import org.springframework.security.config.test.SpringTestRule;
 import org.springframework.test.web.servlet.MockMvc;
 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.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.get;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@@ -57,9 +57,9 @@ public class PermitAllSupportTests {
 
 
 	@Test
 	@Test
 	public void configureWhenNotAuthorizeRequestsThenException() {
 	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
 	@EnableWebSecurity

+ 11 - 6
config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java

@@ -47,7 +47,8 @@ import org.springframework.test.web.servlet.MockMvc;
 import org.springframework.test.web.servlet.MvcResult;
 import org.springframework.test.web.servlet.MvcResult;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -81,8 +82,10 @@ public class RememberMeConfigurerTests {
 	@Test
 	@Test
 	public void postWhenNoUserDetailsServiceThenException() {
 	public void postWhenNoUserDetailsServiceThenException() {
 		this.spring.register(NullUserDetailsConfig.class).autowire();
 		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
 	@Test
@@ -168,9 +171,11 @@ public class RememberMeConfigurerTests {
 
 
 	@Test
 	@Test
 	public void configureWhenRememberMeCookieNameAndRememberMeServicesThenException() {
 	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
 	@Test

+ 6 - 4
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java

@@ -29,6 +29,7 @@ import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.Test;
 
 
+import org.springframework.beans.factory.BeanCreationException;
 import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
 import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.ApplicationListener;
 import org.springframework.context.ApplicationListener;
@@ -91,7 +92,7 @@ import org.springframework.test.web.servlet.MockMvc;
 import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
 import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -479,9 +480,10 @@ public class OAuth2LoginConfigurerTests {
 
 
 	@Test
 	@Test
 	public void oidcLoginCustomWithNoUniqueJwtDecoderFactory() {
 	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<org.springframework.security.oauth2.client.registration.ClientRegistration>' "
 						+ "'org.springframework.security.oauth2.jwt.JwtDecoderFactory<org.springframework.security.oauth2.client.registration.ClientRegistration>' "
 						+ "available: expected single matching bean but found 2: jwtDecoderFactory1,jwtDecoderFactory2");
 						+ "available: expected single matching bean but found 2: jwtDecoderFactory1,jwtDecoderFactory2");
 	}
 	}

+ 26 - 20
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java

@@ -133,7 +133,8 @@ import org.springframework.web.client.RestOperations;
 import org.springframework.web.context.support.GenericWebApplicationContext;
 import org.springframework.web.context.support.GenericWebApplicationContext;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.containsString;
 import static org.hamcrest.CoreMatchers.startsWith;
 import static org.hamcrest.CoreMatchers.startsWith;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.any;
@@ -565,9 +566,10 @@ public class OAuth2ResourceServerConfigurerTests {
 
 
 	@Test
 	@Test
 	public void getBearerTokenResolverWhenDuplicateResolverBeansThenWiringException() {
 	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
 	@Test
@@ -675,7 +677,8 @@ public class OAuth2ResourceServerConfigurerTests {
 		context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder);
 		context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder);
 		this.spring.context(context).autowire();
 		this.spring.context(context).autowire();
 		OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
 		OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
-		assertThatCode(() -> jwtConfigurer.getJwtDecoder()).isInstanceOf(NoUniqueBeanDefinitionException.class);
+		assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
+				.isThrownBy(() -> jwtConfigurer.getJwtDecoder());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -701,14 +704,14 @@ public class OAuth2ResourceServerConfigurerTests {
 	public void authenticationEntryPointWhenGivenNullThenThrowsException() {
 	public void authenticationEntryPointWhenGivenNullThenThrowsException() {
 		ApplicationContext context = mock(ApplicationContext.class);
 		ApplicationContext context = mock(ApplicationContext.class);
 		OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context);
 		OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context);
-		assertThatCode(() -> configurer.authenticationEntryPoint(null)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> configurer.authenticationEntryPoint(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void accessDeniedHandlerWhenGivenNullThenThrowsException() {
 	public void accessDeniedHandlerWhenGivenNullThenThrowsException() {
 		ApplicationContext context = mock(ApplicationContext.class);
 		ApplicationContext context = mock(ApplicationContext.class);
 		OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context);
 		OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context);
-		assertThatCode(() -> configurer.accessDeniedHandler(null)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> configurer.accessDeniedHandler(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -862,8 +865,8 @@ public class OAuth2ResourceServerConfigurerTests {
 
 
 	@Test
 	@Test
 	public void configureWhenOnlyIntrospectionUrlThenException() {
 	public void configureWhenOnlyIntrospectionUrlThenException() {
-		assertThatCode(() -> this.spring.register(OpaqueTokenHalfConfiguredConfig.class).autowire())
-				.isInstanceOf(BeanCreationException.class);
+		assertThatExceptionOfType(BeanCreationException.class)
+				.isThrownBy(() -> this.spring.register(OpaqueTokenHalfConfiguredConfig.class).autowire());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -991,27 +994,30 @@ public class OAuth2ResourceServerConfigurerTests {
 
 
 	@Test
 	@Test
 	public void configuredWhenMissingJwtAuthenticationProviderThenWiringException() {
 	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
 	@Test
 	public void configureWhenMissingJwkSetUriThenWiringException() {
 	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
 	@Test
 	public void configureWhenUsingBothJwtAndOpaqueThenWiringException() {
 	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
 	@Test
 	public void configureWhenUsingBothAuthenticationManagerResolverAndOpaqueThenWiringException() {
 	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
 	@Test
@@ -1064,8 +1070,8 @@ public class OAuth2ResourceServerConfigurerTests {
 		context.registerBean("converterTwo", JwtAuthenticationConverter.class, () -> converterBean);
 		context.registerBean("converterTwo", JwtAuthenticationConverter.class, () -> converterBean);
 		this.spring.context(context).autowire();
 		this.spring.context(context).autowire();
 		OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
 		OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
-		assertThatCode(jwtConfigurer::getJwtAuthenticationConverter)
-				.isInstanceOf(NoUniqueBeanDefinitionException.class);
+		assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
+				.isThrownBy(jwtConfigurer::getJwtAuthenticationConverter);
 	}
 	}
 
 
 	private static <T> void registerMockBean(GenericApplicationContext context, String name, Class<T> clazz) {
 	private static <T> void registerMockBean(GenericApplicationContext context, String name, Class<T> clazz) {

+ 8 - 7
config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java

@@ -29,7 +29,8 @@ import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.util.InMemoryResource;
 import org.springframework.security.util.InMemoryResource;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * @author Rob Winch
@@ -45,15 +46,15 @@ public class UserDetailsResourceFactoryBeanTests {
 
 
 	@Test
 	@Test
 	public void setResourceLoaderWhenNullThenThrowsException() {
 	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
 	@Test
 	public void getObjectWhenPropertiesResourceLocationNullThenThrowsIllegalStateException() {
 	public void getObjectWhenPropertiesResourceLocationNullThenThrowsIllegalStateException() {
 		this.factory.setResourceLoader(this.resourceLoader);
 		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
 	@Test
@@ -72,8 +73,8 @@ public class UserDetailsResourceFactoryBeanTests {
 	@Test
 	@Test
 	public void getObjectWhenInvalidUserThenThrowsMeaningfulException() {
 	public void getObjectWhenInvalidUserThenThrowsMeaningfulException() {
 		this.factory.setResource(new InMemoryResource("user=invalidFormatHere"));
 		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
 	@Test

+ 3 - 3
config/src/test/java/org/springframework/security/config/crypto/RsaKeyConversionServicePostProcessorTests.java

@@ -38,7 +38,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
 import org.springframework.security.config.test.SpringTestRule;
 import org.springframework.security.config.test.SpringTestRule;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}
  * Tests for {@link RsaKeyConversionServicePostProcessor}
@@ -131,9 +131,9 @@ public class RsaKeyConversionServicePostProcessorTests {
 
 
 	@Test
 	@Test
 	public void valueWhenOverridingConversionServiceThenUsed() {
 	public void valueWhenOverridingConversionServiceThenUsed() {
-		assertThatCode(
+		assertThatExceptionOfType(Exception.class).isThrownBy(
 				() -> this.spring.register(OverrideConversionServiceConfig.class, DefaultConfig.class).autowire())
 				() -> this.spring.register(OverrideConversionServiceConfig.class, DefaultConfig.class).autowire())
-						.hasRootCauseInstanceOf(IllegalArgumentException.class);
+				.withRootCauseInstanceOf(IllegalArgumentException.class);
 	}
 	}
 
 
 	@EnableWebSecurity
 	@EnableWebSecurity

+ 5 - 5
config/src/test/java/org/springframework/security/config/http/AccessDeniedConfigTests.java

@@ -36,7 +36,7 @@ import org.springframework.security.web.access.AccessDeniedHandler;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 import org.springframework.test.web.servlet.MockMvc;
 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.request.MockMvcRequestBuilders.get;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 
 
@@ -59,8 +59,8 @@ public class AccessDeniedConfigTests {
 	@Test
 	@Test
 	public void configureWhenAccessDeniedHandlerIsMissingLeadingSlashThenException() {
 	public void configureWhenAccessDeniedHandlerIsMissingLeadingSlashThenException() {
 		SpringTestContext context = this.spring.configLocations(this.xml("NoLeadingSlash"));
 		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
 	@Test
@@ -73,8 +73,8 @@ public class AccessDeniedConfigTests {
 	@Test
 	@Test
 	public void configureWhenAccessDeniedHandlerUsesPathAndRefThenException() {
 	public void configureWhenAccessDeniedHandlerUsesPathAndRefThenException() {
 		SpringTestContext context = this.spring.configLocations(this.xml("UsesPathAndRef"));
 		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) {
 	private String xml(String configName) {

+ 5 - 5
config/src/test/java/org/springframework/security/config/http/FormLoginConfigTests.java

@@ -42,7 +42,7 @@ import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.bind.annotation.RestController;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.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.get;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@@ -89,14 +89,14 @@ public class FormLoginConfigTests {
 
 
 	@Test
 	@Test
 	public void autowireWhenLoginPageIsMisconfiguredThenDetects() {
 	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
 	@Test
 	public void autowireWhenDefaultTargetUrlIsMisconfiguredThenDetects() {
 	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
 	@Test

+ 4 - 3
config/src/test/java/org/springframework/security/config/http/HttpCorsConfigTests.java

@@ -36,7 +36,7 @@ import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.cors.CorsConfiguration;
 import org.springframework.web.cors.CorsConfiguration;
 import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
 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.get;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
@@ -59,8 +59,9 @@ public class HttpCorsConfigTests {
 
 
 	@Test
 	@Test
 	public void autowireWhenMissingMvcThenGivesInformativeError() {
 	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");
 						"Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext");
 	}
 	}
 
 

+ 50 - 51
config/src/test/java/org/springframework/security/config/http/HttpHeadersConfigTests.java

@@ -37,7 +37,7 @@ import org.springframework.test.web.servlet.ResultMatcher;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RestController;
 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.request.MockMvcRequestBuilders.get;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -92,9 +92,9 @@ public class HttpHeadersConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenHeadersDisabledHavingChildElementThenAutowireFails() {
 	public void configureWhenHeadersDisabledHavingChildElementThenAutowireFails() {
-		assertThatThrownBy(() -> this.spring.configLocations(this.xml("HeadersDisabledHavingChildElement")).autowire())
-				.isInstanceOf(BeanDefinitionParsingException.class)
-				.hasMessageContaining("Cannot specify <headers disabled=\"true\"> with child elements");
+		assertThatExceptionOfType(BeanDefinitionParsingException.class)
+				.isThrownBy(() -> this.spring.configLocations(this.xml("HeadersDisabledHavingChildElement")).autowire())
+				.withMessageContaining("Cannot specify <headers disabled=\"true\"> with child elements");
 	}
 	}
 
 
 	@Test
 	@Test
@@ -185,24 +185,20 @@ public class HttpHeadersConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUsingFrameOptionsAllowFromNoOriginThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenUsingFrameOptionsAllowFromBlankOriginThenAutowireFails() {
 	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
 	@Test
@@ -243,15 +239,14 @@ public class HttpHeadersConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUsingCustomHeaderNameOnlyThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenUsingCustomHeaderValueOnlyThenAutowireFails() {
 	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
 	@Test
@@ -283,10 +278,10 @@ public class HttpHeadersConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenXssProtectionDisabledAndBlockSetThenAutowireFails() {
 	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
 	@Test
@@ -326,16 +321,16 @@ public class HttpHeadersConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUsingHpkpWithoutPinsThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenUsingHpkpWithEmptyPinsThenAutowireFails() {
 	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
 	@Test
@@ -452,42 +447,47 @@ public class HttpHeadersConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenHstsDisabledAndIncludeSubdomainsSpecifiedThenAutowireFails() {
 	public void configureWhenHstsDisabledAndIncludeSubdomainsSpecifiedThenAutowireFails() {
-		assertThatThrownBy(
+		assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(
 				() -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingIncludeSubdomains")).autowire())
 				() -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingIncludeSubdomains")).autowire())
-						.isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("include-subdomains");
+				.withMessageContaining("include-subdomains");
 	}
 	}
 
 
 	@Test
 	@Test
 	public void configureWhenHstsDisabledAndMaxAgeSpecifiedThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenHstsDisabledAndRequestMatcherSpecifiedThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenXssProtectionDisabledAndEnabledThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenXssProtectionDisabledAndBlockSpecifiedThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenFrameOptionsDisabledAndPolicySpecifiedThenAutowireFails() {
 	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
 	@Test
@@ -514,9 +514,8 @@ public class HttpHeadersConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenContentSecurityPolicyConfiguredWithEmptyDirectivesThenAutowireFails() {
 	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
 	@Test

+ 9 - 9
config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java

@@ -35,7 +35,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.context.ConfigurableWebApplicationContext;
 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.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.spy;
@@ -151,26 +151,26 @@ public class InterceptUrlConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUsingAntMatcherAndServletPathThenThrowsException() {
 	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
 	@Test
 	public void configureWhenUsingRegexMatcherAndServletPathThenThrowsException() {
 	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
 	@Test
 	public void configureWhenUsingCiRegexMatcherAndServletPathThenThrowsException() {
 	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
 	@Test
 	public void configureWhenUsingDefaultMatcherAndServletPathThenThrowsException() {
 	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) {
 	private MockServletContext mockServletContext(String servletPath) {

+ 7 - 8
config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java

@@ -111,7 +111,7 @@ import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.context.support.XmlWebApplicationContext;
 import org.springframework.web.context.support.XmlWebApplicationContext;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.willAnswer;
 import static org.mockito.BDDMockito.willAnswer;
@@ -296,8 +296,8 @@ public class MiscHttpConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenTwoFiltersWithSameOrderThenException() {
 	public void configureWhenTwoFiltersWithSameOrderThenException() {
-		assertThatCode(() -> this.spring.configLocations(xml("CollidingFilters")).autowire())
-				.isInstanceOf(BeanDefinitionParsingException.class);
+		assertThatExceptionOfType(BeanDefinitionParsingException.class)
+				.isThrownBy(() -> this.spring.configLocations(xml("CollidingFilters")).autowire());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -319,8 +319,8 @@ public class MiscHttpConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUsingInvalidLogoutSuccessUrlThenThrowsException() {
 	public void configureWhenUsingInvalidLogoutSuccessUrlThenThrowsException() {
-		assertThatCode(() -> this.spring.configLocations(xml("InvalidLogoutSuccessUrl")).autowire())
-				.isInstanceOf(BeanCreationException.class);
+		assertThatExceptionOfType(BeanCreationException.class)
+				.isThrownBy(() -> this.spring.configLocations(xml("InvalidLogoutSuccessUrl")).autowire());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -432,9 +432,8 @@ public class MiscHttpConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUserDetailsServiceInParentContextThenLocatesSuccessfully() {
 	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()) {
 		try (XmlWebApplicationContext parent = new XmlWebApplicationContext()) {
 			parent.setConfigLocations(MiscHttpConfigTests.xml("AutoConfig"));
 			parent.setConfigLocations(MiscHttpConfigTests.xml("AutoConfig"));
 			parent.refresh();
 			parent.refresh();

+ 7 - 5
config/src/test/java/org/springframework/security/config/http/MultiHttpBlockConfigTests.java

@@ -27,7 +27,7 @@ import org.springframework.test.web.servlet.MockMvc;
 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
 import org.springframework.web.bind.annotation.GetMapping;
 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.csrf;
 import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
 import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -61,14 +61,16 @@ public class MultiHttpBlockConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUsingDuplicateHttpElementsThenThrowsWiringException() {
 	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
 	@Test
 	public void configureWhenUsingIndenticallyPatternedHttpElementsThenThrowsWiringException() {
 	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);
 	}
 	}
 
 
 	/**
 	/**

+ 15 - 15
config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java

@@ -96,8 +96,7 @@ import org.springframework.util.MultiValueMap;
 import org.springframework.web.client.RestOperations;
 import org.springframework.web.client.RestOperations;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.containsString;
 import static org.hamcrest.CoreMatchers.startsWith;
 import static org.hamcrest.CoreMatchers.startsWith;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.any;
@@ -436,8 +435,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
 
 
 	@Test
 	@Test
 	public void configureWhenDecoderAndJwkSetUriThenException() {
 	public void configureWhenDecoderAndJwkSetUriThenException() {
-		assertThatThrownBy(() -> this.spring.configLocations(xml("JwtDecoderAndJwkSetUri")).autowire())
-				.isInstanceOf(BeanDefinitionParsingException.class);
+		assertThatExceptionOfType(BeanDefinitionParsingException.class)
+				.isThrownBy(() -> this.spring.configLocations(xml("JwtDecoderAndJwkSetUri")).autowire());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -554,14 +553,14 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
 
 
 	@Test
 	@Test
 	public void configureWhenOnlyIntrospectionUrlThenException() {
 	public void configureWhenOnlyIntrospectionUrlThenException() {
-		assertThatCode(() -> this.spring.configLocations(xml("OpaqueTokenHalfConfigured")).autowire())
-				.isInstanceOf(BeanDefinitionParsingException.class);
+		assertThatExceptionOfType(BeanDefinitionParsingException.class)
+				.isThrownBy(() -> this.spring.configLocations(xml("OpaqueTokenHalfConfigured")).autowire());
 	}
 	}
 
 
 	@Test
 	@Test
 	public void configureWhenIntrospectorAndIntrospectionUriThenError() {
 	public void configureWhenIntrospectorAndIntrospectionUriThenError() {
-		assertThatCode(() -> this.spring.configLocations(xml("OpaqueTokenAndIntrospectionUri")).autowire())
-				.isInstanceOf(BeanDefinitionParsingException.class);
+		assertThatExceptionOfType(BeanDefinitionParsingException.class)
+				.isThrownBy(() -> this.spring.configLocations(xml("OpaqueTokenAndIntrospectionUri")).autowire());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -642,22 +641,23 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
 
 
 	@Test
 	@Test
 	public void configuredWhenMissingJwtAuthenticationProviderThenWiringException() {
 	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
 	@Test
 	public void configureWhenMissingJwkSetUriThenWiringException() {
 	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
 	@Test
 	public void configureWhenUsingBothAuthenticationManagerResolverAndJwtThenException() {
 	public void configureWhenUsingBothAuthenticationManagerResolverAndJwtThenException() {
-		assertThatCode(
+		assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(
 				() -> this.spring.configLocations(xml("AuthenticationManagerResolverPlusOtherConfig")).autowire())
 				() -> this.spring.configLocations(xml("AuthenticationManagerResolverPlusOtherConfig")).autowire())
-						.isInstanceOf(BeanDefinitionParsingException.class)
-						.hasMessageContaining("authentication-manager-resolver-ref");
+				.withMessageContaining("authentication-manager-resolver-ref");
 	}
 	}
 
 
 	@Test
 	@Test

+ 3 - 3
config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java

@@ -44,7 +44,7 @@ import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.bind.annotation.RestController;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.hamcrest.CoreMatchers.containsString;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.anyString;
@@ -92,8 +92,8 @@ public class OpenIDConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenOpenIDAndFormLoginBothConfigureLoginPagesThenWiringException() {
 	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
 	@Test

+ 13 - 12
config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java

@@ -41,7 +41,7 @@ import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RestController;
 import org.springframework.web.bind.annotation.RestController;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.BDDMockito.given;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verify;
@@ -155,8 +155,8 @@ public class RememberMeConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUsingDataSourceAndANegativeTokenValidityThenThrowsWiringException() {
 	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
 	@Test
@@ -186,9 +186,8 @@ public class RememberMeConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUsingPersistentTokenRepositoryAndANegativeTokenValidityThenThrowsWiringException() {
 	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
 	@Test
@@ -231,8 +230,8 @@ public class RememberMeConfigTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUsingRememberMeParameterAndServicesRefThenThrowsWiringException() {
 	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 class RememberMeConfigTests {
 	 */
 	 */
 	@Test
 	@Test
 	public void configureWhenUsingRememberMeCookieAndServicesRefThenThrowsWiringException() {
 	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 "
 						"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 {
 	private ResultActions rememberAuthentication(String username, String password) throws Exception {

+ 3 - 4
config/src/test/java/org/springframework/security/config/web/server/FormLoginTests.java

@@ -47,8 +47,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.server.ServerWebExchange;
 import org.springframework.web.server.ServerWebExchange;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.atLeastOnce;
@@ -294,7 +293,7 @@ public class FormLoginTests {
 		}
 		}
 
 
 		public DefaultLoginPage assertLoginFormNotPresent() {
 		public DefaultLoginPage assertLoginFormNotPresent() {
-			assertThatThrownBy(() -> loginForm().username("")).isInstanceOf(NoSuchElementException.class);
+			assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(() -> loginForm().username(""));
 			return this;
 			return this;
 		}
 		}
 
 
@@ -353,7 +352,7 @@ public class FormLoginTests {
 			}
 			}
 
 
 			public OAuth2Login assertClientRegistrationByName(String clientName) {
 			public OAuth2Login assertClientRegistrationByName(String clientName) {
-				assertThatCode(() -> findClientRegistrationByName(clientName)).doesNotThrowAnyException();
+				findClientRegistrationByName(clientName);
 				return this;
 				return this;
 			}
 			}
 
 

+ 6 - 5
config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java

@@ -80,7 +80,7 @@ import org.springframework.web.reactive.config.EnableWebFlux;
 import org.springframework.web.server.ServerWebExchange;
 import org.springframework.web.server.ServerWebExchange;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.hamcrest.CoreMatchers.startsWith;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.anyString;
@@ -334,7 +334,7 @@ public class OAuth2ResourceServerSpecTests {
 		context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
 		context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
 		context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
 		context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
 		ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
 		ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
-		assertThatCode(() -> jwt.getJwtDecoder()).isInstanceOf(NoUniqueBeanDefinitionException.class);
+		assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -343,7 +343,7 @@ public class OAuth2ResourceServerSpecTests {
 		ServerHttpSecurity http = new ServerHttpSecurity();
 		ServerHttpSecurity http = new ServerHttpSecurity();
 		http.setApplicationContext(context);
 		http.setApplicationContext(context);
 		ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
 		ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
-		assertThatCode(() -> jwt.getJwtDecoder()).isInstanceOf(NoSuchBeanDefinitionException.class);
+		assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -366,8 +366,9 @@ public class OAuth2ResourceServerSpecTests {
 
 
 	@Test
 	@Test
 	public void configureWhenUsingBothAuthenticationManagerResolverAndOpaqueThenWiringException() {
 	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) {
 	private static Dispatcher requiresAuth(String username, String password, String response) {

+ 49 - 42
config/src/test/java/org/springframework/security/config/websocket/WebSocketMessageBrokerConfigTests.java

@@ -20,7 +20,6 @@ import java.util.HashMap;
 import java.util.Map;
 import java.util.Map;
 
 
 import org.assertj.core.api.ThrowableAssert;
 import org.assertj.core.api.ThrowableAssert;
-import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
 import org.junit.Rule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runner.RunWith;
@@ -68,8 +67,7 @@ import org.springframework.web.socket.server.HandshakeFailureException;
 import org.springframework.web.socket.server.HandshakeHandler;
 import org.springframework.web.socket.server.HandshakeHandler;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
 
 
 /**
 /**
@@ -103,8 +101,8 @@ public class WebSocketMessageBrokerConfigTests {
 	public void sendWhenNoIdSpecifiedThenIntegratesWithClientInboundChannel() {
 	public void sendWhenNoIdSpecifiedThenIntegratesWithClientInboundChannel() {
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.clientInboundChannel.send(message("/permitAll"));
 		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
 	@Test
@@ -112,141 +110,146 @@ public class WebSocketMessageBrokerConfigTests {
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
 		SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
 		headers.setNativeHeader(this.token.getHeaderName(), this.token.getToken());
 		headers.setNativeHeader(this.token.getHeaderName(), this.token.getToken());
-		assertThatCode(() -> this.clientInboundChannel.send(message("/permitAll", headers))).doesNotThrowAnyException();
+		this.clientInboundChannel.send(message("/permitAll", headers));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenAnonymousMessageWithConnectAckMessageTypeThenPermitted() {
 	public void sendWhenAnonymousMessageWithConnectAckMessageTypeThenPermitted() {
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		Message<?> message = message("/permitAll", SimpMessageType.CONNECT_ACK);
 		Message<?> message = message("/permitAll", SimpMessageType.CONNECT_ACK);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenAnonymousMessageWithDisconnectMessageTypeThenPermitted() {
 	public void sendWhenAnonymousMessageWithDisconnectMessageTypeThenPermitted() {
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		Message<?> message = message("/permitAll", SimpMessageType.DISCONNECT);
 		Message<?> message = message("/permitAll", SimpMessageType.DISCONNECT);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenAnonymousMessageWithDisconnectAckMessageTypeThenPermitted() {
 	public void sendWhenAnonymousMessageWithDisconnectAckMessageTypeThenPermitted() {
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		Message<?> message = message("/permitAll", SimpMessageType.DISCONNECT_ACK);
 		Message<?> message = message("/permitAll", SimpMessageType.DISCONNECT_ACK);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenAnonymousMessageWithHeartbeatMessageTypeThenPermitted() {
 	public void sendWhenAnonymousMessageWithHeartbeatMessageTypeThenPermitted() {
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		Message<?> message = message("/permitAll", SimpMessageType.HEARTBEAT);
 		Message<?> message = message("/permitAll", SimpMessageType.HEARTBEAT);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenAnonymousMessageWithMessageMessageTypeThenPermitted() {
 	public void sendWhenAnonymousMessageWithMessageMessageTypeThenPermitted() {
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		Message<?> message = message("/permitAll", SimpMessageType.MESSAGE);
 		Message<?> message = message("/permitAll", SimpMessageType.MESSAGE);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenAnonymousMessageWithOtherMessageTypeThenPermitted() {
 	public void sendWhenAnonymousMessageWithOtherMessageTypeThenPermitted() {
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		Message<?> message = message("/permitAll", SimpMessageType.OTHER);
 		Message<?> message = message("/permitAll", SimpMessageType.OTHER);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenAnonymousMessageWithSubscribeMessageTypeThenPermitted() {
 	public void sendWhenAnonymousMessageWithSubscribeMessageTypeThenPermitted() {
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		Message<?> message = message("/permitAll", SimpMessageType.SUBSCRIBE);
 		Message<?> message = message("/permitAll", SimpMessageType.SUBSCRIBE);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenAnonymousMessageWithUnsubscribeMessageTypeThenPermitted() {
 	public void sendWhenAnonymousMessageWithUnsubscribeMessageTypeThenPermitted() {
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		this.spring.configLocations(xml("NoIdConfig")).autowire();
 		Message<?> message = message("/permitAll", SimpMessageType.UNSUBSCRIBE);
 		Message<?> message = message("/permitAll", SimpMessageType.UNSUBSCRIBE);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenConnectWithoutCsrfTokenThenDenied() {
 	public void sendWhenConnectWithoutCsrfTokenThenDenied() {
 		this.spring.configLocations(xml("SyncConfig")).autowire();
 		this.spring.configLocations(xml("SyncConfig")).autowire();
 		Message<?> message = message("/message", SimpMessageType.CONNECT);
 		Message<?> message = message("/message", SimpMessageType.CONNECT);
-		assertThatThrownBy(send(message)).hasCauseInstanceOf(InvalidCsrfTokenException.class);
+		assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
+				.withCauseInstanceOf(InvalidCsrfTokenException.class);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenConnectWithSameOriginDisabledThenCsrfTokenNotRequired() {
 	public void sendWhenConnectWithSameOriginDisabledThenCsrfTokenNotRequired() {
 		this.spring.configLocations(xml("SyncSameOriginDisabledConfig")).autowire();
 		this.spring.configLocations(xml("SyncSameOriginDisabledConfig")).autowire();
 		Message<?> message = message("/message", SimpMessageType.CONNECT);
 		Message<?> message = message("/message", SimpMessageType.CONNECT);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenInterceptWiredForMessageTypeThenDeniesOnTypeMismatch() {
 	public void sendWhenInterceptWiredForMessageTypeThenDeniesOnTypeMismatch() {
 		this.spring.configLocations(xml("MessageInterceptTypeConfig")).autowire();
 		this.spring.configLocations(xml("MessageInterceptTypeConfig")).autowire();
 		Message<?> message = message("/permitAll", SimpMessageType.MESSAGE);
 		Message<?> message = message("/permitAll", SimpMessageType.MESSAGE);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 		message = message("/permitAll", SimpMessageType.UNSUBSCRIBE);
 		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);
 		message = message("/anyOther", SimpMessageType.MESSAGE);
-		assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
+				.withCauseInstanceOf(AccessDeniedException.class);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenInterceptWiredForSubscribeTypeThenDeniesOnTypeMismatch() {
 	public void sendWhenInterceptWiredForSubscribeTypeThenDeniesOnTypeMismatch() {
 		this.spring.configLocations(xml("SubscribeInterceptTypeConfig")).autowire();
 		this.spring.configLocations(xml("SubscribeInterceptTypeConfig")).autowire();
 		Message<?> message = message("/permitAll", SimpMessageType.SUBSCRIBE);
 		Message<?> message = message("/permitAll", SimpMessageType.SUBSCRIBE);
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 		message = message("/permitAll", SimpMessageType.UNSUBSCRIBE);
 		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);
 		message = message("/anyOther", SimpMessageType.SUBSCRIBE);
-		assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
+				.withCauseInstanceOf(AccessDeniedException.class);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void configureWhenUsingConnectMessageTypeThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenUsingConnectAckMessageTypeThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenUsingDisconnectMessageTypeThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenUsingDisconnectAckMessageTypeThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenUsingHeartbeatMessageTypeThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenUsingOtherMessageTypeThenAutowireFails() {
 	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
 	@Test
 	public void configureWhenUsingUnsubscribeMessageTypeThenAutowireFails() {
 	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
 	@Test
@@ -301,16 +304,17 @@ public class WebSocketMessageBrokerConfigTests {
 	public void sendWhenUsingCustomPathMatcherThenSecurityAppliesIt() {
 	public void sendWhenUsingCustomPathMatcherThenSecurityAppliesIt() {
 		this.spring.configLocations(xml("CustomPathMatcherConfig")).autowire();
 		this.spring.configLocations(xml("CustomPathMatcherConfig")).autowire();
 		Message<?> message = message("/denyAll.a");
 		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");
 		message = message("/denyAll.a.b");
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenIdSpecifiedThenSecurityDoesNotIntegrateWithClientInboundChannel() {
 	public void sendWhenIdSpecifiedThenSecurityDoesNotIntegrateWithClientInboundChannel() {
 		this.spring.configLocations(xml("IdConfig")).autowire();
 		this.spring.configLocations(xml("IdConfig")).autowire();
 		Message<?> message = message("/denyAll");
 		Message<?> message = message("/denyAll");
-		assertThatCode(send(message)).doesNotThrowAnyException();
+		send(message);
 	}
 	}
 
 
 	@Test
 	@Test
@@ -318,14 +322,16 @@ public class WebSocketMessageBrokerConfigTests {
 	public void sendWhenIdSpecifiedAndExplicitlyIntegratedWhenBrokerUsesClientInboundChannel() {
 	public void sendWhenIdSpecifiedAndExplicitlyIntegratedWhenBrokerUsesClientInboundChannel() {
 		this.spring.configLocations(xml("IdIntegratedConfig")).autowire();
 		this.spring.configLocations(xml("IdIntegratedConfig")).autowire();
 		Message<?> message = message("/denyAll");
 		Message<?> message = message("/denyAll");
-		assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
+				.withCauseInstanceOf(AccessDeniedException.class);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void sendWhenNoIdSpecifiedThenSecurityDoesntOverrideCustomInterceptors() {
 	public void sendWhenNoIdSpecifiedThenSecurityDoesntOverrideCustomInterceptors() {
 		this.spring.configLocations(xml("CustomInterceptorConfig")).autowire();
 		this.spring.configLocations(xml("CustomInterceptorConfig")).autowire();
 		Message<?> message = message("/throwAll");
 		Message<?> message = message("/throwAll");
-		assertThatThrownBy(send(message)).hasCauseInstanceOf(UnsupportedOperationException.class);
+		assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
+				.withCauseInstanceOf(UnsupportedOperationException.class);
 	}
 	}
 
 
 	@Test
 	@Test
@@ -333,7 +339,8 @@ public class WebSocketMessageBrokerConfigTests {
 	public void sendWhenCustomExpressionHandlerThenAuthorizesAccordingly() {
 	public void sendWhenCustomExpressionHandlerThenAuthorizesAccordingly() {
 		this.spring.configLocations(xml("CustomExpressionHandlerConfig")).autowire();
 		this.spring.configLocations(xml("CustomExpressionHandlerConfig")).autowire();
 		Message<?> message = message("/denyNile");
 		Message<?> message = message("/denyNile");
-		assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
+		assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
+				.withCauseInstanceOf(AccessDeniedException.class);
 	}
 	}
 
 
 	private String xml(String configName) {
 	private String xml(String configName) {

+ 3 - 4
core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java

@@ -33,9 +33,7 @@ import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.core.userdetails.UserDetailsChecker;
 import org.springframework.security.core.userdetails.UserDetailsChecker;
 import org.springframework.security.crypto.password.PasswordEncoder;
 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.assertThatExceptionOfType;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -85,7 +83,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
 
 
 	@Test
 	@Test
 	public void setSchedulerWhenNullThenIllegalArgumentException() {
 	public void setSchedulerWhenNullThenIllegalArgumentException() {
-		assertThatCode(() -> this.manager.setScheduler(null)).isInstanceOf(IllegalArgumentException.class);
+		assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> this.manager.setScheduler(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -125,7 +123,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
 		this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
 		this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
 		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
 		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
 				this.user.getPassword());
 				this.user.getPassword());
-		assertThatThrownBy(() -> this.manager.authenticate(token).block()).isInstanceOf(BadCredentialsException.class);
+		assertThatExceptionOfType(BadCredentialsException.class)
+				.isThrownBy(() -> this.manager.authenticate(token).block());
 		verifyZeroInteractions(this.userDetailsPasswordService);
 		verifyZeroInteractions(this.userDetailsPasswordService);
 	}
 	}
 
 

+ 2 - 2
core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java

@@ -49,7 +49,7 @@ import org.springframework.security.crypto.password.NoOpPasswordEncoder;
 import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.security.crypto.password.PasswordEncoder;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.assertj.core.api.Assertions.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.anyString;
@@ -362,7 +362,7 @@ public class DaoAuthenticationProviderTests {
 		UserDetails user = PasswordEncodedUser.user();
 		UserDetails user = PasswordEncodedUser.user();
 		given(encoder.matches(any(), any())).willReturn(false);
 		given(encoder.matches(any(), any())).willReturn(false);
 		given(userDetailsService.loadUserByUsername(any())).willReturn(user);
 		given(userDetailsService.loadUserByUsername(any())).willReturn(user);
-		assertThatThrownBy(() -> provider.authenticate(token)).isInstanceOf(BadCredentialsException.class);
+		assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
 		verifyZeroInteractions(passwordManager);
 		verifyZeroInteractions(passwordManager);
 	}
 	}
 
 

+ 5 - 9
core/src/test/java/org/springframework/security/authentication/jaas/JaasGrantedAuthorityTests.java

@@ -18,7 +18,7 @@ package org.springframework.security.authentication.jaas;
 
 
 import org.junit.Test;
 import org.junit.Test;
 
 
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
 
 
 /**
 /**
  * @author Clement Ng
  * @author Clement Ng
@@ -26,20 +26,16 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
  */
  */
 public class JaasGrantedAuthorityTests {
 public class JaasGrantedAuthorityTests {
 
 
-	/**
-	 */
 	@Test
 	@Test
 	public void authorityWithNullRoleFailsAssertion() {
 	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
 	@Test
 	public void authorityWithNullPrincipleFailsAssertion() {
 	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");
 	}
 	}
 
 
 }
 }

+ 3 - 5
core/src/test/java/org/springframework/security/converter/RsaKeyConvertersTests.java

@@ -28,7 +28,7 @@ import org.junit.Test;
 
 
 import org.springframework.core.convert.converter.Converter;
 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}
  * Tests for {@link RsaKeyConverters}
@@ -99,8 +99,7 @@ public class RsaKeyConvertersTests {
 
 
 	@Test
 	@Test
 	public void pkcs8WhenConvertingPkcs1PrivateKeyThenIllegalArgumentException() {
 	public void pkcs8WhenConvertingPkcs1PrivateKeyThenIllegalArgumentException() {
-		assertThatCode(() -> this.pkcs8.convert(toInputStream(PKCS1_PRIVATE_KEY)))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.pkcs8.convert(toInputStream(PKCS1_PRIVATE_KEY)));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -111,8 +110,7 @@ public class RsaKeyConvertersTests {
 
 
 	@Test
 	@Test
 	public void x509WhenConvertingDerEncodedX509PublicKeyThenIllegalArgumentException() {
 	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) {
 	private static InputStream toInputStream(String string) {

+ 3 - 2
core/src/test/java/org/springframework/security/jackson2/SecurityJackson2ModulesTests.java

@@ -32,7 +32,7 @@ import org.junit.Before;
 import org.junit.Test;
 import org.junit.Test;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * @author Rob Winch
@@ -51,7 +51,8 @@ public class SecurityJackson2ModulesTests {
 	@Test
 	@Test
 	public void readValueWhenNotAllowedOrMappedThenThrowsException() {
 	public void readValueWhenNotAllowedOrMappedThenThrowsException() {
 		String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlisted\",\"property\":\"bar\"}";
 		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
 	@Test

+ 20 - 18
crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java

@@ -27,7 +27,7 @@ import org.mockito.Mock;
 import org.mockito.junit.MockitoJUnitRunner;
 import org.mockito.junit.MockitoJUnitRunner;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verify;
@@ -120,41 +120,43 @@ public class DelegatingPasswordEncoderTests {
 
 
 	@Test
 	@Test
 	public void matchesWhenUnMappedThenIllegalArgumentException() {
 	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);
 		verifyZeroInteractions(this.bcrypt, this.noop);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void matchesWhenNoClosingPrefixStringThenIllegalArgumentExcetion() {
 	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);
 		verifyZeroInteractions(this.bcrypt, this.noop);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void matchesWhenNoStartingPrefixStringThenFalse() {
 	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);
 		verifyZeroInteractions(this.bcrypt, this.noop);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void matchesWhenNoIdStringThenFalse() {
 	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);
 		verifyZeroInteractions(this.bcrypt, this.noop);
 	}
 	}
 
 
 	@Test
 	@Test
 	public void matchesWhenPrefixInMiddleThenFalse() {
 	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)
 				.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);
 		verifyZeroInteractions(this.bcrypt, this.noop);
 	}
 	}
 
 
@@ -162,9 +164,9 @@ public class DelegatingPasswordEncoderTests {
 	public void matchesWhenIdIsNullThenFalse() {
 	public void matchesWhenIdIsNullThenFalse() {
 		this.delegates = new Hashtable<>(this.delegates);
 		this.delegates = new Hashtable<>(this.delegates);
 		DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, 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);
 		verifyZeroInteractions(this.bcrypt, this.noop);
 	}
 	}
 
 

+ 8 - 0
etc/checkstyle/checkstyle.xml

@@ -14,4 +14,12 @@
 	<module name="io.spring.javaformat.checkstyle.SpringChecks">
 	<module name="io.spring.javaformat.checkstyle.SpringChecks">
 		<property name="excludes" value="io.spring.javaformat.checkstyle.check.SpringHeaderCheck" />
 		<property name="excludes" value="io.spring.javaformat.checkstyle.check.SpringHeaderCheck" />
 	</module>
 	</module>
+	<module name="com.puppycrawl.tools.checkstyle.TreeWalker">
+ 		<module name="com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineJavaCheck">
+ 			<property name="maximum" value="0"/>
+			<property name="format" value="org\.assertj\.core\.api\.Assertions\.(catchThrowable|catchThrowableOfType|assertThatThrownBy|assertThatCode)" />
+			<property name="message" value="Please use assertThatExceptionOfType." />
+			<property name="ignoreComments" value="true" />
+		</module>
+	</module>
 </module>
 </module>

+ 3 - 9
ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java

@@ -32,6 +32,7 @@ import org.springframework.core.io.ClassPathResource;
 import org.springframework.util.FileCopyUtils;
 import org.springframework.util.FileCopyUtils;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
 import static org.assertj.core.api.Assertions.fail;
 import static org.assertj.core.api.Assertions.fail;
 
 
 /**
 /**
@@ -138,15 +139,8 @@ public class ApacheDSContainerTests {
 		server.setLdapOverSslEnabled(true);
 		server.setLdapOverSslEnabled(true);
 		server.setKeyStoreFile(temporaryKeyStoreFile);
 		server.setKeyStoreFile(temporaryKeyStoreFile);
 		server.setCertificatePassord("incorrect-password");
 		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);
 	}
 	}
 
 
 	/**
 	/**

+ 3 - 3
ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerModifyPasswordTests.java

@@ -36,7 +36,7 @@ import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringRunner;
 import org.springframework.test.context.junit4.SpringRunner;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * Tests for {@link LdapUserDetailsManager#changePassword}, specifically relating to the
@@ -63,8 +63,8 @@ public class LdapUserDetailsManagerModifyPasswordTests {
 	@Test
 	@Test
 	@WithMockUser(username = "bob", password = "bobspassword", authorities = "ROLE_USER")
 	@WithMockUser(username = "bob", password = "bobspassword", authorities = "ROLE_USER")
 	public void changePasswordWhenOldPasswordIsIncorrectThenThrowsException() {
 	public void changePasswordWhenOldPasswordIsIncorrectThenThrowsException() {
-		assertThatCode(() -> this.userDetailsManager.changePassword("wrongoldpassword", "bobsnewpassword"))
-				.isInstanceOf(BadCredentialsException.class);
+		assertThatExceptionOfType(BadCredentialsException.class)
+				.isThrownBy(() -> this.userDetailsManager.changePassword("wrongoldpassword", "bobsnewpassword"));
 	}
 	}
 
 
 	@Test
 	@Test

+ 5 - 5
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeOAuth2AuthorizedClientProviderTests.java

@@ -26,7 +26,8 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
 import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link AuthorizationCodeOAuth2AuthorizedClientProvider}.
@@ -54,8 +55,7 @@ public class AuthorizationCodeOAuth2AuthorizedClientProviderTests {
 
 
 	@Test
 	@Test
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -77,8 +77,8 @@ public class AuthorizationCodeOAuth2AuthorizedClientProviderTests {
 	public void authorizeWhenAuthorizationCodeAndNotAuthorizedThenAuthorize() {
 	public void authorizeWhenAuthorizationCodeAndNotAuthorizedThenAuthorize() {
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 				.withClientRegistration(this.clientRegistration).principal(this.principal).build();
 				.withClientRegistration(this.clientRegistration).principal(this.principal).build();
-		assertThatThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext))
-				.isInstanceOf(ClientAuthorizationRequiredException.class);
+		assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
+				.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext));
 	}
 	}
 
 
 }
 }

+ 5 - 5
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests.java

@@ -26,7 +26,8 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
 import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link AuthorizationCodeReactiveOAuth2AuthorizedClientProvider}.
@@ -54,8 +55,7 @@ public class AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests {
 
 
 	@Test
 	@Test
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null).block());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -77,8 +77,8 @@ public class AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests {
 	public void authorizeWhenAuthorizationCodeAndNotAuthorizedThenAuthorize() {
 	public void authorizeWhenAuthorizationCodeAndNotAuthorizedThenAuthorize() {
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 				.withClientRegistration(this.clientRegistration).principal(this.principal).build();
 				.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());
 	}
 	}
 
 
 }
 }

+ 26 - 23
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java

@@ -35,8 +35,8 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
 import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
 import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -108,57 +108,58 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
 	public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(
+		assertThatIllegalArgumentException().isThrownBy(
 				() -> new AuthorizedClientServiceOAuth2AuthorizedClientManager(null, this.authorizedClientService))
 				() -> new AuthorizedClientServiceOAuth2AuthorizedClientManager(null, this.authorizedClientService))
-						.isInstanceOf(IllegalArgumentException.class)
-						.hasMessage("clientRegistrationRepository cannot be null");
+				.withMessage("clientRegistrationRepository cannot be null");
 	}
 	}
 
 
 	@Test
 	@Test
 	public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
 	public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(
+		assertThatIllegalArgumentException().isThrownBy(
 				() -> new AuthorizedClientServiceOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null))
 				() -> new AuthorizedClientServiceOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null))
-						.isInstanceOf(IllegalArgumentException.class)
-						.hasMessage("authorizedClientService cannot be null");
+				.withMessage("authorizedClientService cannot be null");
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() {
 	public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() {
 		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
 		OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
 				.withClientRegistrationId("invalid-registration-id").principal(this.principal).build();
 				.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")
 	@SuppressWarnings("unchecked")
@@ -308,7 +309,8 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
 				.willThrow(authorizationException);
 				.willThrow(authorizationException);
 		OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
 		OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
 				.principal(this.principal).build();
 				.principal(this.principal).build();
-		assertThatCode(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
+		assertThatExceptionOfType(ClientAuthorizationException.class)
+				.isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
 				.isEqualTo(authorizationException);
 				.isEqualTo(authorizationException);
 		verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
 		verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
 				any());
 				any());
@@ -324,7 +326,8 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
 				.willThrow(authorizationException);
 				.willThrow(authorizationException);
 		OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
 		OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
 				.principal(this.principal).build();
 				.principal(this.principal).build();
-		assertThatCode(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
+		assertThatExceptionOfType(ClientAuthorizationException.class)
+				.isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
 				.isEqualTo(authorizationException);
 				.isEqualTo(authorizationException);
 		verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
 		verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
 				any());
 				any());

+ 39 - 23
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java

@@ -39,8 +39,8 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
 import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
 import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -105,46 +105,52 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
@@ -243,7 +249,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
 				this.clientRegistration.getRegistrationId());
 				this.clientRegistration.getRegistrationId());
 		given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
 		given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
 				.willReturn(Mono.error(exception));
 				.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.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
 		verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
 		verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
 		OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
 		OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
@@ -269,7 +277,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
 				this.clientRegistration.getRegistrationId());
 				this.clientRegistration.getRegistrationId());
 		given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
 		given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
 				.willReturn(Mono.error(exception));
 				.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.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
 		verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
 		verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
 		OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
 		OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
@@ -295,7 +305,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
 				this.clientRegistration.getRegistrationId());
 				this.clientRegistration.getRegistrationId());
 		given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
 		given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
 				.willReturn(Mono.error(exception));
 				.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.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
 		verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
 		verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
 		OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
 		OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
@@ -318,7 +330,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
 				new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
 				new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
 		given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
 		given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
 				.willReturn(Mono.error(exception));
 				.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.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
 		verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
 		verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
 		OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
 		OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
@@ -344,7 +358,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
 		PublisherProbe<Void> authorizationFailureHandlerProbe = PublisherProbe.empty();
 		PublisherProbe<Void> authorizationFailureHandlerProbe = PublisherProbe.empty();
 		this.authorizedClientManager.setAuthorizationFailureHandler(
 		this.authorizedClientManager.setAuthorizationFailureHandler(
 				(client, principal, attributes) -> authorizationFailureHandlerProbe.mono());
 				(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.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
 		verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
 		verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
 		OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
 		OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();

+ 13 - 11
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java

@@ -34,7 +34,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -65,32 +65,34 @@ public class ClientCredentialsOAuth2AuthorizedClientProviderTests {
 
 
 	@Test
 	@Test
 	public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test

+ 13 - 11
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java

@@ -35,7 +35,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -66,32 +66,34 @@ public class ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests {
 
 
 	@Test
 	@Test
 	public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test

+ 7 - 7
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java

@@ -27,7 +27,7 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
 import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -41,18 +41,18 @@ public class DelegatingOAuth2AuthorizedClientProviderTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenProvidersIsEmptyThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 		DelegatingOAuth2AuthorizedClientProvider delegate = new DelegatingOAuth2AuthorizedClientProvider(
 		DelegatingOAuth2AuthorizedClientProvider delegate = new DelegatingOAuth2AuthorizedClientProvider(
 				mock(OAuth2AuthorizedClientProvider.class));
 				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
 	@Test

+ 7 - 7
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java

@@ -28,7 +28,7 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
 import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -42,18 +42,18 @@ public class DelegatingReactiveOAuth2AuthorizedClientProviderTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenProvidersIsEmptyThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 		DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(
 		DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(
 				mock(ReactiveOAuth2AuthorizedClientProvider.class));
 				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
 	@Test

+ 4 - 3
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java

@@ -29,8 +29,8 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
 import org.springframework.security.oauth2.core.OAuth2AccessToken;
 import org.springframework.security.oauth2.core.OAuth2AccessToken;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.assertThatObject;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -67,8 +67,9 @@ public class InMemoryOAuth2AuthorizedClientServiceTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenAuthorizedClientsIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test

+ 23 - 29
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java

@@ -35,7 +35,7 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
 import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
 import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
 import org.springframework.security.oauth2.core.OAuth2AccessToken;
 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;
 import static org.mockito.BDDMockito.given;
 
 
 /**
 /**
@@ -76,40 +76,36 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
 	@Test
 	@Test
 	public void constructorNullClientRegistrationRepositoryThenThrowsIllegalArgumentException() {
 	public void constructorNullClientRegistrationRepositoryThenThrowsIllegalArgumentException() {
 		this.clientRegistrationRepository = null;
 		this.clientRegistrationRepository = null;
-		assertThatThrownBy(() -> new InMemoryReactiveOAuth2AuthorizedClientService(this.clientRegistrationRepository))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new InMemoryReactiveOAuth2AuthorizedClientService(this.clientRegistrationRepository));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void loadAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() {
 	public void loadAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() {
 		this.clientRegistrationId = null;
 		this.clientRegistrationId = null;
-		assertThatThrownBy(
-				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
-						.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(
+				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void loadAuthorizedClientWhenClientRegistrationIdEmptyThenIllegalArgumentException() {
 	public void loadAuthorizedClientWhenClientRegistrationIdEmptyThenIllegalArgumentException() {
 		this.clientRegistrationId = "";
 		this.clientRegistrationId = "";
-		assertThatThrownBy(
-				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
-						.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(
+				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void loadAuthorizedClientWhenPrincipalNameNullThenIllegalArgumentException() {
 	public void loadAuthorizedClientWhenPrincipalNameNullThenIllegalArgumentException() {
 		this.principalName = null;
 		this.principalName = null;
-		assertThatThrownBy(
-				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
-						.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(
+				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void loadAuthorizedClientWhenPrincipalNameEmptyThenIllegalArgumentException() {
 	public void loadAuthorizedClientWhenPrincipalNameEmptyThenIllegalArgumentException() {
 		this.principalName = "";
 		this.principalName = "";
-		assertThatThrownBy(
-				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
-						.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(
+				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -145,8 +141,8 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
 	@Test
 	@Test
 	public void saveAuthorizedClientWhenAuthorizedClientNullThenIllegalArgumentException() {
 	public void saveAuthorizedClientWhenAuthorizedClientNullThenIllegalArgumentException() {
 		OAuth2AuthorizedClient authorizedClient = null;
 		OAuth2AuthorizedClient authorizedClient = null;
-		assertThatThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -154,38 +150,36 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
 		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
 		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
 				this.principalName, this.accessToken);
 				this.principalName, this.accessToken);
 		this.principal = null;
 		this.principal = null;
-		assertThatThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void removeAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() {
 	public void removeAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() {
 		this.clientRegistrationId = null;
 		this.clientRegistrationId = null;
-		assertThatThrownBy(
-				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
-						.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(
+				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void removeAuthorizedClientWhenClientRegistrationIdEmptyThenIllegalArgumentException() {
 	public void removeAuthorizedClientWhenClientRegistrationIdEmptyThenIllegalArgumentException() {
 		this.clientRegistrationId = "";
 		this.clientRegistrationId = "";
-		assertThatThrownBy(
-				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
-						.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(
+				() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void removeAuthorizedClientWhenPrincipalNameNullThenIllegalArgumentException() {
 	public void removeAuthorizedClientWhenPrincipalNameNullThenIllegalArgumentException() {
 		this.principalName = null;
 		this.principalName = null;
-		assertThatThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(this.clientRegistrationId,
-				this.principalName)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientService
+				.removeAuthorizedClient(this.clientRegistrationId, this.principalName));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void removeAuthorizedClientWhenPrincipalNameEmptyThenIllegalArgumentException() {
 	public void removeAuthorizedClientWhenPrincipalNameEmptyThenIllegalArgumentException() {
 		this.principalName = "";
 		this.principalName = "";
-		assertThatThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(this.clientRegistrationId,
-				this.principalName)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientService
+				.removeAuthorizedClient(this.clientRegistrationId, this.principalName));
 	}
 	}
 
 
 	@Test
 	@Test

+ 39 - 29
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java

@@ -54,7 +54,8 @@ import org.springframework.util.Assert;
 import org.springframework.util.StringUtils;
 import org.springframework.util.StringUtils;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.assertj.core.api.Assertions.within;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyInt;
@@ -103,40 +104,45 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenJdbcOperationsIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setAuthorizedClientRowMapperWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setAuthorizedClientParametersMapperWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void loadAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
@@ -177,26 +183,28 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
 		Authentication principal = createPrincipal();
 		Authentication principal = createPrincipal();
 		OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
 		OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
 		this.authorizedClientService.saveAuthorizedClient(expected, principal);
 		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
 	@Test
 	public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
 	public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
 		Authentication principal = createPrincipal();
 		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
 	@Test
 	public void saveAuthorizedClientWhenPrincipalIsNullThenThrowIllegalArgumentException() {
 	public void saveAuthorizedClientWhenPrincipalIsNullThenThrowIllegalArgumentException() {
 		Authentication principal = createPrincipal();
 		Authentication principal = createPrincipal();
 		OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
 		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
 	@Test
@@ -293,15 +301,17 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
 
 
 	@Test
 	@Test
 	public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void removeAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test

+ 10 - 7
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizationContextTests.java

@@ -26,7 +26,7 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
 import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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;
 import static org.assertj.core.api.Assertions.entry;
 
 
 /**
 /**
@@ -52,20 +52,23 @@ public class OAuth2AuthorizationContextTests {
 
 
 	@Test
 	@Test
 	public void withClientRegistrationWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void withAuthorizedClientWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void withClientRegistrationWhenPrincipalIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test

+ 11 - 10
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizeRequestTests.java

@@ -26,7 +26,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
 import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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;
 import static org.assertj.core.api.Assertions.entry;
 
 
 /**
 /**
@@ -46,28 +46,29 @@ public class OAuth2AuthorizeRequestTests {
 
 
 	@Test
 	@Test
 	public void withClientRegistrationIdWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void withAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void withClientRegistrationIdWhenPrincipalIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void withClientRegistrationIdWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
 	public void withClientRegistrationIdWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> OAuth2AuthorizeRequest
+		assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest
 				.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal((String) null).build())
 				.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal((String) null).build())
-						.isInstanceOf(IllegalArgumentException.class).hasMessage("principalName cannot be empty");
+				.withMessage("principalName cannot be empty");
 	}
 	}
 
 
 	@Test
 	@Test

+ 5 - 5
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientIdTests.java

@@ -19,7 +19,7 @@ package org.springframework.security.oauth2.client;
 import org.junit.Test;
 import org.junit.Test;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link OAuth2AuthorizedClientId}.
@@ -30,14 +30,14 @@ public class OAuth2AuthorizedClientIdTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenRegistrationIdNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void constructorWhenPrincipalNameNullThenThrowIllegalArgumentException() {
 	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
 	@Test

+ 8 - 7
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java

@@ -39,7 +39,8 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenRe
 import org.springframework.web.client.RestOperations;
 import org.springframework.web.client.RestOperations;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -82,8 +83,8 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
 
 
 	@Test
 	@Test
 	public void providerWhenNullThenThrowIllegalArgumentException() {
 	public void providerWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> OAuth2AuthorizedClientProviderBuilder.builder().provider(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> OAuth2AuthorizedClientProviderBuilder.builder().provider(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -93,8 +94,8 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 				.withClientRegistration(TestClientRegistrations.clientRegistration().build()).principal(this.principal)
 				.withClientRegistration(TestClientRegistrations.clientRegistration().build()).principal(this.principal)
 				.build();
 				.build();
-		assertThatThrownBy(() -> authorizedClientProvider.authorize(authorizationContext))
-				.isInstanceOf(ClientAuthorizationRequiredException.class);
+		assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
+				.isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -155,8 +156,8 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
 		// authorization_code
 		// authorization_code
 		OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext
 		OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext
 				.withClientRegistration(clientRegistration).principal(this.principal).build();
 				.withClientRegistration(clientRegistration).principal(this.principal).build();
-		assertThatThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext))
-				.isInstanceOf(ClientAuthorizationRequiredException.class);
+		assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
+				.isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext));
 		// refresh_token
 		// refresh_token
 		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration,
 		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration,
 				this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());
 				this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());

+ 13 - 11
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java

@@ -34,7 +34,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -65,32 +65,34 @@ public class PasswordOAuth2AuthorizedClientProviderTests {
 
 
 	@Test
 	@Test
 	public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test

+ 13 - 11
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java

@@ -35,7 +35,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -66,32 +66,34 @@ public class PasswordReactiveOAuth2AuthorizedClientProviderTests {
 
 
 	@Test
 	@Test
 	public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test

+ 8 - 7
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java

@@ -38,7 +38,8 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken;
 import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
 import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -73,8 +74,8 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
 
 
 	@Test
 	@Test
 	public void providerWhenNullThenThrowIllegalArgumentException() {
 	public void providerWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -83,8 +84,8 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
 				.builder().authorizationCode().build();
 				.builder().authorizationCode().build();
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 				.withClientRegistration(this.clientRegistrationBuilder.build()).principal(this.principal).build();
 				.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
 	@Test
@@ -157,8 +158,8 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
 		// authorization_code
 		// authorization_code
 		OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext
 		OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext
 				.withClientRegistration(this.clientRegistrationBuilder.build()).principal(this.principal).build();
 				.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
 		// refresh_token
 		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
 		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
 				this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());
 				this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());

+ 16 - 14
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java

@@ -38,7 +38,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -78,32 +78,34 @@ public class RefreshTokenOAuth2AuthorizedClientProviderTests {
 
 
 	@Test
 	@Test
 	public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
@@ -193,9 +195,9 @@ public class RefreshTokenOAuth2AuthorizedClientProviderTests {
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 				.withAuthorizedClient(this.authorizedClient).principal(this.principal)
 				.withAuthorizedClient(this.authorizedClient).principal(this.principal)
 				.attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, invalidRequestScope).build();
 				.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 + "'");
 						+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
 	}
 	}
 
 

+ 16 - 14
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java

@@ -39,7 +39,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -79,32 +79,34 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
 
 
 	@Test
 	@Test
 	public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void setClockWhenNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
@@ -196,9 +198,9 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 		OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
 				.withAuthorizedClient(this.authorizedClient).principal(this.principal)
 				.withAuthorizedClient(this.authorizedClient).principal(this.principal)
 				.attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, invalidRequestScope).build();
 				.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 + "'");
 						+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
 	}
 	}
 
 

+ 11 - 11
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.TestOAuth2Authorization
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -69,8 +70,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() {
 	public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationProvider(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationProvider(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -84,10 +84,10 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
 				.errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build();
 				.errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build();
 		OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
 		OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
 				authorizationResponse);
 				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
 	@Test
@@ -96,10 +96,10 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
 				.build();
 				.build();
 		OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
 		OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
 				authorizationResponse);
 				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
 	@Test

+ 12 - 12
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.TestOAuth2Authorization
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link OAuth2AuthorizationCodeAuthenticationToken}.
@@ -55,14 +55,14 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests {
 
 
 	@Test
 	@Test
 	public void constructorAuthorizationRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
 	public void constructorAuthorizationRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void constructorAuthorizationRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
 	public void constructorAuthorizationRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -81,21 +81,21 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests {
 
 
 	@Test
 	@Test
 	public void constructorTokenRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
 	public void constructorTokenRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange,
-				this.accessToken)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null,
+				this.authorizationExchange, this.accessToken));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void constructorTokenRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
 	public void constructorTokenRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(
-				() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null, this.accessToken))
-						.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(
+				() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null, this.accessToken));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void constructorTokenRequestResponseWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
 	public void constructorTokenRequestResponseWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration,
-				this.authorizationExchange, null)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration,
+						this.authorizationExchange, null));
 	}
 	}
 
 
 	@Test
 	@Test

+ 4 - 4
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.TestOAuth2Authorization
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
 import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 
 
@@ -70,13 +70,13 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests {
 	@Test
 	@Test
 	public void authenticateWhenErrorThenOAuth2AuthorizationException() {
 	public void authenticateWhenErrorThenOAuth2AuthorizationException() {
 		this.authorizationResponse = TestOAuth2AuthorizationResponses.error();
 		this.authorizationResponse = TestOAuth2AuthorizationResponses.error();
-		assertThatCode(() -> authenticate()).isInstanceOf(OAuth2AuthorizationException.class);
+		assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
 	}
 	}
 
 
 	@Test
 	@Test
 	public void authenticateWhenStateNotEqualThenOAuth2AuthorizationException() {
 	public void authenticateWhenStateNotEqualThenOAuth2AuthorizationException() {
 		this.authorizationRequest.state("notequal");
 		this.authorizationRequest.state("notequal");
-		assertThatCode(() -> authenticate()).isInstanceOf(OAuth2AuthorizationException.class);
+		assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -97,7 +97,7 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests {
 	public void authenticateWhenOAuth2AuthorizationExceptionThenOAuth2AuthorizationException() {
 	public void authenticateWhenOAuth2AuthorizationExceptionThenOAuth2AuthorizationException() {
 		given(this.accessTokenResponseClient.getTokenResponse(any()))
 		given(this.accessTokenResponseClient.getTokenResponse(any()))
 				.willReturn(Mono.error(() -> new OAuth2AuthorizationException(new OAuth2Error("error"))));
 				.willReturn(Mono.error(() -> new OAuth2AuthorizationException(new OAuth2Error("error"))));
-		assertThatCode(() -> authenticate()).isInstanceOf(OAuth2AuthorizationException.class);
+		assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
 	}
 	}
 
 
 	private OAuth2AuthorizationCodeAuthenticationToken authenticate() {
 	private OAuth2AuthorizationCodeAuthenticationToken authenticate() {

+ 13 - 15
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.DefaultOAuth2User;
 import org.springframework.security.oauth2.core.user.OAuth2User;
 import org.springframework.security.oauth2.core.user.OAuth2User;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.ArgumentMatchers.anyCollection;
 import static org.mockito.ArgumentMatchers.anyCollection;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -90,22 +90,20 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
 	@Test
 	@Test
 	public void constructorWhenNullAccessTokenResponseClientThenIllegalArgumentException() {
 	public void constructorWhenNullAccessTokenResponseClientThenIllegalArgumentException() {
 		this.accessTokenResponseClient = null;
 		this.accessTokenResponseClient = null;
-		assertThatThrownBy(
-				() -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService))
-						.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(
+				() -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void constructorWhenNullUserServiceThenIllegalArgumentException() {
 	public void constructorWhenNullUserServiceThenIllegalArgumentException() {
 		this.userService = null;
 		this.userService = null;
-		assertThatThrownBy(
-				() -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService))
-						.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(
+				() -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
 	public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.manager.setAuthoritiesMapper(null)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setAuthoritiesMapper(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -113,8 +111,8 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
 		// we didn't do anything because it should cause a ClassCastException (as verified
 		// we didn't do anything because it should cause a ClassCastException (as verified
 		// below)
 		// below)
 		TestingAuthenticationToken token = new TestingAuthenticationToken("a", "b");
 		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
 	@Test
@@ -127,15 +125,15 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
 	@Test
 	@Test
 	public void authenticationWhenErrorThenOAuth2AuthenticationException() {
 	public void authenticationWhenErrorThenOAuth2AuthenticationException() {
 		this.authorizationResponseBldr = OAuth2AuthorizationResponse.error("error").state("state");
 		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
 	@Test
 	public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() {
 	public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() {
 		this.authorizationResponseBldr.state("notmatch");
 		this.authorizationResponseBldr.state("notmatch");
-		assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block())
-				.isInstanceOf(OAuth2AuthenticationException.class);
+		assertThatExceptionOfType(OAuth2AuthenticationException.class)
+				.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
 	}
 	}
 
 
 	@Test
 	@Test

+ 26 - 24
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.OAuth2AuthorizationRequ
 import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link DefaultAuthorizationCodeTokenResponseClient}.
@@ -74,20 +75,17 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
 
 
 	@Test
 	@Test
 	public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
 	public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
 	public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -151,22 +149,22 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
 		String accessTokenSuccessResponse = "{\n" + "	\"access_token\": \"access-token-1234\",\n"
 		String accessTokenSuccessResponse = "{\n" + "	\"access_token\": \"access-token-1234\",\n"
 				+ "   \"token_type\": \"not-bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
 				+ "   \"token_type\": \"not-bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		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")
 						"[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
 	@Test
 	public void getTokenResponseWhenSuccessResponseAndMissingTokenTypeParameterThenThrowOAuth2AuthorizationException() {
 	public void getTokenResponseWhenSuccessResponseAndMissingTokenTypeParameterThenThrowOAuth2AuthorizationException() {
 		String accessTokenSuccessResponse = "{\n" + "	\"access_token\": \"access-token-1234\"\n" + "}\n";
 		String accessTokenSuccessResponse = "{\n" + "	\"access_token\": \"access-token-1234\"\n" + "}\n";
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		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")
 						"[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
 	@Test
@@ -195,8 +193,9 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
 	public void getTokenResponseWhenTokenUriInvalidThenThrowOAuth2AuthorizationException() {
 	public void getTokenResponseWhenTokenUriInvalidThenThrowOAuth2AuthorizationException() {
 		String invalidTokenUri = "https://invalid-provider.com/oauth2/token";
 		String invalidTokenUri = "https://invalid-provider.com/oauth2/token";
 		ClientRegistration clientRegistration = this.from(this.clientRegistration).tokenUri(invalidTokenUri).build();
 		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");
 						"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
 	}
 	}
 
 
@@ -209,8 +208,9 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
 				+ "   \"custom_parameter_2\": \"custom-value-2\"\n";
 				+ "   \"custom_parameter_2\": \"custom-value-2\"\n";
 		// "}\n"; // Make the JSON invalid/malformed
 		// "}\n"; // Make the JSON invalid/malformed
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		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");
 						"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
 	}
 	}
 
 
@@ -218,16 +218,18 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
 	public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
 	public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
 		String accessTokenErrorResponse = "{\n" + "   \"error\": \"unauthorized_client\"\n" + "}\n";
 		String accessTokenErrorResponse = "{\n" + "   \"error\": \"unauthorized_client\"\n" + "}\n";
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		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
 	@Test
 	public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
 	public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		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() {
 	private OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest() {

+ 25 - 23
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultClientCredentialsTokenResponseClientTests.java

@@ -36,7 +36,8 @@ import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link DefaultClientCredentialsTokenResponseClient}.
@@ -69,20 +70,17 @@ public class DefaultClientCredentialsTokenResponseClientTests {
 
 
 	@Test
 	@Test
 	public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
 	public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
 	public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -152,11 +150,11 @@ public class DefaultClientCredentialsTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 				this.clientRegistration);
 				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")
 						"[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
 	@Test
@@ -165,11 +163,11 @@ public class DefaultClientCredentialsTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 				this.clientRegistration);
 				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")
 						"[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
 	@Test
@@ -203,8 +201,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
 		ClientRegistration clientRegistration = this.from(this.clientRegistration).tokenUri(invalidTokenUri).build();
 		ClientRegistration clientRegistration = this.from(this.clientRegistration).tokenUri(invalidTokenUri).build();
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 				clientRegistration);
 				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");
 						"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
 	}
 	}
 
 
@@ -218,8 +217,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 				this.clientRegistration);
 				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");
 						"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
 	}
 	}
 
 
@@ -229,8 +229,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 				this.clientRegistration);
 				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
 	@Test
@@ -238,8 +239,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 		OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
 				this.clientRegistration);
 				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");
 						"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
 	}
 	}
 
 

+ 16 - 16
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultPasswordTokenResponseClientTests.java

@@ -37,7 +37,8 @@ import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link DefaultPasswordTokenResponseClient}.
@@ -72,20 +73,17 @@ public class DefaultPasswordTokenResponseClientTests {
 
 
 	@Test
 	@Test
 	public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
 	public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
 	public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -141,11 +139,11 @@ public class DefaultPasswordTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 				this.clientRegistrationBuilder.build(), this.username, this.password);
 				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")
 						"[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
 	@Test
@@ -169,8 +167,9 @@ public class DefaultPasswordTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 				this.clientRegistrationBuilder.build(), this.username, this.password);
 				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
 	@Test
@@ -178,9 +177,10 @@ public class DefaultPasswordTokenResponseClientTests {
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 				this.clientRegistrationBuilder.build(), this.username, this.password);
 				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) {
 	private MockResponse jsonResponse(String json) {

+ 17 - 17
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/DefaultRefreshTokenTokenResponseClientTests.java

@@ -40,7 +40,8 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link DefaultRefreshTokenTokenResponseClient}.
@@ -76,20 +77,17 @@ public class DefaultRefreshTokenTokenResponseClientTests {
 
 
 	@Test
 	@Test
 	public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
 	public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
 	public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -144,11 +142,11 @@ public class DefaultRefreshTokenTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 				this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
 				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
 	@Test
@@ -174,8 +172,9 @@ public class DefaultRefreshTokenTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 				this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
 				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
 	@Test
@@ -183,9 +182,10 @@ public class DefaultRefreshTokenTokenResponseClientTests {
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 				this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
 				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) {
 	private MockResponse jsonResponse(String json) {

+ 4 - 5
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java

@@ -24,7 +24,7 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
 import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
 import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link OAuth2ClientCredentialsGrantRequest}.
@@ -45,8 +45,7 @@ public class OAuth2ClientCredentialsGrantRequestTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
 	public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -55,8 +54,8 @@ public class OAuth2ClientCredentialsGrantRequestTests {
 				.clientId("client-1").authorizationGrantType(AuthorizationGrantType.IMPLICIT)
 				.clientId("client-1").authorizationGrantType(AuthorizationGrantType.IMPLICIT)
 				.redirectUri("https://localhost:8080/redirect-uri").authorizationUri("https://provider.com/oauth2/auth")
 				.redirectUri("https://localhost:8080/redirect-uri").authorizationUri("https://provider.com/oauth2/auth")
 				.clientName("Client 1").build();
 				.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");
 						"clientRegistration.authorizationGrantType must be AuthorizationGrantType.CLIENT_CREDENTIALS");
 	}
 	}
 
 

+ 19 - 14
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestTests.java

@@ -23,7 +23,7 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
 import org.springframework.security.oauth2.core.AuthorizationGrantType;
 import org.springframework.security.oauth2.core.AuthorizationGrantType;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link OAuth2PasswordGrantRequest}.
@@ -41,32 +41,37 @@ public class OAuth2PasswordGrantRequestTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void constructorWhenUsernameIsEmptyThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void constructorWhenPasswordIsEmptyThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException() {
 	public void constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException() {
 		ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
 		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
 	@Test

+ 10 - 7
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestTests.java

@@ -31,7 +31,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
 import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
 import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link OAuth2RefreshTokenGrantRequest}.
@@ -55,20 +55,23 @@ public class OAuth2RefreshTokenGrantRequestTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void constructorWhenRefreshTokenIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test

+ 11 - 9
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java

@@ -41,7 +41,7 @@ import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
 import org.springframework.web.reactive.function.client.WebClient;
 import org.springframework.web.reactive.function.client.WebClient;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.BDDMockito.given;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -179,10 +179,10 @@ public class WebClientReactiveAuthorizationCodeTokenResponseClientTests {
 		String accessTokenErrorResponse = "{\n" + "   \"error\": \"unauthorized_client\"\n" + "}\n";
 		String accessTokenErrorResponse = "{\n" + "   \"error\": \"unauthorized_client\"\n" + "}\n";
 		this.server.enqueue(
 		this.server.enqueue(
 				jsonResponse(accessTokenErrorResponse).setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()));
 				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
 	// gh-5594
@@ -191,8 +191,9 @@ public class WebClientReactiveAuthorizationCodeTokenResponseClientTests {
 		String accessTokenErrorResponse = "{}";
 		String accessTokenErrorResponse = "{}";
 		this.server.enqueue(
 		this.server.enqueue(
 				jsonResponse(accessTokenErrorResponse).setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()));
 				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
 	@Test
@@ -200,8 +201,9 @@ public class WebClientReactiveAuthorizationCodeTokenResponseClientTests {
 		String accessTokenSuccessResponse = "{\n" + "	\"access_token\": \"access-token-1234\",\n"
 		String accessTokenSuccessResponse = "{\n" + "	\"access_token\": \"access-token-1234\",\n"
 				+ "   \"token_type\": \"not-bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
 				+ "   \"token_type\": \"not-bearer\",\n" + "   \"expires_in\": \"3600\"\n" + "}\n";
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		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
 	@Test

+ 6 - 6
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.WebClient;
 import org.springframework.web.reactive.function.client.WebClientResponseException;
 import org.springframework.web.reactive.function.client.WebClientResponseException;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.BDDMockito.given;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -134,11 +134,11 @@ public class WebClientReactiveClientCredentialsTokenResponseClientTests {
 		ClientRegistration registration = this.clientRegistration.build();
 		ClientRegistration registration = this.clientRegistration.build();
 		enqueueUnexpectedResponse();
 		enqueueUnexpectedResponse();
 		OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
 		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() {
 	private void enqueueUnexpectedResponse() {

+ 19 - 20
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactivePasswordTokenResponseClientTests.java

@@ -36,7 +36,8 @@ import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link WebClientReactivePasswordTokenResponseClient}.
@@ -70,14 +71,12 @@ public class WebClientReactivePasswordTokenResponseClientTests {
 
 
 	@Test
 	@Test
 	public void setWebClientWhenClientIsNullThenThrowIllegalArgumentException() {
 	public void setWebClientWhenClientIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.setWebClient(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setWebClient(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block())
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -134,12 +133,12 @@ public class WebClientReactivePasswordTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 				this.clientRegistrationBuilder.build(), this.username, this.password);
 				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
 	@Test
@@ -164,10 +163,10 @@ public class WebClientReactivePasswordTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 				this.clientRegistrationBuilder.build(), this.username, this.password);
 				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
 	@Test
@@ -175,11 +174,11 @@ public class WebClientReactivePasswordTokenResponseClientTests {
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 		OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
 				this.clientRegistrationBuilder.build(), this.username, this.password);
 				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) {
 	private MockResponse jsonResponse(String json) {

+ 18 - 18
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveRefreshTokenTokenResponseClientTests.java

@@ -40,7 +40,8 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link WebClientReactiveRefreshTokenTokenResponseClient}.
@@ -76,14 +77,12 @@ public class WebClientReactiveRefreshTokenTokenResponseClientTests {
 
 
 	@Test
 	@Test
 	public void setWebClientWhenClientIsNullThenThrowIllegalArgumentException() {
 	public void setWebClientWhenClientIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.setWebClient(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setWebClient(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
 	public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block())
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -138,10 +137,11 @@ public class WebClientReactiveRefreshTokenTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 				this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
 				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
 	@Test
@@ -167,10 +167,10 @@ public class WebClientReactiveRefreshTokenTokenResponseClientTests {
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 				this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
 				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
 	@Test
@@ -178,11 +178,11 @@ public class WebClientReactiveRefreshTokenTokenResponseClientTests {
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		this.server.enqueue(new MockResponse().setResponseCode(500));
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 		OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
 				this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
 				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) {
 	private MockResponse jsonResponse(String json) {

+ 7 - 7
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandlerTests.java

@@ -23,7 +23,7 @@ import org.springframework.http.HttpStatus;
 import org.springframework.mock.http.client.MockClientHttpResponse;
 import org.springframework.mock.http.client.MockClientHttpResponse;
 import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
 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}.
  * Tests for {@link OAuth2ErrorResponseErrorHandler}.
@@ -39,9 +39,9 @@ public class OAuth2ErrorResponseErrorHandlerTests {
 		String errorResponse = "{\n" + "	\"error\": \"unauthorized_client\",\n"
 		String errorResponse = "{\n" + "	\"error\": \"unauthorized_client\",\n"
 				+ "   \"error_description\": \"The client is not authorized\"\n" + "}\n";
 				+ "   \"error_description\": \"The client is not authorized\"\n" + "}\n";
 		MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST);
 		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
 	@Test
@@ -49,9 +49,9 @@ public class OAuth2ErrorResponseErrorHandlerTests {
 		String wwwAuthenticateHeader = "Bearer realm=\"auth-realm\" error=\"insufficient_scope\" error_description=\"The access token expired\"";
 		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);
 		MockClientHttpResponse response = new MockClientHttpResponse(new byte[0], HttpStatus.BAD_REQUEST);
 		response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticateHeader);
 		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");
 	}
 	}
 
 
 }
 }

+ 3 - 3
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixinTests.java

@@ -27,7 +27,7 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
 import org.springframework.security.oauth2.core.OAuth2Error;
 import org.springframework.security.oauth2.core.OAuth2Error;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link OAuth2AuthenticationExceptionMixin}.
@@ -68,8 +68,8 @@ public class OAuth2AuthenticationExceptionMixinTests {
 	@Test
 	@Test
 	public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
 	public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
 		String json = asJson(new OAuth2AuthenticationException(new OAuth2Error("[authorization_request_not_found]")));
 		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
 	@Test

+ 3 - 3
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java

@@ -48,7 +48,7 @@ import org.springframework.util.CollectionUtils;
 import org.springframework.util.StringUtils;
 import org.springframework.util.StringUtils;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link OAuth2AuthenticationTokenMixin}.
@@ -95,8 +95,8 @@ public class OAuth2AuthenticationTokenMixinTests {
 	public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
 	public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
 		OAuth2AuthenticationToken authentication = TestOAuth2AuthenticationTokens.oidcAuthenticated();
 		OAuth2AuthenticationToken authentication = TestOAuth2AuthenticationTokens.oidcAuthenticated();
 		String json = asJson(authentication);
 		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
 	@Test

+ 6 - 5
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixinTests.java

@@ -34,7 +34,7 @@ import org.springframework.util.CollectionUtils;
 import org.springframework.util.StringUtils;
 import org.springframework.util.StringUtils;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link OAuth2AuthorizationRequestMixin}.
@@ -79,8 +79,8 @@ public class OAuth2AuthorizationRequestMixinTests {
 	@Test
 	@Test
 	public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
 	public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
 		String json = asJson(this.authorizationRequestBuilder.build());
 		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
 	@Test
@@ -128,8 +128,9 @@ public class OAuth2AuthorizationRequestMixinTests {
 	public void deserializeWhenInvalidAuthorizationGrantTypeThenThrowJsonParseException() {
 	public void deserializeWhenInvalidAuthorizationGrantTypeThenThrowJsonParseException() {
 		OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestBuilder.build();
 		OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestBuilder.build();
 		String json = asJson(authorizationRequest).replace("authorization_code", "client_credentials");
 		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) {
 	private static String asJson(OAuth2AuthorizationRequest authorizationRequest) {

+ 3 - 3
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixinTests.java

@@ -40,7 +40,7 @@ import org.springframework.util.CollectionUtils;
 import org.springframework.util.StringUtils;
 import org.springframework.util.StringUtils;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link OAuth2AuthorizedClientMixin}.
@@ -99,8 +99,8 @@ public class OAuth2AuthorizedClientMixinTests {
 		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
 		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
 				this.principalName, this.accessToken);
 				this.principalName, this.accessToken);
 		String json = asJson(authorizedClient);
 		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
 	@Test

+ 22 - 19
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.ReactiveJwtDecoder;
 import org.springframework.security.oauth2.jwt.TestJwts;
 import org.springframework.security.oauth2.jwt.TestJwts;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.ArgumentMatchers.anyCollection;
 import static org.mockito.ArgumentMatchers.anyCollection;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -113,25 +113,27 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
 	@Test
 	@Test
 	public void constructorWhenNullAccessTokenResponseClientThenIllegalArgumentException() {
 	public void constructorWhenNullAccessTokenResponseClientThenIllegalArgumentException() {
 		this.accessTokenResponseClient = null;
 		this.accessTokenResponseClient = null;
-		assertThatThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
-				this.userService)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
+						this.userService));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void constructorWhenNullUserServiceThenIllegalArgumentException() {
 	public void constructorWhenNullUserServiceThenIllegalArgumentException() {
 		this.userService = null;
 		this.userService = null;
-		assertThatThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
-				this.userService)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
+						this.userService));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setJwtDecoderFactoryWhenNullThenIllegalArgumentException() {
 	public void setJwtDecoderFactoryWhenNullThenIllegalArgumentException() {
-		assertThatThrownBy(() -> this.manager.setJwtDecoderFactory(null)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setJwtDecoderFactory(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
 	public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.manager.setAuthoritiesMapper(null)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setAuthoritiesMapper(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -139,8 +141,8 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
 		// we didn't do anything because it should cause a ClassCastException (as verified
 		// we didn't do anything because it should cause a ClassCastException (as verified
 		// below)
 		// below)
 		TestingAuthenticationToken token = new TestingAuthenticationToken("a", "b");
 		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
 	@Test
@@ -152,15 +154,15 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
 	@Test
 	@Test
 	public void authenticationWhenErrorThenOAuth2AuthenticationException() {
 	public void authenticationWhenErrorThenOAuth2AuthenticationException() {
 		this.authorizationResponseBldr = OAuth2AuthorizationResponse.error("error").state("state");
 		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
 	@Test
 	public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() {
 	public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() {
 		this.authorizationResponseBldr.state("notmatch");
 		this.authorizationResponseBldr.state("notmatch");
-		assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block())
-				.isInstanceOf(OAuth2AuthenticationException.class);
+		assertThatExceptionOfType(OAuth2AuthenticationException.class)
+				.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -172,9 +174,9 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
 		given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
 		given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
 		given(this.jwtDecoder.decode(any())).willThrow(new JwtException("ID Token Validation Error"));
 		given(this.jwtDecoder.decode(any())).willThrow(new JwtException("ID Token Validation Error"));
 		this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
 		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
 	@Test
@@ -193,8 +195,9 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
 		given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
 		given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
 		given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
 		given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
 		this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
 		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
 	@Test

+ 20 - 21
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java

@@ -36,7 +36,8 @@ import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
 import org.springframework.security.oauth2.jwt.Jwt;
 import org.springframework.security.oauth2.jwt.Jwt;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.same;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -76,33 +77,30 @@ public class OidcIdTokenDecoderFactoryTests {
 
 
 	@Test
 	@Test
 	public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException() {
 	public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setJwsAlgorithmResolverWhenNullThenThrowIllegalArgumentException() {
 	public void setJwsAlgorithmResolverWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
 	public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void createDecoderWhenClientRegistrationNullThenThrowIllegalArgumentException() {
 	public void createDecoderWhenClientRegistrationNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void createDecoderWhenJwsAlgorithmDefaultAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
 	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'. "
 						+ "for Client Registration: 'registration-id'. "
 						+ "Check to ensure you have configured the JwkSet URI.");
 						+ "Check to ensure you have configured the JwkSet URI.");
 	}
 	}
@@ -110,9 +108,9 @@ public class OidcIdTokenDecoderFactoryTests {
 	@Test
 	@Test
 	public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
 	public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
 		this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> SignatureAlgorithm.ES256);
 		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'. "
 						+ "for Client Registration: 'registration-id'. "
 						+ "Check to ensure you have configured the JwkSet URI.");
 						+ "Check to ensure you have configured the JwkSet URI.");
 	}
 	}
@@ -120,9 +118,10 @@ public class OidcIdTokenDecoderFactoryTests {
 	@Test
 	@Test
 	public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() {
 	public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() {
 		this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> MacAlgorithm.HS256);
 		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'. "
 						+ "for Client Registration: 'registration-id'. "
 						+ "Check to ensure you have configured the client secret.");
 						+ "Check to ensure you have configured the client secret.");
 	}
 	}
@@ -130,9 +129,9 @@ public class OidcIdTokenDecoderFactoryTests {
 	@Test
 	@Test
 	public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() {
 	public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() {
 		this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> null);
 		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'. "
 						+ "for Client Registration: 'registration-id'. "
 						+ "Check to ensure you have configured a valid JWS Algorithm: 'null'");
 						+ "Check to ensure you have configured a valid JWS Algorithm: 'null'");
 	}
 	}

+ 4 - 5
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenValidatorTests.java

@@ -35,7 +35,7 @@ import org.springframework.security.oauth2.jose.jws.JwsAlgorithms;
 import org.springframework.security.oauth2.jwt.Jwt;
 import org.springframework.security.oauth2.jwt.Jwt;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * @author Rob Winch
@@ -72,20 +72,19 @@ public class OidcIdTokenValidatorTests {
 	@Test
 	@Test
 	public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
 	public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
 		OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
 		OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
-		assertThatThrownBy(() -> idTokenValidator.setClockSkew(null)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> idTokenValidator.setClockSkew(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
 	public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
 		OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
 		OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
-		assertThatThrownBy(() -> idTokenValidator.setClockSkew(Duration.ofSeconds(-1)))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> idTokenValidator.setClockSkew(Duration.ofSeconds(-1)));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setClockWhenNullThenThrowIllegalArgumentException() {
 	public void setClockWhenNullThenThrowIllegalArgumentException() {
 		OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
 		OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
-		assertThatThrownBy(() -> idTokenValidator.setClock(null)).isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> idTokenValidator.setClock(null));
 	}
 	}
 
 
 	@Test
 	@Test

+ 20 - 21
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java

@@ -36,7 +36,8 @@ import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
 import org.springframework.security.oauth2.jwt.Jwt;
 import org.springframework.security.oauth2.jwt.Jwt;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.ArgumentMatchers.same;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
@@ -76,33 +77,30 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
 
 
 	@Test
 	@Test
 	public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException() {
 	public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setJwsAlgorithmResolverWhenNullThenThrowIllegalArgumentException() {
 	public void setJwsAlgorithmResolverWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
 	public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void createDecoderWhenClientRegistrationNullThenThrowIllegalArgumentException() {
 	public void createDecoderWhenClientRegistrationNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void createDecoderWhenJwsAlgorithmDefaultAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
 	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'. "
 						+ "for Client Registration: 'registration-id'. "
 						+ "Check to ensure you have configured the JwkSet URI.");
 						+ "Check to ensure you have configured the JwkSet URI.");
 	}
 	}
@@ -110,9 +108,9 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
 	@Test
 	@Test
 	public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
 	public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
 		this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> SignatureAlgorithm.ES256);
 		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'. "
 						+ "for Client Registration: 'registration-id'. "
 						+ "Check to ensure you have configured the JwkSet URI.");
 						+ "Check to ensure you have configured the JwkSet URI.");
 	}
 	}
@@ -120,9 +118,10 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
 	@Test
 	@Test
 	public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() {
 	public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() {
 		this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> MacAlgorithm.HS256);
 		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'. "
 						+ "for Client Registration: 'registration-id'. "
 						+ "Check to ensure you have configured the client secret.");
 						+ "Check to ensure you have configured the client secret.");
 	}
 	}
@@ -130,9 +129,9 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
 	@Test
 	@Test
 	public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() {
 	public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() {
 		this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> null);
 		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'. "
 						+ "for Client Registration: 'registration-id'. "
 						+ "Check to ensure you have configured a valid JWS Algorithm: 'null'");
 						+ "Check to ensure you have configured a valid JWS Algorithm: 'null'");
 	}
 	}

+ 7 - 8
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.OAuth2User;
 import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
 import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.any;
 import static org.mockito.ArgumentMatchers.same;
 import static org.mockito.ArgumentMatchers.same;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -97,8 +97,7 @@ public class OidcReactiveOAuth2UserServiceTests {
 
 
 	@Test
 	@Test
 	public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
 	public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.userService.setClaimTypeConverterFactory(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setClaimTypeConverterFactory(null));
 	}
 	}
 
 
 	@Test
 	@Test
@@ -120,8 +119,8 @@ public class OidcReactiveOAuth2UserServiceTests {
 		OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
 		OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
 				Collections.singletonMap("user", "rob"), "user");
 				Collections.singletonMap("user", "rob"), "user");
 		given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
 		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
 	@Test
@@ -132,8 +131,8 @@ public class OidcReactiveOAuth2UserServiceTests {
 		OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
 		OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
 				"user");
 				"user");
 		given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
 		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
 	@Test

+ 7 - 7
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.OidcIdToken;
 import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
 import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link OidcUserRequest}.
@@ -62,20 +62,20 @@ public class OidcUserRequestTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
 	public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> new OidcUserRequest(null, this.accessToken, this.idToken))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new OidcUserRequest(null, this.accessToken, this.idToken));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
 	public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> new OidcUserRequest(this.clientRegistration, null, this.idToken))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new OidcUserRequest(this.clientRegistration, null, this.idToken));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void constructorWhenIdTokenIsNullThenThrowIllegalArgumentException() {
 	public void constructorWhenIdTokenIsNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> new OidcUserRequest(this.clientRegistration, this.accessToken, null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new OidcUserRequest(this.clientRegistration, this.accessToken, null));
 	}
 	}
 
 
 	@Test
 	@Test

+ 4 - 7
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.OidcUser;
 import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
 import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.hamcrest.CoreMatchers.containsString;
 import static org.mockito.ArgumentMatchers.same;
 import static org.mockito.ArgumentMatchers.same;
 import static org.mockito.BDDMockito.given;
 import static org.mockito.BDDMockito.given;
@@ -113,20 +113,17 @@ public class OidcUserServiceTests {
 
 
 	@Test
 	@Test
 	public void setOauth2UserServiceWhenNullThenThrowIllegalArgumentException() {
 	public void setOauth2UserServiceWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.userService.setOauth2UserService(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setOauth2UserService(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
 	public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.userService.setClaimTypeConverterFactory(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setClaimTypeConverterFactory(null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setAccessibleScopesWhenNullThenThrowIllegalArgumentException() {
 	public void setAccessibleScopesWhenNullThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> this.userService.setAccessibleScopes(null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setAccessibleScopes(null));
 	}
 	}
 
 
 	@Test
 	@Test

+ 3 - 5
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.oidc.user.TestOidcUsers;
 import org.springframework.security.oauth2.core.user.TestOAuth2Users;
 import org.springframework.security.oauth2.core.user.TestOAuth2Users;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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;
 import static org.mockito.Mockito.mock;
 
 
 /**
 /**
@@ -137,14 +137,12 @@ public class OidcClientInitiatedLogoutSuccessHandlerTests {
 
 
 	@Test
 	@Test
 	public void setPostLogoutRedirectUriWhenGivenNullThenThrowsException() {
 	public void setPostLogoutRedirectUriWhenGivenNullThenThrowsException() {
-		assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setPostLogoutRedirectUriTemplateWhenGivenNullThenThrowsException() {
 	public void setPostLogoutRedirectUriTemplateWhenGivenNullThenThrowsException() {
-		assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null));
 	}
 	}
 
 
 }
 }

+ 3 - 5
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.ServerWebExchange;
 import org.springframework.web.server.WebFilterChain;
 import org.springframework.web.server.WebFilterChain;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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.BDDMockito.given;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.mock;
 
 
@@ -149,14 +149,12 @@ public class OidcClientInitiatedServerLogoutSuccessHandlerTests {
 
 
 	@Test
 	@Test
 	public void setPostLogoutRedirectUriWhenGivenNullThenThrowsException() {
 	public void setPostLogoutRedirectUriWhenGivenNullThenThrowsException() {
-		assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void setPostLogoutRedirectUriTemplateWhenGivenNullThenThrowsException() {
 	public void setPostLogoutRedirectUriTemplateWhenGivenNullThenThrowsException() {
-		assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null));
 	}
 	}
 
 
 	private String redirectedUrl(ServerWebExchange exchange) {
 	private String redirectedUrl(ServerWebExchange exchange) {

+ 27 - 29
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java

@@ -30,7 +30,7 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
 import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
 import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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}.
  * Tests for {@link ClientRegistration}.
@@ -364,18 +364,17 @@ public class ClientRegistrationTests {
 
 
 	@Test
 	@Test
 	public void buildWhenClientCredentialsGrantRegistrationIdIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void buildWhenClientCredentialsGrantClientIdIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
@@ -396,23 +395,23 @@ public class ClientRegistrationTests {
 
 
 	@Test
 	@Test
 	public void buildWhenClientCredentialsGrantTokenUriIsNullThenThrowIllegalArgumentException() {
 	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
 	// gh-6256
 	@Test
 	@Test
 	public void buildWhenScopesContainASpaceThenThrowIllegalArgumentException() {
 	public void buildWhenScopesContainASpaceThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> TestClientRegistrations.clientCredentials().scope("openid profile email").build())
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> TestClientRegistrations.clientCredentials().scope("openid profile email").build());
 	}
 	}
 
 
 	@Test
 	@Test
 	public void buildWhenScopesContainAnInvalidCharacterThenThrowIllegalArgumentException() {
 	public void buildWhenScopesContainAnInvalidCharacterThenThrowIllegalArgumentException() {
-		assertThatThrownBy(() -> TestClientRegistrations.clientCredentials().scope("an\"invalid\"scope").build())
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> TestClientRegistrations.clientCredentials().scope("an\"invalid\"scope").build());
 	}
 	}
 
 
 	@Test
 	@Test
@@ -433,18 +432,17 @@ public class ClientRegistrationTests {
 
 
 	@Test
 	@Test
 	public void buildWhenPasswordGrantRegistrationIdIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
 	public void buildWhenPasswordGrantClientIdIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test
@@ -465,10 +463,10 @@ public class ClientRegistrationTests {
 
 
 	@Test
 	@Test
 	public void buildWhenPasswordGrantTokenUriIsNullThenThrowIllegalArgumentException() {
 	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
 	@Test

+ 28 - 27
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java

@@ -35,7 +35,8 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
 import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
 import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * @author Rob Winch
@@ -142,17 +143,16 @@ public class ClientRegistrationsTests {
 	@Test
 	@Test
 	public void issuerWhenResponseMissingJwksUriThenThrowsIllegalArgumentException() throws Exception {
 	public void issuerWhenResponseMissingJwksUriThenThrowsIllegalArgumentException() throws Exception {
 		this.response.remove("jwks_uri");
 		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
 	// gh-7512
 	@Test
 	@Test
 	public void issuerWhenOidcFallbackResponseMissingJwksUriThenThrowsIllegalArgumentException() throws Exception {
 	public void issuerWhenOidcFallbackResponseMissingJwksUriThenThrowsIllegalArgumentException() throws Exception {
 		this.response.remove("jwks_uri");
 		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
 	// gh-7512
@@ -239,16 +239,16 @@ public class ClientRegistrationsTests {
 	@Test
 	@Test
 	public void issuerWhenGrantTypesSupportedInvalidThenException() {
 	public void issuerWhenGrantTypesSupportedInvalidThenException() {
 		this.response.put("grant_types_supported", Arrays.asList("implicit"));
 		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]");
 						+ this.issuer + "\" returned a configuration of [implicit]");
 	}
 	}
 
 
 	@Test
 	@Test
 	public void issuerWhenOAuth2GrantTypesSupportedInvalidThenException() {
 	public void issuerWhenOAuth2GrantTypesSupportedInvalidThenException() {
 		this.response.put("grant_types_supported", Arrays.asList("implicit"));
 		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]");
 						+ this.issuer + "\" returned a configuration of [implicit]");
 	}
 	}
 
 
@@ -301,30 +301,31 @@ public class ClientRegistrationsTests {
 	@Test
 	@Test
 	public void issuerWhenTokenEndpointAuthMethodsInvalidThenException() {
 	public void issuerWhenTokenEndpointAuthMethodsInvalidThenException() {
 		this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("tls_client_auth"));
 		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
 	@Test
 	public void issuerWhenOAuth2TokenEndpointAuthMethodsInvalidThenException() {
 	public void issuerWhenOAuth2TokenEndpointAuthMethodsInvalidThenException() {
 		this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("tls_client_auth"));
 		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
 	@Test
 	public void issuerWhenOAuth2EmptyStringThenMeaningfulErrorMessage() {
 	public void issuerWhenOAuth2EmptyStringThenMeaningfulErrorMessage() {
-		assertThatThrownBy(() -> ClientRegistrations.fromIssuerLocation(""))
-				.hasMessageContaining("issuer cannot be empty");
+		assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistrations.fromIssuerLocation(""))
+				.withMessageContaining("issuer cannot be empty");
 	}
 	}
 
 
 	@Test
 	@Test
 	public void issuerWhenEmptyStringThenMeaningfulErrorMessage() {
 	public void issuerWhenEmptyStringThenMeaningfulErrorMessage() {
-		assertThatThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation(""))
-				.hasMessageContaining("issuer cannot be empty");
+		assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation(""))
+				.withMessageContaining("issuer cannot be empty");
 	}
 	}
 
 
 	@Test
 	@Test
@@ -334,9 +335,9 @@ public class ClientRegistrationsTests {
 		MockResponse mockResponse = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE,
 		MockResponse mockResponse = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE,
 				MediaType.APPLICATION_JSON_VALUE);
 				MediaType.APPLICATION_JSON_VALUE);
 		this.server.enqueue(mockResponse);
 		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
 	@Test
@@ -346,9 +347,9 @@ public class ClientRegistrationsTests {
 		MockResponse mockResponse = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE,
 		MockResponse mockResponse = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE,
 				MediaType.APPLICATION_JSON_VALUE);
 				MediaType.APPLICATION_JSON_VALUE);
 		this.server.enqueue(mockResponse);
 		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 {
 	private ClientRegistration.Builder registration(String path) throws Exception {

+ 8 - 9
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/InMemoryReactiveClientRegistrationRepositoryTests.java

@@ -24,7 +24,7 @@ import org.junit.Test;
 import reactor.test.StepVerifier;
 import reactor.test.StepVerifier;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
 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
  * @author Rob Winch
@@ -43,22 +43,21 @@ public class InMemoryReactiveClientRegistrationRepositoryTests {
 
 
 	@Test
 	@Test
 	public void constructorWhenZeroVarArgsThenIllegalArgumentException() {
 	public void constructorWhenZeroVarArgsThenIllegalArgumentException() {
-		assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository())
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException().isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository());
 	}
 	}
 
 
 	@Test
 	@Test
 	public void constructorWhenClientRegistrationArrayThenIllegalArgumentException() {
 	public void constructorWhenClientRegistrationArrayThenIllegalArgumentException() {
 		ClientRegistration[] registrations = null;
 		ClientRegistration[] registrations = null;
-		assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations));
 	}
 	}
 
 
 	@Test
 	@Test
 	public void constructorWhenClientRegistrationListThenIllegalArgumentException() {
 	public void constructorWhenClientRegistrationListThenIllegalArgumentException() {
 		List<ClientRegistration> registrations = null;
 		List<ClientRegistration> registrations = null;
-		assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations));
 	}
 	}
 
 
 	@Test(expected = IllegalStateException.class)
 	@Test(expected = IllegalStateException.class)
@@ -70,8 +69,8 @@ public class InMemoryReactiveClientRegistrationRepositoryTests {
 	@Test
 	@Test
 	public void constructorWhenClientRegistrationIsNullThenIllegalArgumentException() {
 	public void constructorWhenClientRegistrationIsNullThenIllegalArgumentException() {
 		ClientRegistration registration = null;
 		ClientRegistration registration = null;
-		assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registration))
-				.isInstanceOf(IllegalArgumentException.class);
+		assertThatIllegalArgumentException()
+				.isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registration));
 	}
 	}
 
 
 	@Test
 	@Test

部分文件因文件數量過多而無法顯示