Skip to content

Commit 4f3e599

Browse files
committed
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
1 parent d5c6645 commit 4f3e599

File tree

196 files changed

+2241
-2116
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

196 files changed

+2241
-2116
lines changed

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

+6-4
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import java.util.List;
2121

2222
import io.rsocket.RSocketFactory;
23+
import io.rsocket.exceptions.RejectedSetupException;
2324
import io.rsocket.frame.decoder.PayloadDecoder;
2425
import io.rsocket.transport.netty.server.CloseableChannel;
2526
import io.rsocket.transport.netty.server.TcpServerTransport;
@@ -46,7 +47,7 @@
4647
import org.springframework.test.context.junit4.SpringRunner;
4748

4849
import static org.assertj.core.api.Assertions.assertThat;
49-
import static org.assertj.core.api.Assertions.assertThatCode;
50+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
5051

5152
/**
5253
* @author Rob Winch
@@ -87,10 +88,11 @@ public void retrieveMonoWhenSecureThenDenied() throws Exception {
8788
this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies())
8889
.connectTcp("localhost", this.server.address().getPort()).block();
8990
String data = "rob";
90-
assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
91-
.isNotNull();
91+
assertThatExceptionOfType(Exception.class).isThrownBy(
92+
() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
93+
.matches((ex) -> ex instanceof RejectedSetupException
94+
|| ex.getClass().toString().contains("ReactiveException"));
9295
// FIXME: https://github.com/rsocket/rsocket-java/issues/686
93-
// .isInstanceOf(RejectedSetupException.class);
9496
assertThat(this.controller.payloads).isEmpty();
9597
}
9698

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

+14-11
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import io.rsocket.RSocketFactory;
2323
import io.rsocket.exceptions.ApplicationErrorException;
24+
import io.rsocket.exceptions.RejectedSetupException;
2425
import io.rsocket.frame.decoder.PayloadDecoder;
2526
import io.rsocket.transport.netty.server.CloseableChannel;
2627
import io.rsocket.transport.netty.server.TcpServerTransport;
@@ -49,7 +50,7 @@
4950
import org.springframework.test.context.junit4.SpringRunner;
5051

5152
import static org.assertj.core.api.Assertions.assertThat;
52-
import static org.assertj.core.api.Assertions.assertThatCode;
53+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
5354

5455
/**
5556
* @author Rob Winch
@@ -103,8 +104,8 @@ public void routeWhenNotAuthorized() {
103104
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
104105
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
105106
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
106-
assertThatCode(() -> this.requester.route("secure.admin.retrieve-mono").data("data").retrieveMono(String.class)
107-
.block()).isInstanceOf(ApplicationErrorException.class);
107+
assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(() -> this.requester
108+
.route("secure.admin.retrieve-mono").data("data").retrieveMono(String.class).block());
108109
}
109110

110111
@Test
@@ -137,30 +138,32 @@ public void routeWhenStreamCredentialsHaveAuthority() {
137138
public void connectWhenNotAuthenticated() {
138139
this.requester = requester().connectTcp(this.server.address().getHostName(), this.server.address().getPort())
139140
.block();
140-
assertThatCode(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block())
141-
.isNotNull();
141+
assertThatExceptionOfType(Exception.class)
142+
.isThrownBy(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block())
143+
.matches((ex) -> ex instanceof RejectedSetupException
144+
|| ex.getClass().toString().contains("ReactiveException"));
142145
// FIXME: https://github.com/rsocket/rsocket-java/issues/686
143-
// .isInstanceOf(RejectedSetupException.class);
144146
}
145147

146148
@Test
147149
public void connectWhenNotAuthorized() {
148150
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("evil", "password");
149151
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
150152
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
151-
assertThatCode(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block())
152-
.isNotNull();
153+
assertThatExceptionOfType(Exception.class)
154+
.isThrownBy(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block())
155+
.matches((ex) -> ex instanceof RejectedSetupException
156+
|| ex.getClass().toString().contains("ReactiveException"));
153157
// FIXME: https://github.com/rsocket/rsocket-java/issues/686
154-
// .isInstanceOf(RejectedSetupException.class);
155158
}
156159

157160
@Test
158161
public void connectionDenied() {
159162
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
160163
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
161164
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
162-
assertThatCode(() -> this.requester.route("prohibit").data("data").retrieveMono(String.class).block())
163-
.isInstanceOf(ApplicationErrorException.class);
165+
assertThatExceptionOfType(ApplicationErrorException.class)
166+
.isThrownBy(() -> this.requester.route("prohibit").data("data").retrieveMono(String.class).block());
164167
}
165168

166169
@Test

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

+15-12
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
import org.springframework.test.context.junit4.SpringRunner;
5353

5454
import static org.assertj.core.api.Assertions.assertThat;
55-
import static org.assertj.core.api.Assertions.assertThatCode;
55+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
5656

5757
/**
5858
* @author Rob Winch
@@ -96,19 +96,21 @@ public void dispose() {
9696
@Test
9797
public void retrieveMonoWhenSecureThenDenied() throws Exception {
9898
String data = "rob";
99-
assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
100-
.isInstanceOf(ApplicationErrorException.class).hasMessageContaining("Access Denied");
99+
assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(
100+
() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
101+
.withMessageContaining("Access Denied");
101102
assertThat(this.controller.payloads).isEmpty();
102103
}
103104

104105
@Test
105106
public void retrieveMonoWhenAuthenticationFailedThenException() throws Exception {
106107
String data = "rob";
107108
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("invalid", "password");
108-
assertThatCode(() -> this.requester.route("secure.retrieve-mono")
109-
.metadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE).data(data)
110-
.retrieveMono(String.class).block()).isInstanceOf(ApplicationErrorException.class)
111-
.hasMessageContaining("Invalid Credentials");
109+
assertThatExceptionOfType(ApplicationErrorException.class)
110+
.isThrownBy(() -> this.requester.route("secure.retrieve-mono")
111+
.metadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE).data(data)
112+
.retrieveMono(String.class).block())
113+
.withMessageContaining("Invalid Credentials");
112114
assertThat(this.controller.payloads).isEmpty();
113115
}
114116

@@ -134,9 +136,10 @@ public void retrieveMonoWhenPublicThenGranted() throws Exception {
134136
@Test
135137
public void retrieveFluxWhenDataFluxAndSecureThenDenied() throws Exception {
136138
Flux<String> data = Flux.just("a", "b", "c");
137-
assertThatCode(() -> this.requester.route("secure.retrieve-flux").data(data, String.class)
138-
.retrieveFlux(String.class).collectList().block()).isInstanceOf(ApplicationErrorException.class)
139-
.hasMessageContaining("Access Denied");
139+
assertThatExceptionOfType(ApplicationErrorException.class)
140+
.isThrownBy(() -> this.requester.route("secure.retrieve-flux").data(data, String.class)
141+
.retrieveFlux(String.class).collectList().block())
142+
.withMessageContaining("Access Denied");
140143
assertThat(this.controller.payloads).isEmpty();
141144
}
142145

@@ -152,9 +155,9 @@ public void retrieveFluxWhenDataFluxAndPublicThenGranted() throws Exception {
152155
@Test
153156
public void retrieveFluxWhenDataStringAndSecureThenDenied() throws Exception {
154157
String data = "a";
155-
assertThatCode(
158+
assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(
156159
() -> this.requester.route("secure.hello").data(data).retrieveFlux(String.class).collectList().block())
157-
.isInstanceOf(ApplicationErrorException.class).hasMessageContaining("Access Denied");
160+
.withMessageContaining("Access Denied");
158161
assertThat(this.controller.payloads).isEmpty();
159162
}
160163

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

+3-3
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
import org.springframework.util.MimeTypeUtils;
5353

5454
import static org.assertj.core.api.Assertions.assertThat;
55-
import static org.assertj.core.api.Assertions.assertThatCode;
55+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
5656

5757
/**
5858
* @author Rob Winch
@@ -93,8 +93,8 @@ public void retrieveMonoWhenSecureThenDenied() throws Exception {
9393
this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies())
9494
.connectTcp("localhost", this.server.address().getPort()).block();
9595
String data = "rob";
96-
assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
97-
.isInstanceOf(ApplicationErrorException.class);
96+
assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(
97+
() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block());
9898
assertThat(this.controller.payloads).isEmpty();
9999
}
100100

config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java

+8-9
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@
6363
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
6464

6565
import static org.assertj.core.api.Assertions.assertThat;
66-
import static org.assertj.core.api.Assertions.assertThatThrownBy;
66+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
6767
import static org.mockito.ArgumentMatchers.any;
6868
import static org.mockito.ArgumentMatchers.eq;
6969
import static org.mockito.ArgumentMatchers.startsWith;
@@ -165,9 +165,8 @@ public void getAuthenticationWhenConfiguredThenBootNotTrigger() throws Exception
165165
new BootGlobalAuthenticationConfigurerAdapter()));
166166
AuthenticationManager authenticationManager = config.getAuthenticationManager();
167167
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
168-
assertThatThrownBy(
169-
() -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password")))
170-
.isInstanceOf(AuthenticationException.class);
168+
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
169+
() -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password")));
171170
}
172171

173172
@Test
@@ -207,8 +206,8 @@ public void getAuthenticationWhenUserDetailsServiceBeanThenAuthenticationManager
207206
.getAuthenticationManager();
208207
given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
209208
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
210-
assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
211-
.isInstanceOf(AuthenticationException.class);
209+
assertThatExceptionOfType(AuthenticationException.class)
210+
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")));
212211
}
213212

214213
@Test
@@ -222,8 +221,8 @@ public void getAuthenticationWhenUserDetailsServiceAndPasswordEncoderBeanThenEnc
222221
given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
223222
User.withUserDetails(user).build());
224223
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
225-
assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
226-
.isInstanceOf(AuthenticationException.class);
224+
assertThatExceptionOfType(AuthenticationException.class)
225+
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")));
227226
}
228227

229228
@Test
@@ -291,7 +290,7 @@ public void getAuthenticationManagerWhenAuthenticationConfigurationSubclassedThe
291290
this.spring.register(AuthenticationConfigurationSubclass.class).autowire();
292291
AuthenticationManagerBuilder ap = this.spring.getContext().getBean(AuthenticationManagerBuilder.class);
293292
this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
294-
assertThatThrownBy(ap::build).isInstanceOf(AlreadyBuiltException.class);
293+
assertThatExceptionOfType(AlreadyBuiltException.class).isThrownBy(ap::build);
295294
}
296295

297296
@EnableGlobalMethodSecurity(securedEnabled = true)

config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java

+6-4
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
import org.springframework.test.context.junit4.SpringRunner;
3636

3737
import static org.assertj.core.api.Assertions.assertThat;
38-
import static org.assertj.core.api.Assertions.assertThatThrownBy;
38+
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
3939
import static org.mockito.BDDMockito.given;
4040
import static org.mockito.Mockito.mock;
4141
import static org.mockito.Mockito.reset;
@@ -73,9 +73,11 @@ public void setConfig(Config config) {
7373

7474
@Test
7575
public void notPublisherPreAuthorizeFindByIdThenThrowsIllegalStateException() {
76-
assertThatThrownBy(() -> this.messageService.notPublisherPreAuthorizeFindById(1L))
77-
.isInstanceOf(IllegalStateException.class).extracting(Throwable::getMessage).isEqualTo(
78-
"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");
76+
assertThatIllegalStateException().isThrownBy(() -> this.messageService.notPublisherPreAuthorizeFindById(1L))
77+
.withMessage("The returnType class java.lang.String on public abstract java.lang.String "
78+
+ "org.springframework.security.config.annotation.method.configuration.ReactiveMessageService"
79+
+ ".notPublisherPreAuthorizeFindById(long) must return an instance of org.reactivestreams"
80+
+ ".Publisher (i.e. Mono / Flux) in order to support Reactor Context");
7981
}
8082

8183
@Test

config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java

+13-11
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
6262

6363
import static org.assertj.core.api.Assertions.assertThat;
64-
import static org.assertj.core.api.Assertions.assertThatThrownBy;
64+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
6565
import static org.mockito.ArgumentMatchers.any;
6666
import static org.mockito.ArgumentMatchers.eq;
6767
import static org.mockito.BDDMockito.given;
@@ -125,7 +125,8 @@ public void methodSecurityWhenAuthenticationTrustResolverIsBeanThenAutowires() {
125125
this.spring.register(CustomTrustResolverConfig.class).autowire();
126126
AuthenticationTrustResolver trustResolver = this.spring.getContext().getBean(AuthenticationTrustResolver.class);
127127
given(trustResolver.isAnonymous(any())).willReturn(true, false);
128-
assertThatThrownBy(() -> this.service.preAuthorizeNotAnonymous()).isInstanceOf(AccessDeniedException.class);
128+
assertThatExceptionOfType(AccessDeniedException.class)
129+
.isThrownBy(() -> this.service.preAuthorizeNotAnonymous());
129130
this.service.preAuthorizeNotAnonymous();
130131
verify(trustResolver, atLeastOnce()).isAnonymous(any());
131132
}
@@ -136,15 +137,15 @@ public void methodSecurityWhenAuthenticationTrustResolverIsBeanThenAutowires() {
136137
public void defaultWebSecurityExpressionHandlerHasBeanResolverSet() {
137138
this.spring.register(ExpressionHandlerHasBeanResolverSetConfig.class).autowire();
138139
Authz authz = this.spring.getContext().getBean(Authz.class);
139-
assertThatThrownBy(() -> this.service.preAuthorizeBean(false)).isInstanceOf(AccessDeniedException.class);
140+
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorizeBean(false));
140141
this.service.preAuthorizeBean(true);
141142
}
142143

143144
@Test
144145
@WithMockUser
145146
public void methodSecuritySupportsAnnotaitonsOnInterfaceParamerNames() {
146147
this.spring.register(MethodSecurityServiceConfig.class).autowire();
147-
assertThatThrownBy(() -> this.service.postAnnotation("deny")).isInstanceOf(AccessDeniedException.class);
148+
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.postAnnotation("deny"));
148149
this.service.postAnnotation("grant");
149150
// no exception
150151
}
@@ -157,7 +158,8 @@ public void globalMethodSecurityConfigurationAutowiresPermissionEvaluator() {
157158
given(permission.hasPermission(any(), eq("something"), eq("read"))).willReturn(true, false);
158159
this.service.hasPermission("something");
159160
// no exception
160-
assertThatThrownBy(() -> this.service.hasPermission("something")).isInstanceOf(AccessDeniedException.class);
161+
assertThatExceptionOfType(AccessDeniedException.class)
162+
.isThrownBy(() -> this.service.hasPermission("something"));
161163
}
162164

163165
@Test
@@ -171,7 +173,7 @@ public void multiPermissionEvaluatorConfig() {
171173
@WithMockUser
172174
public void enableGlobalMethodSecurityWorksOnSuperclass() {
173175
this.spring.register(ChildConfig.class).autowire();
174-
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
176+
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
175177
}
176178

177179
// SEC-2479
@@ -186,7 +188,7 @@ public void supportAuthenticationManagerInParent() {
186188
child.register(Sec2479ChildConfig.class);
187189
child.refresh();
188190
this.spring.context(child).autowire();
189-
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
191+
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
190192
}
191193
}
192194
}
@@ -228,7 +230,7 @@ public void globalSecurityProxiesSecurity() {
228230
@WithMockUser
229231
public void preAuthorizeBeanSpel() {
230232
this.spring.register(PreAuthorizeBeanSpelConfig.class).autowire();
231-
assertThatThrownBy(() -> this.service.preAuthorizeBean(false)).isInstanceOf(AccessDeniedException.class);
233+
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorizeBean(false));
232234
this.service.preAuthorizeBean(true);
233235
}
234236

@@ -237,7 +239,7 @@ public void preAuthorizeBeanSpel() {
237239
@WithMockUser
238240
public void roleHierarchy() {
239241
this.spring.register(RoleHierarchyConfig.class).autowire();
240-
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
242+
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
241243
this.service.preAuthorizeAdmin();
242244
}
243245

@@ -247,7 +249,7 @@ public void grantedAuthorityDefaultsAutowires() {
247249
this.spring.register(CustomGrantedAuthorityConfig.class).autowire();
248250
CustomGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
249251
.getBean(CustomGrantedAuthorityConfig.CustomAuthorityService.class);
250-
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
252+
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
251253
customService.customPrefixRoleUser();
252254
// no exception
253255
}
@@ -258,7 +260,7 @@ public void grantedAuthorityDefaultsWithEmptyRolePrefix() {
258260
this.spring.register(EmptyRolePrefixGrantedAuthorityConfig.class).autowire();
259261
EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
260262
.getBean(EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService.class);
261-
assertThatThrownBy(() -> this.service.securedUser()).isInstanceOf(AccessDeniedException.class);
263+
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.securedUser());
262264
customService.emptyPrefixRoleUser();
263265
// no exception
264266
}

0 commit comments

Comments
 (0)