Migrate to BDD Mockito

Migrate Mockito imports to use the BDD variant. This aligns better with
the "given" / "when" / "then" style used in most tests since the "given"
block now uses Mockito `given(...)` calls.

The commit also updates a few tests that were accidentally using
Power Mockito when regular Mockito could be used.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-07-27 12:53:19 -07:00
committed by Rob Winch
parent c12ced6aaa
commit db55ef4b3b
259 changed files with 2126 additions and 2125 deletions

View File

@@ -53,10 +53,10 @@ import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
@@ -88,7 +88,7 @@ public class AuthenticationManagerBuilderTests {
public void customAuthenticationEventPublisherWithWeb() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationEventPublisher aep = mock(AuthenticationEventPublisher.class);
when(opp.postProcess(any())).thenAnswer(a -> a.getArgument(0));
given(opp.postProcess(any())).willAnswer(a -> a.getArgument(0));
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
.inMemoryAuthentication().and().build();

View File

@@ -66,9 +66,9 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AuthenticationConfigurationTests {
@@ -150,7 +150,7 @@ public class AuthenticationConfigurationTests {
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
when(authentication.authenticate(token)).thenReturn(TestAuthentication.authenticatedUser());
given(authentication.authenticate(token)).willReturn(TestAuthentication.authenticatedUser());
assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName());
}
@@ -196,7 +196,7 @@ public class AuthenticationConfigurationTests {
public void getAuthenticationManagerWhenPostProcessThenUsesBeanClassLoaderOnProxyFactoryBean() throws Exception {
this.spring.register(Sec2531Config.class).autowire();
ObjectPostProcessor<Object> opp = this.spring.getContext().getBean(ObjectPostProcessor.class);
when(opp.postProcess(any())).thenAnswer(a -> a.getArgument(0));
given(opp.postProcess(any())).willAnswer(a -> a.getArgument(0));
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
config.getAuthenticationManager();
@@ -220,7 +220,7 @@ public class AuthenticationConfigurationTests {
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
when(uds.loadUserByUsername("user")).thenReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
@@ -236,7 +236,7 @@ public class AuthenticationConfigurationTests {
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
when(uds.loadUserByUsername("user")).thenReturn(User.withUserDetails(user).build(),
given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
@@ -253,9 +253,9 @@ public class AuthenticationConfigurationTests {
.getBean(UserDetailsPasswordManagerBeanConfig.Manager.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
when(manager.loadUserByUsername("user")).thenReturn(User.withUserDetails(user).build(),
given(manager.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build());
when(manager.updatePassword(any(), any())).thenReturn(user);
given(manager.updatePassword(any(), any())).willReturn(user);
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
@@ -269,8 +269,8 @@ public class AuthenticationConfigurationTests {
AuthenticationProvider ap = this.spring.getContext().getBean(AuthenticationProvider.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
when(ap.supports(any())).thenReturn(true);
when(ap.authenticate(any())).thenReturn(TestAuthentication.authenticatedUser());
given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
@@ -282,8 +282,8 @@ public class AuthenticationConfigurationTests {
AuthenticationProvider ap = this.spring.getContext().getBean(AuthenticationProvider.class);
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
when(ap.supports(any())).thenReturn(true);
when(ap.authenticate(any())).thenReturn(TestAuthentication.authenticatedUser());
given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}

View File

@@ -36,9 +36,9 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -80,7 +80,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoWhenPermitAllThenAopDoesNotSubscribe() {
when(this.delegate.monoFindById(1L)).thenReturn(Mono.from(this.result));
given(this.delegate.monoFindById(1L)).willReturn(Mono.from(this.result));
this.delegate.monoFindById(1L);
@@ -89,14 +89,14 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoWhenPermitAllThenSuccess() {
when(this.delegate.monoFindById(1L)).thenReturn(Mono.just("success"));
given(this.delegate.monoFindById(1L)).willReturn(Mono.just("success"));
StepVerifier.create(this.delegate.monoFindById(1L)).expectNext("success").verifyComplete();
}
@Test
public void monoPreAuthorizeHasRoleWhenGrantedThenSuccess() {
when(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).thenReturn(Mono.just("result"));
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withAdmin);
@@ -105,7 +105,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
when(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).thenReturn(Mono.from(this.result));
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -115,7 +115,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
when(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).thenReturn(Mono.from(this.result));
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withUser);
@@ -126,7 +126,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeBeanWhenGrantedThenSuccess() {
when(this.delegate.monoPreAuthorizeBeanFindById(2L)).thenReturn(Mono.just("result"));
given(this.delegate.monoPreAuthorizeBeanFindById(2L)).willReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(2L).subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
@@ -134,7 +134,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeBeanWhenNotAuthenticatedAndGrantedThenSuccess() {
when(this.delegate.monoPreAuthorizeBeanFindById(2L)).thenReturn(Mono.just("result"));
given(this.delegate.monoPreAuthorizeBeanFindById(2L)).willReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("result").verifyComplete();
@@ -142,7 +142,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
when(this.delegate.monoPreAuthorizeBeanFindById(1L)).thenReturn(Mono.from(this.result));
given(this.delegate.monoPreAuthorizeBeanFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -152,7 +152,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
when(this.delegate.monoPreAuthorizeBeanFindById(1L)).thenReturn(Mono.from(this.result));
given(this.delegate.monoPreAuthorizeBeanFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -162,7 +162,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenAuthorizedThenSuccess() {
when(this.delegate.monoPostAuthorizeFindById(1L)).thenReturn(Mono.just("user"));
given(this.delegate.monoPostAuthorizeFindById(1L)).willReturn(Mono.just("user"));
Mono<String> findById = this.messageService.monoPostAuthorizeFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
@@ -170,7 +170,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenNotAuthorizedThenDenied() {
when(this.delegate.monoPostAuthorizeBeanFindById(1L)).thenReturn(Mono.just("not-authorized"));
given(this.delegate.monoPostAuthorizeBeanFindById(1L)).willReturn(Mono.just("not-authorized"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -178,7 +178,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
when(this.delegate.monoPostAuthorizeBeanFindById(2L)).thenReturn(Mono.just("user"));
given(this.delegate.monoPostAuthorizeBeanFindById(2L)).willReturn(Mono.just("user"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(2L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
@@ -186,7 +186,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenBeanAndNotAuthenticatedAndAuthorizedThenSuccess() {
when(this.delegate.monoPostAuthorizeBeanFindById(2L)).thenReturn(Mono.just("anonymous"));
given(this.delegate.monoPostAuthorizeBeanFindById(2L)).willReturn(Mono.just("anonymous"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("anonymous").verifyComplete();
@@ -194,7 +194,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
when(this.delegate.monoPostAuthorizeBeanFindById(1L)).thenReturn(Mono.just("not-authorized"));
given(this.delegate.monoPostAuthorizeBeanFindById(1L)).willReturn(Mono.just("not-authorized"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -204,7 +204,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxWhenPermitAllThenAopDoesNotSubscribe() {
when(this.delegate.fluxFindById(1L)).thenReturn(Flux.from(this.result));
given(this.delegate.fluxFindById(1L)).willReturn(Flux.from(this.result));
this.delegate.fluxFindById(1L);
@@ -213,14 +213,14 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxWhenPermitAllThenSuccess() {
when(this.delegate.fluxFindById(1L)).thenReturn(Flux.just("success"));
given(this.delegate.fluxFindById(1L)).willReturn(Flux.just("success"));
StepVerifier.create(this.delegate.fluxFindById(1L)).expectNext("success").verifyComplete();
}
@Test
public void fluxPreAuthorizeHasRoleWhenGrantedThenSuccess() {
when(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).thenReturn(Flux.just("result"));
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withAdmin);
@@ -230,7 +230,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
when(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).thenReturn(Flux.from(this.result));
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -240,7 +240,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
when(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).thenReturn(Flux.from(this.result));
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withUser);
@@ -251,7 +251,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeBeanWhenGrantedThenSuccess() {
when(this.delegate.fluxPreAuthorizeBeanFindById(2L)).thenReturn(Flux.just("result"));
given(this.delegate.fluxPreAuthorizeBeanFindById(2L)).willReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(2L).subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
@@ -259,7 +259,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeBeanWhenNotAuthenticatedAndGrantedThenSuccess() {
when(this.delegate.fluxPreAuthorizeBeanFindById(2L)).thenReturn(Flux.just("result"));
given(this.delegate.fluxPreAuthorizeBeanFindById(2L)).willReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("result").verifyComplete();
@@ -267,7 +267,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
when(this.delegate.fluxPreAuthorizeBeanFindById(1L)).thenReturn(Flux.from(this.result));
given(this.delegate.fluxPreAuthorizeBeanFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -277,7 +277,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
when(this.delegate.fluxPreAuthorizeBeanFindById(1L)).thenReturn(Flux.from(this.result));
given(this.delegate.fluxPreAuthorizeBeanFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -287,7 +287,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenAuthorizedThenSuccess() {
when(this.delegate.fluxPostAuthorizeFindById(1L)).thenReturn(Flux.just("user"));
given(this.delegate.fluxPostAuthorizeFindById(1L)).willReturn(Flux.just("user"));
Flux<String> findById = this.messageService.fluxPostAuthorizeFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
@@ -295,7 +295,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenNotAuthorizedThenDenied() {
when(this.delegate.fluxPostAuthorizeBeanFindById(1L)).thenReturn(Flux.just("not-authorized"));
given(this.delegate.fluxPostAuthorizeBeanFindById(1L)).willReturn(Flux.just("not-authorized"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -303,7 +303,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
when(this.delegate.fluxPostAuthorizeBeanFindById(2L)).thenReturn(Flux.just("user"));
given(this.delegate.fluxPostAuthorizeBeanFindById(2L)).willReturn(Flux.just("user"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(2L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
@@ -311,7 +311,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenBeanAndNotAuthenticatedAndAuthorizedThenSuccess() {
when(this.delegate.fluxPostAuthorizeBeanFindById(2L)).thenReturn(Flux.just("anonymous"));
given(this.delegate.fluxPostAuthorizeBeanFindById(2L)).willReturn(Flux.just("anonymous"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("anonymous").verifyComplete();
@@ -319,7 +319,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
when(this.delegate.fluxPostAuthorizeBeanFindById(1L)).thenReturn(Flux.just("not-authorized"));
given(this.delegate.fluxPostAuthorizeBeanFindById(1L)).willReturn(Flux.just("not-authorized"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -329,7 +329,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherWhenPermitAllThenAopDoesNotSubscribe() {
when(this.delegate.publisherFindById(1L)).thenReturn(this.result);
given(this.delegate.publisherFindById(1L)).willReturn(this.result);
this.delegate.publisherFindById(1L);
@@ -338,14 +338,14 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherWhenPermitAllThenSuccess() {
when(this.delegate.publisherFindById(1L)).thenReturn(publisherJust("success"));
given(this.delegate.publisherFindById(1L)).willReturn(publisherJust("success"));
StepVerifier.create(this.delegate.publisherFindById(1L)).expectNext("success").verifyComplete();
}
@Test
public void publisherPreAuthorizeHasRoleWhenGrantedThenSuccess() {
when(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).thenReturn(publisherJust("result"));
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(publisherJust("result"));
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
.subscriberContext(this.withAdmin);
@@ -355,7 +355,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
when(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).thenReturn(this.result);
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(this.result);
Publisher<String> findById = this.messageService.publisherPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -365,7 +365,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
when(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).thenReturn(this.result);
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(this.result);
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
.subscriberContext(this.withUser);
@@ -376,7 +376,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeBeanWhenGrantedThenSuccess() {
when(this.delegate.publisherPreAuthorizeBeanFindById(2L)).thenReturn(publisherJust("result"));
given(this.delegate.publisherPreAuthorizeBeanFindById(2L)).willReturn(publisherJust("result"));
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(2L))
.subscriberContext(this.withAdmin);
@@ -385,7 +385,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeBeanWhenNotAuthenticatedAndGrantedThenSuccess() {
when(this.delegate.publisherPreAuthorizeBeanFindById(2L)).thenReturn(publisherJust("result"));
given(this.delegate.publisherPreAuthorizeBeanFindById(2L)).willReturn(publisherJust("result"));
Publisher<String> findById = this.messageService.publisherPreAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("result").verifyComplete();
@@ -393,7 +393,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
when(this.delegate.publisherPreAuthorizeBeanFindById(1L)).thenReturn(this.result);
given(this.delegate.publisherPreAuthorizeBeanFindById(1L)).willReturn(this.result);
Publisher<String> findById = this.messageService.publisherPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -403,7 +403,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
when(this.delegate.publisherPreAuthorizeBeanFindById(1L)).thenReturn(this.result);
given(this.delegate.publisherPreAuthorizeBeanFindById(1L)).willReturn(this.result);
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(1L))
.subscriberContext(this.withUser);
@@ -414,7 +414,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenAuthorizedThenSuccess() {
when(this.delegate.publisherPostAuthorizeFindById(1L)).thenReturn(publisherJust("user"));
given(this.delegate.publisherPostAuthorizeFindById(1L)).willReturn(publisherJust("user"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeFindById(1L))
.subscriberContext(this.withUser);
@@ -423,7 +423,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenNotAuthorizedThenDenied() {
when(this.delegate.publisherPostAuthorizeBeanFindById(1L)).thenReturn(publisherJust("not-authorized"));
given(this.delegate.publisherPostAuthorizeBeanFindById(1L)).willReturn(publisherJust("not-authorized"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
.subscriberContext(this.withUser);
@@ -432,7 +432,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
when(this.delegate.publisherPostAuthorizeBeanFindById(2L)).thenReturn(publisherJust("user"));
given(this.delegate.publisherPostAuthorizeBeanFindById(2L)).willReturn(publisherJust("user"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(2L))
.subscriberContext(this.withUser);
@@ -441,7 +441,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenBeanAndNotAuthenticatedAndAuthorizedThenSuccess() {
when(this.delegate.publisherPostAuthorizeBeanFindById(2L)).thenReturn(publisherJust("anonymous"));
given(this.delegate.publisherPostAuthorizeBeanFindById(2L)).willReturn(publisherJust("anonymous"));
Publisher<String> findById = this.messageService.publisherPostAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("anonymous").verifyComplete();
@@ -449,7 +449,7 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
when(this.delegate.publisherPostAuthorizeBeanFindById(1L)).thenReturn(publisherJust("not-authorized"));
given(this.delegate.publisherPostAuthorizeBeanFindById(1L)).willReturn(publisherJust("not-authorized"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
.subscriberContext(this.withUser);

View File

@@ -63,10 +63,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -126,7 +126,7 @@ public class GlobalMethodSecurityConfigurationTests {
this.spring.register(CustomTrustResolverConfig.class).autowire();
AuthenticationTrustResolver trustResolver = this.spring.getContext().getBean(AuthenticationTrustResolver.class);
when(trustResolver.isAnonymous(any())).thenReturn(true, false);
given(trustResolver.isAnonymous(any())).willReturn(true, false);
assertThatThrownBy(() -> this.service.preAuthorizeNotAnonymous()).isInstanceOf(AccessDeniedException.class);
@@ -163,7 +163,7 @@ public class GlobalMethodSecurityConfigurationTests {
public void globalMethodSecurityConfigurationAutowiresPermissionEvaluator() {
this.spring.register(AutowirePermissionEvaluatorConfig.class).autowire();
PermissionEvaluator permission = this.spring.getContext().getBean(PermissionEvaluator.class);
when(permission.hasPermission(any(), eq("something"), eq("read"))).thenReturn(true, false);
given(permission.hasPermission(any(), eq("something"), eq("read"))).willReturn(true, false);
this.service.hasPermission("something");
// no exception

View File

@@ -58,10 +58,10 @@ import org.springframework.web.bind.annotation.GetMapping;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
@@ -89,9 +89,9 @@ public class NamespaceHttpTests {
@Test // http@access-decision-manager-ref
public void configureWhenAccessDecisionManagerSetThenVerifyUse() throws Exception {
AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER = mock(AccessDecisionManager.class);
when(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER.supports(FilterInvocation.class)).thenReturn(true);
when(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER.supports(any(ConfigAttribute.class)))
.thenReturn(true);
given(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER.supports(FilterInvocation.class)).willReturn(true);
given(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER.supports(any(ConfigAttribute.class)))
.willReturn(true);
this.spring.register(AccessDecisionManagerRefConfig.class).autowire();
@@ -178,11 +178,11 @@ public class NamespaceHttpTests {
@Test // http@jaas-api-provision
public void configureWhenJaasApiIntegrationFilterAddedThenJaasSubjectObtained() throws Exception {
LoginContext loginContext = mock(LoginContext.class);
when(loginContext.getSubject()).thenReturn(new Subject());
given(loginContext.getSubject()).willReturn(new Subject());
JaasAuthenticationToken authenticationToken = mock(JaasAuthenticationToken.class);
when(authenticationToken.isAuthenticated()).thenReturn(true);
when(authenticationToken.getLoginContext()).thenReturn(loginContext);
given(authenticationToken.isAuthenticated()).willReturn(true);
given(authenticationToken.getLoginContext()).willReturn(loginContext);
this.spring.register(JaasApiProvisionConfig.class).autowire();

View File

@@ -46,12 +46,12 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientCredentials;
import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
@@ -80,17 +80,17 @@ public class OAuth2ClientConfigurationTests {
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
ClientRegistration clientRegistration = clientRegistration().registrationId(clientRegistrationId).build();
when(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId)))
.thenReturn(clientRegistration);
given(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId)))
.willReturn(clientRegistration);
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
when(authorizedClient.getClientRegistration()).thenReturn(clientRegistration);
when(authorizedClientRepository.loadAuthorizedClient(eq(clientRegistrationId), eq(authentication),
any(HttpServletRequest.class))).thenReturn(authorizedClient);
given(authorizedClient.getClientRegistration()).willReturn(clientRegistration);
given(authorizedClientRepository.loadAuthorizedClient(eq(clientRegistrationId), eq(authentication),
any(HttpServletRequest.class))).willReturn(authorizedClient);
OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
when(authorizedClient.getAccessToken()).thenReturn(accessToken);
given(authorizedClient.getAccessToken()).willReturn(accessToken);
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
@@ -116,12 +116,12 @@ public class OAuth2ClientConfigurationTests {
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
ClientRegistration clientRegistration = clientCredentials().registrationId(clientRegistrationId).build();
when(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).thenReturn(clientRegistration);
given(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(clientRegistration);
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(300).build();
when(accessTokenResponseClient.getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class)))
.thenReturn(accessTokenResponse);
given(accessTokenResponseClient.getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class)))
.willReturn(accessTokenResponse);
OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
@@ -180,7 +180,7 @@ public class OAuth2ClientConfigurationTests {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName,
TestOAuth2AccessTokens.noScopes());
when(authorizedClientManager.authorize(any())).thenReturn(authorizedClient);
given(authorizedClientManager.authorize(any())).willReturn(authorizedClient);
OAuth2AuthorizedClientManagerRegisteredConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;

View File

@@ -61,8 +61,8 @@ import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
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.result.MockMvcResultMatchers.status;
@@ -162,8 +162,8 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenSecurityExpressionHandlerSetThenIsRegistered() {
WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER = mock(SecurityExpressionHandler.class);
when(WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER.getExpressionParser())
.thenReturn(mock(ExpressionParser.class));
given(WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER.getExpressionParser())
.willReturn(mock(ExpressionParser.class));
this.spring.register(WebSecurityExpressionHandlerConfig.class).autowire();

View File

@@ -55,10 +55,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
@@ -209,8 +209,8 @@ public class CsrfConfigurerTests {
public void loginWhenCsrfEnabledThenDoesNotRedirectToPreviousPostRequest() throws Exception {
CsrfDisablesPostRequestFromRequestCacheConfig.REPO = mock(CsrfTokenRepository.class);
DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
when(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadToken(any())).thenReturn(csrfToken);
when(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.generateToken(any())).thenReturn(csrfToken);
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadToken(any())).willReturn(csrfToken);
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.generateToken(any())).willReturn(csrfToken);
this.spring.register(CsrfDisablesPostRequestFromRequestCacheConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(post("/some-url")).andReturn();
@@ -226,8 +226,8 @@ public class CsrfConfigurerTests {
public void loginWhenCsrfEnabledThenRedirectsToPreviousGetRequest() throws Exception {
CsrfDisablesPostRequestFromRequestCacheConfig.REPO = mock(CsrfTokenRepository.class);
DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
when(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadToken(any())).thenReturn(csrfToken);
when(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.generateToken(any())).thenReturn(csrfToken);
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadToken(any())).willReturn(csrfToken);
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.generateToken(any())).willReturn(csrfToken);
this.spring.register(CsrfDisablesPostRequestFromRequestCacheConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/some-url")).andReturn();
@@ -254,7 +254,7 @@ public class CsrfConfigurerTests {
@Test
public void requireCsrfProtectionMatcherWhenRequestDoesNotMatchThenRespondsWithOk() throws Exception {
this.spring.register(RequireCsrfProtectionMatcherConfig.class, BasicController.class).autowire();
when(RequireCsrfProtectionMatcherConfig.MATCHER.matches(any())).thenReturn(false);
given(RequireCsrfProtectionMatcherConfig.MATCHER.matches(any())).willReturn(false);
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@@ -262,7 +262,7 @@ public class CsrfConfigurerTests {
@Test
public void requireCsrfProtectionMatcherWhenRequestMatchesThenRespondsWithForbidden() throws Exception {
RequireCsrfProtectionMatcherConfig.MATCHER = mock(RequestMatcher.class);
when(RequireCsrfProtectionMatcherConfig.MATCHER.matches(any())).thenReturn(true);
given(RequireCsrfProtectionMatcherConfig.MATCHER.matches(any())).willReturn(true);
this.spring.register(RequireCsrfProtectionMatcherConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isForbidden());
@@ -272,7 +272,7 @@ public class CsrfConfigurerTests {
public void requireCsrfProtectionMatcherInLambdaWhenRequestDoesNotMatchThenRespondsWithOk() throws Exception {
RequireCsrfProtectionMatcherInLambdaConfig.MATCHER = mock(RequestMatcher.class);
this.spring.register(RequireCsrfProtectionMatcherInLambdaConfig.class, BasicController.class).autowire();
when(RequireCsrfProtectionMatcherInLambdaConfig.MATCHER.matches(any())).thenReturn(false);
given(RequireCsrfProtectionMatcherInLambdaConfig.MATCHER.matches(any())).willReturn(false);
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@@ -280,7 +280,7 @@ public class CsrfConfigurerTests {
@Test
public void requireCsrfProtectionMatcherInLambdaWhenRequestMatchesThenRespondsWithForbidden() throws Exception {
RequireCsrfProtectionMatcherInLambdaConfig.MATCHER = mock(RequestMatcher.class);
when(RequireCsrfProtectionMatcherInLambdaConfig.MATCHER.matches(any())).thenReturn(true);
given(RequireCsrfProtectionMatcherInLambdaConfig.MATCHER.matches(any())).willReturn(true);
this.spring.register(RequireCsrfProtectionMatcherInLambdaConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isForbidden());
@@ -289,8 +289,8 @@ public class CsrfConfigurerTests {
@Test
public void getWhenCustomCsrfTokenRepositoryThenRepositoryIsUsed() throws Exception {
CsrfTokenRepositoryConfig.REPO = mock(CsrfTokenRepository.class);
when(CsrfTokenRepositoryConfig.REPO.loadToken(any()))
.thenReturn(new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token"));
given(CsrfTokenRepositoryConfig.REPO.loadToken(any()))
.willReturn(new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token"));
this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
@@ -312,8 +312,8 @@ public class CsrfConfigurerTests {
public void loginWhenCustomCsrfTokenRepositoryThenCsrfTokenIsCleared() throws Exception {
CsrfTokenRepositoryConfig.REPO = mock(CsrfTokenRepository.class);
DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
when(CsrfTokenRepositoryConfig.REPO.loadToken(any())).thenReturn(csrfToken);
when(CsrfTokenRepositoryConfig.REPO.generateToken(any())).thenReturn(csrfToken);
given(CsrfTokenRepositoryConfig.REPO.loadToken(any())).willReturn(csrfToken);
given(CsrfTokenRepositoryConfig.REPO.generateToken(any())).willReturn(csrfToken);
this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
@@ -326,8 +326,8 @@ public class CsrfConfigurerTests {
@Test
public void getWhenCustomCsrfTokenRepositoryInLambdaThenRepositoryIsUsed() throws Exception {
CsrfTokenRepositoryInLambdaConfig.REPO = mock(CsrfTokenRepository.class);
when(CsrfTokenRepositoryInLambdaConfig.REPO.loadToken(any()))
.thenReturn(new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token"));
given(CsrfTokenRepositoryInLambdaConfig.REPO.loadToken(any()))
.willReturn(new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token"));
this.spring.register(CsrfTokenRepositoryInLambdaConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());

View File

@@ -39,10 +39,10 @@ import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.logout;
@@ -260,7 +260,7 @@ public class FormLoginConfigurerTests {
@Test
public void requestWhenCustomPortMapperThenPortMapperUsed() throws Exception {
FormLoginUsesPortMapperConfig.PORT_MAPPER = mock(PortMapper.class);
when(FormLoginUsesPortMapperConfig.PORT_MAPPER.lookupHttpsPort(any())).thenReturn(9443);
given(FormLoginUsesPortMapperConfig.PORT_MAPPER.lookupHttpsPort(any())).willReturn(9443);
this.spring.register(FormLoginUsesPortMapperConfig.class).autowire();
this.mockMvc.perform(get("http://localhost:9090")).andExpect(status().isFound())

View File

@@ -36,10 +36,10 @@ import org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthe
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -79,7 +79,7 @@ public class JeeConfigurerTests {
public void jeeWhenInvokedTwiceThenUsesOriginalMappableRoles() throws Exception {
this.spring.register(InvokeTwiceDoesNotOverride.class).autowire();
Principal user = mock(Principal.class);
when(user.getName()).thenReturn("user");
given(user.getName()).willReturn("user");
this.mvc.perform(get("/").principal(user).with(request -> {
request.addUserRole("ROLE_ADMIN");
@@ -92,7 +92,7 @@ public class JeeConfigurerTests {
public void requestWhenJeeMappableRolesInLambdaThenAuthenticatedWithMappableRoles() throws Exception {
this.spring.register(JeeMappableRolesConfig.class).autowire();
Principal user = mock(Principal.class);
when(user.getName()).thenReturn("user");
given(user.getName()).willReturn("user");
this.mvc.perform(get("/").principal(user).with(request -> {
request.addUserRole("ROLE_ADMIN");
@@ -105,7 +105,7 @@ public class JeeConfigurerTests {
public void requestWhenJeeMappableAuthoritiesInLambdaThenAuthenticatedWithMappableAuthorities() throws Exception {
this.spring.register(JeeMappableAuthoritiesConfig.class).autowire();
Principal user = mock(Principal.class);
when(user.getName()).thenReturn("user");
given(user.getName()).willReturn("user");
this.mvc.perform(get("/").principal(user).with(request -> {
request.addUserRole("ROLE_ADMIN");
@@ -121,9 +121,9 @@ public class JeeConfigurerTests {
Principal user = mock(Principal.class);
User userDetails = new User("user", "N/A", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_USER"));
when(user.getName()).thenReturn("user");
when(JeeCustomAuthenticatedUserDetailsServiceConfig.authenticationUserDetailsService.loadUserDetails(any()))
.thenReturn(userDetails);
given(user.getName()).willReturn("user");
given(JeeCustomAuthenticatedUserDetailsServiceConfig.authenticationUserDetailsService.loadUserDetails(any()))
.willReturn(userDetails);
this.mvc.perform(get("/").principal(user).with(request -> {
request.addUserRole("ROLE_ADMIN");

View File

@@ -36,9 +36,9 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -63,7 +63,7 @@ public class NamespaceHttpJeeTests {
this.spring.register(JeeMappableRolesConfig.class, BaseController.class).autowire();
Principal user = mock(Principal.class);
when(user.getName()).thenReturn("joe");
given(user.getName()).willReturn("joe");
this.mvc.perform(get("/roles").principal(user).with(request -> {
request.addUserRole("ROLE_admin");
@@ -78,12 +78,12 @@ public class NamespaceHttpJeeTests {
this.spring.register(JeeUserServiceRefConfig.class, BaseController.class).autowire();
Principal user = mock(Principal.class);
when(user.getName()).thenReturn("joe");
given(user.getName()).willReturn("joe");
User result = new User(user.getName(), "N/A", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_user"));
when(bean(AuthenticationUserDetailsService.class).loadUserDetails(any())).thenReturn(result);
given(bean(AuthenticationUserDetailsService.class).loadUserDetails(any())).willReturn(result);
this.mvc.perform(get("/roles").principal(user)).andExpect(status().isOk())
.andExpect(content().string("ROLE_user"));

View File

@@ -58,11 +58,11 @@ import org.springframework.test.web.servlet.MvcResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.openid4java.discovery.yadis.YadisResolver.YADIS_XRDS_LOCATION;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -97,10 +97,11 @@ public class NamespaceHttpOpenIDLoginTests {
OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER = mock(ConsumerManager.class);
AuthRequest mockAuthRequest = mock(AuthRequest.class);
DiscoveryInformation mockDiscoveryInformation = mock(DiscoveryInformation.class);
when(mockAuthRequest.getDestinationUrl(anyBoolean())).thenReturn("mockUrl");
when(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.associate(any())).thenReturn(mockDiscoveryInformation);
when(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
any())).thenReturn(mockAuthRequest);
given(mockAuthRequest.getDestinationUrl(anyBoolean())).willReturn("mockUrl");
given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.associate(any()))
.willReturn(mockDiscoveryInformation);
given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
any())).willReturn(mockAuthRequest);
this.spring.register(OpenIDLoginAttributeExchangeConfig.class).autowire();
try (MockWebServer server = new MockWebServer()) {
@@ -144,20 +145,20 @@ public class NamespaceHttpOpenIDLoginTests {
"identityUrl", "message", Arrays.asList(new OpenIDAttribute("name", "type")));
OpenIDLoginCustomRefsConfig.AUDS = mock(AuthenticationUserDetailsService.class);
when(OpenIDLoginCustomRefsConfig.AUDS.loadUserDetails(any(Authentication.class)))
.thenReturn(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
given(OpenIDLoginCustomRefsConfig.AUDS.loadUserDetails(any(Authentication.class)))
.willReturn(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
OpenIDLoginCustomRefsConfig.ADS = spy(new WebAuthenticationDetailsSource());
OpenIDLoginCustomRefsConfig.CONSUMER = mock(OpenIDConsumer.class);
this.spring.register(OpenIDLoginCustomRefsConfig.class, UserDetailsServiceConfig.class).autowire();
when(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class)))
.thenThrow(new AuthenticationServiceException("boom"));
given(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class)))
.willThrow(new AuthenticationServiceException("boom"));
this.mvc.perform(post("/login/openid").with(csrf()).param("openid.identity", "identity"))
.andExpect(redirectedUrl("/custom/failure"));
reset(OpenIDLoginCustomRefsConfig.CONSUMER);
when(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class))).thenReturn(token);
given(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class))).willReturn(token);
this.mvc.perform(post("/login/openid").with(csrf()).param("openid.identity", "identity"))
.andExpect(redirectedUrl("/custom/targetUrl"));

View File

@@ -51,10 +51,10 @@ import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@@ -230,8 +230,8 @@ public class NamespaceRememberMeTests {
UserServiceRefConfig.USERDETAILS_SERVICE = mock(UserDetailsService.class);
this.spring.register(UserServiceRefConfig.class).autowire();
when(UserServiceRefConfig.USERDETAILS_SERVICE.loadUserByUsername("user"))
.thenReturn(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
given(UserServiceRefConfig.USERDETAILS_SERVICE.loadUserByUsername("user"))
.willReturn(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
this.mvc.perform(post("/login").with(rememberMeLogin()));

View File

@@ -56,10 +56,10 @@ import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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.result.MockMvcResultMatchers.redirectedUrl;
@@ -110,7 +110,7 @@ public class NamespaceSessionManagementTests {
SessionInformation sessionInformation = new SessionInformation(new Object(), session.getId(), new Date(0));
sessionInformation.expireNow();
SessionRegistry sessionRegistry = this.spring.getContext().getBean(SessionRegistry.class);
when(sessionRegistry.getSessionInformation(session.getId())).thenReturn(sessionInformation);
given(sessionRegistry.getSessionInformation(session.getId())).willReturn(sessionInformation);
this.mvc.perform(get("/auth").session(session)).andExpect(redirectedUrl("/expired-session"));
}
@@ -133,7 +133,7 @@ public class NamespaceSessionManagementTests {
MockHttpServletRequest mock = spy(MockHttpServletRequest.class);
mock.setSession(new MockHttpSession());
when(mock.changeSessionId()).thenThrow(SessionAuthenticationException.class);
given(mock.changeSessionId()).willThrow(SessionAuthenticationException.class);
mock.setMethod("GET");
this.mvc.perform(get("/auth").with(request -> mock).with(httpBasic("user", "password")))

View File

@@ -50,10 +50,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
@@ -95,8 +95,8 @@ public class RememberMeConfigurerTests {
@Test
public void rememberMeWhenInvokedTwiceThenUsesOriginalUserDetailsService() throws Exception {
when(DuplicateDoesNotOverrideConfig.userDetailsService.loadUserByUsername(anyString()))
.thenReturn(new User("user", "password", Collections.emptyList()));
given(DuplicateDoesNotOverrideConfig.userDetailsService.loadUserByUsername(anyString()))
.willReturn(new User("user", "password", Collections.emptyList()));
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
this.mvc.perform(get("/").with(httpBasic("user", "password")).param("remember-me", "true"));

View File

@@ -42,10 +42,10 @@ import org.springframework.test.web.servlet.MvcResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -74,7 +74,7 @@ public class SecurityContextConfigurerTests {
@Test
public void securityContextWhenInvokedTwiceThenUsesOriginalSecurityContextRepository() throws Exception {
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
when(DuplicateDoesNotOverrideConfig.SCR.loadContext(any())).thenReturn(mock(SecurityContext.class));
given(DuplicateDoesNotOverrideConfig.SCR.loadContext(any())).willReturn(mock(SecurityContext.class));
this.mvc.perform(get("/"));

View File

@@ -52,11 +52,11 @@ import org.springframework.test.web.servlet.MvcResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
@@ -93,8 +93,8 @@ public class SessionManagementConfigurerTests {
@Test
public void sessionManagementWhenConfiguredThenDoesNotOverrideSecurityContextRepository() throws Exception {
SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO = mock(SecurityContextRepository.class);
when(SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO
.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(mock(SecurityContext.class));
given(SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO
.loadContext(any(HttpRequestResponseHolder.class))).willReturn(mock(SecurityContext.class));
this.spring.register(SessionManagementSecurityContextRepositoryConfig.class).autowire();
this.mvc.perform(get("/"));
@@ -243,7 +243,7 @@ public class SessionManagementConfigurerTests {
public void getWhenAnonymousRequestAndTrustResolverSharedObjectReturnsAnonymousFalseThenSessionIsSaved()
throws Exception {
SharedTrustResolverConfig.TR = mock(AuthenticationTrustResolver.class);
when(SharedTrustResolverConfig.TR.isAnonymous(any())).thenReturn(false);
given(SharedTrustResolverConfig.TR.isAnonymous(any())).willReturn(false);
this.spring.register(SharedTrustResolverConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")).andReturn();

View File

@@ -66,9 +66,9 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
@@ -123,8 +123,8 @@ public class OAuth2ClientConfigurerTests {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(300).build();
accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
when(accessTokenResponseClient.getTokenResponse(any(OAuth2AuthorizationCodeGrantRequest.class)))
.thenReturn(accessTokenResponse);
given(accessTokenResponseClient.getTokenResponse(any(OAuth2AuthorizationCodeGrantRequest.class)))
.willReturn(accessTokenResponse);
requestCache = mock(RequestCache.class);
}
@@ -231,8 +231,8 @@ public class OAuth2ClientConfigurerTests {
// Override default resolver
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = authorizationRequestResolver;
authorizationRequestResolver = mock(OAuth2AuthorizationRequestResolver.class);
when(authorizationRequestResolver.resolve(any()))
.thenAnswer(invocation -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0)));
given(authorizationRequestResolver.resolve(any()))
.willAnswer(invocation -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0)));
this.spring.register(OAuth2ClientConfig.class).autowire();

View File

@@ -90,8 +90,8 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.security.oauth2.core.oidc.TestOidcIdTokens.idToken;
import static org.springframework.security.oauth2.jwt.TestJwts.jwt;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
@@ -325,7 +325,7 @@ public class OAuth2LoginConfigurerTests {
.authorizationRequestUri(
"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=clientId&scope=openid+profile+email&state=state&redirect_uri=http%3A%2F%2Flocalhost%2Flogin%2Foauth2%2Fcode%2Fgoogle&custom-param1=custom-value1")
.build();
when(resolver.resolve(any())).thenReturn(result);
given(resolver.resolve(any())).willReturn(result);
String requestUri = "/oauth2/authorization/google";
this.request = new MockHttpServletRequest("GET", requestUri);
@@ -348,7 +348,7 @@ public class OAuth2LoginConfigurerTests {
.authorizationRequestUri(
"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=clientId&scope=openid+profile+email&state=state&redirect_uri=http%3A%2F%2Flocalhost%2Flogin%2Foauth2%2Fcode%2Fgoogle&custom-param1=custom-value1")
.build();
when(resolver.resolve(any())).thenReturn(result);
given(resolver.resolve(any())).willReturn(result);
String requestUri = "/oauth2/authorization/google";
this.request = new MockHttpServletRequest("GET", requestUri);
@@ -995,7 +995,7 @@ public class OAuth2LoginConfigurerTests {
claims.put(IdTokenClaimNames.AZP, "clientId");
Jwt jwt = jwt().claims(c -> c.putAll(claims)).build();
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
when(jwtDecoder.decode(any())).thenReturn(jwt);
given(jwtDecoder.decode(any())).willReturn(jwt);
return jwtDecoder;
}

View File

@@ -135,10 +135,10 @@ import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes;
import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS;
@@ -590,7 +590,7 @@ public class OAuth2ResourceServerConfigurerTests {
.autowire();
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(anyString())).thenReturn(JWT);
given(decoder.decode(anyString())).willReturn(JWT);
this.mvc.perform(get("/authenticated").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk())
.andExpect(content().string(JWT_SUBJECT));
@@ -608,7 +608,7 @@ public class OAuth2ResourceServerConfigurerTests {
.autowire();
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(anyString())).thenReturn(JWT);
given(decoder.decode(anyString())).willReturn(JWT);
this.mvc.perform(get("/authenticated").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk())
.andExpect(content().string(JWT_SUBJECT));
@@ -625,7 +625,7 @@ public class OAuth2ResourceServerConfigurerTests {
.autowire();
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(anyString())).thenReturn(JWT);
given(decoder.decode(anyString())).willReturn(JWT);
this.mvc.perform(
post("/authenticated").param("access_token", JWT_TOKEN).with(bearerToken(JWT_TOKEN)).with(csrf()))
@@ -642,7 +642,7 @@ public class OAuth2ResourceServerConfigurerTests {
.autowire();
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(anyString())).thenReturn(JWT);
given(decoder.decode(anyString())).willReturn(JWT);
this.mvc.perform(get("/authenticated").with(bearerToken(JWT_TOKEN)).param("access_token", JWT_TOKEN))
.andExpect(status().isBadRequest())
@@ -707,7 +707,7 @@ public class OAuth2ResourceServerConfigurerTests {
CustomJwtDecoderOnDsl config = this.spring.getContext().getBean(CustomJwtDecoderOnDsl.class);
JwtDecoder decoder = config.decoder();
when(decoder.decode(anyString())).thenReturn(JWT);
given(decoder.decode(anyString())).willReturn(JWT);
this.mvc.perform(get("/authenticated").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk())
.andExpect(content().string(JWT_SUBJECT));
@@ -721,7 +721,7 @@ public class OAuth2ResourceServerConfigurerTests {
CustomJwtDecoderInLambdaOnDsl config = this.spring.getContext().getBean(CustomJwtDecoderInLambdaOnDsl.class);
JwtDecoder decoder = config.decoder();
when(decoder.decode(anyString())).thenReturn(JWT);
given(decoder.decode(anyString())).willReturn(JWT);
this.mvc.perform(get("/authenticated").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk())
.andExpect(content().string(JWT_SUBJECT));
@@ -734,7 +734,7 @@ public class OAuth2ResourceServerConfigurerTests {
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(anyString())).thenReturn(JWT);
given(decoder.decode(anyString())).willReturn(JWT);
this.mvc.perform(get("/authenticated").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk())
.andExpect(content().string(JWT_SUBJECT));
@@ -769,7 +769,7 @@ public class OAuth2ResourceServerConfigurerTests {
JwtDecoder decoder = mock(JwtDecoder.class);
ApplicationContext context = mock(ApplicationContext.class);
when(context.getBean(JwtDecoder.class)).thenReturn(decoderBean);
given(context.getBean(JwtDecoder.class)).willReturn(decoderBean);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
@@ -782,7 +782,7 @@ public class OAuth2ResourceServerConfigurerTests {
JwtDecoder decoder = mock(JwtDecoder.class);
ApplicationContext context = mock(ApplicationContext.class);
when(context.getBean(JwtDecoder.class)).thenReturn(decoder);
given(context.getBean(JwtDecoder.class)).willReturn(decoder);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
@@ -832,7 +832,7 @@ public class OAuth2ResourceServerConfigurerTests {
this.spring.register(RealmNameConfiguredOnEntryPoint.class, JwtDecoderConfig.class).autowire();
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(anyString())).thenThrow(JwtException.class);
given(decoder.decode(anyString())).willThrow(JwtException.class);
this.mvc.perform(get("/authenticated").with(bearerToken("invalid_token"))).andExpect(status().isUnauthorized())
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer realm=\"myRealm\"")));
@@ -844,7 +844,7 @@ public class OAuth2ResourceServerConfigurerTests {
this.spring.register(RealmNameConfiguredOnAccessDeniedHandler.class, JwtDecoderConfig.class).autowire();
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(anyString())).thenReturn(JWT);
given(decoder.decode(anyString())).willReturn(JWT);
this.mvc.perform(get("/authenticated").with(bearerToken("insufficiently_scoped")))
.andExpect(status().isForbidden())
@@ -879,7 +879,7 @@ public class OAuth2ResourceServerConfigurerTests {
OAuth2Error error = new OAuth2Error("custom-error", "custom-description", "custom-uri");
when(jwtValidator.validate(any(Jwt.class))).thenReturn(OAuth2TokenValidatorResult.failure(error));
given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(error));
this.mvc.perform(get("/").with(bearerToken(token))).andExpect(status().isUnauthorized())
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, containsString("custom-description")));
@@ -918,10 +918,10 @@ public class OAuth2ResourceServerConfigurerTests {
Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter = this.spring.getContext()
.getBean(JwtAuthenticationConverterConfiguredOnDsl.class).getJwtAuthenticationConverter();
when(jwtAuthenticationConverter.convert(JWT)).thenReturn(JWT_AUTHENTICATION_TOKEN);
given(jwtAuthenticationConverter.convert(JWT)).willReturn(JWT_AUTHENTICATION_TOKEN);
JwtDecoder jwtDecoder = this.spring.getContext().getBean(JwtDecoder.class);
when(jwtDecoder.decode(anyString())).thenReturn(JWT);
given(jwtDecoder.decode(anyString())).willReturn(JWT);
this.mvc.perform(get("/").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk());
@@ -936,7 +936,7 @@ public class OAuth2ResourceServerConfigurerTests {
.autowire();
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(JWT_TOKEN)).thenReturn(JWT);
given(decoder.decode(JWT_TOKEN)).willReturn(JWT);
this.mvc.perform(get("/requires-read-scope").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk());
}
@@ -975,7 +975,7 @@ public class OAuth2ResourceServerConfigurerTests {
public void requestWhenUsingCustomAuthenticationEventPublisherThenUses() throws Exception {
this.spring.register(CustomAuthenticationEventPublisher.class).autowire();
when(bean(JwtDecoder.class).decode(anyString())).thenThrow(new BadJwtException("problem"));
given(bean(JwtDecoder.class).decode(anyString())).willThrow(new BadJwtException("problem"));
this.mvc.perform(get("/").with(bearerToken("token")));
@@ -987,8 +987,8 @@ public class OAuth2ResourceServerConfigurerTests {
public void getWhenCustomJwtAuthenticationManagerThenUsed() throws Exception {
this.spring.register(JwtAuthenticationManagerConfig.class, BasicController.class).autowire();
when(bean(AuthenticationProvider.class).authenticate(any(Authentication.class)))
.thenReturn(JWT_AUTHENTICATION_TOKEN);
given(bean(AuthenticationProvider.class).authenticate(any(Authentication.class)))
.willReturn(JWT_AUTHENTICATION_TOKEN);
this.mvc.perform(get("/authenticated").with(bearerToken("token"))).andExpect(status().isOk())
.andExpect(content().string("mock-test-subject"));
@@ -1038,8 +1038,8 @@ public class OAuth2ResourceServerConfigurerTests {
public void getWhenCustomIntrospectionAuthenticationManagerThenUsed() throws Exception {
this.spring.register(OpaqueTokenAuthenticationManagerConfig.class, BasicController.class).autowire();
when(bean(AuthenticationProvider.class).authenticate(any(Authentication.class)))
.thenReturn(INTROSPECTION_AUTHENTICATION_TOKEN);
given(bean(AuthenticationProvider.class).authenticate(any(Authentication.class)))
.willReturn(INTROSPECTION_AUTHENTICATION_TOKEN);
this.mvc.perform(get("/authenticated").with(bearerToken("token"))).andExpect(status().isOk())
.andExpect(content().string("mock-test-subject"));
@@ -1050,8 +1050,8 @@ public class OAuth2ResourceServerConfigurerTests {
public void getWhenCustomIntrospectionAuthenticationManagerInLambdaThenUsed() throws Exception {
this.spring.register(OpaqueTokenAuthenticationManagerInLambdaConfig.class, BasicController.class).autowire();
when(bean(AuthenticationProvider.class).authenticate(any(Authentication.class)))
.thenReturn(INTROSPECTION_AUTHENTICATION_TOKEN);
given(bean(AuthenticationProvider.class).authenticate(any(Authentication.class)))
.willReturn(INTROSPECTION_AUTHENTICATION_TOKEN);
this.mvc.perform(get("/authenticated").with(bearerToken("token"))).andExpect(status().isOk())
.andExpect(content().string("mock-test-subject"));
@@ -1111,7 +1111,7 @@ public class OAuth2ResourceServerConfigurerTests {
this.spring.register(BasicAndResourceServerConfig.class, JwtDecoderConfig.class).autowire();
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(anyString())).thenThrow(JwtException.class);
given(decoder.decode(anyString())).willThrow(JwtException.class);
this.mvc.perform(get("/authenticated").with(httpBasic("some", "user"))).andExpect(status().isUnauthorized())
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, startsWith("Basic")));
@@ -1129,7 +1129,7 @@ public class OAuth2ResourceServerConfigurerTests {
this.spring.register(FormAndResourceServerConfig.class, JwtDecoderConfig.class).autowire();
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(anyString())).thenThrow(JwtException.class);
given(decoder.decode(anyString())).willThrow(JwtException.class);
MvcResult result = this.mvc.perform(get("/authenticated")).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/login")).andReturn();
@@ -1150,7 +1150,7 @@ public class OAuth2ResourceServerConfigurerTests {
.autowire();
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
when(decoder.decode(anyString())).thenReturn(JWT);
given(decoder.decode(anyString())).willReturn(JWT);
this.mvc.perform(get("/authenticated").with(httpBasic("basic-user", "basic-password")))
.andExpect(status().isForbidden()).andExpect(header().doesNotExist(HttpHeaders.WWW_AUTHENTICATE));
@@ -1380,7 +1380,7 @@ public class OAuth2ResourceServerConfigurerTests {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<String> entity = new ResponseEntity<>(response, headers, HttpStatus.OK);
when(rest.exchange(any(RequestEntity.class), eq(String.class))).thenReturn(entity);
given(rest.exchange(any(RequestEntity.class), eq(String.class))).willReturn(entity);
}
private <T> T bean(Class<T> beanClass) {

View File

@@ -43,10 +43,10 @@ import org.springframework.test.web.servlet.MvcResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.openid4java.discovery.yadis.YadisResolver.YADIS_XRDS_LOCATION;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -104,10 +104,10 @@ public class OpenIDLoginConfigurerTests {
OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER = mock(ConsumerManager.class);
AuthRequest mockAuthRequest = mock(AuthRequest.class);
DiscoveryInformation mockDiscoveryInformation = mock(DiscoveryInformation.class);
when(mockAuthRequest.getDestinationUrl(anyBoolean())).thenReturn("mockUrl");
when(OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER.associate(any())).thenReturn(mockDiscoveryInformation);
when(OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
any())).thenReturn(mockAuthRequest);
given(mockAuthRequest.getDestinationUrl(anyBoolean())).willReturn("mockUrl");
given(OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER.associate(any())).willReturn(mockDiscoveryInformation);
given(OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
any())).willReturn(mockAuthRequest);
this.spring.register(OpenIdAttributesInLambdaConfig.class).autowire();
try (MockWebServer server = new MockWebServer()) {
@@ -142,10 +142,10 @@ public class OpenIDLoginConfigurerTests {
OpenIdAttributesNullNameConfig.CONSUMER_MANAGER = mock(ConsumerManager.class);
AuthRequest mockAuthRequest = mock(AuthRequest.class);
DiscoveryInformation mockDiscoveryInformation = mock(DiscoveryInformation.class);
when(mockAuthRequest.getDestinationUrl(anyBoolean())).thenReturn("mockUrl");
when(OpenIdAttributesNullNameConfig.CONSUMER_MANAGER.associate(any())).thenReturn(mockDiscoveryInformation);
when(OpenIdAttributesNullNameConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
any())).thenReturn(mockAuthRequest);
given(mockAuthRequest.getDestinationUrl(anyBoolean())).willReturn("mockUrl");
given(OpenIdAttributesNullNameConfig.CONSUMER_MANAGER.associate(any())).willReturn(mockDiscoveryInformation);
given(OpenIdAttributesNullNameConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
any())).willReturn(mockAuthRequest);
this.spring.register(OpenIdAttributesNullNameConfig.class).autowire();
try (MockWebServer server = new MockWebServer()) {

View File

@@ -85,9 +85,9 @@ import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.saml2.core.TestSaml2X509Credentials.relyingPartyVerifyingCredential;
import static org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationRequestContexts.authenticationRequestContext;
@@ -173,7 +173,7 @@ public class Saml2LoginConfigurerTests {
Saml2AuthenticationRequestContext context = authenticationRequestContext().build();
Saml2AuthenticationRequestContextResolver resolver = CustomAuthenticationRequestContextResolver.resolver;
when(resolver.resolve(any(HttpServletRequest.class))).thenReturn(context);
given(resolver.resolve(any(HttpServletRequest.class))).willReturn(context);
this.mvc.perform(get("/saml2/authenticate/registration-id")).andExpect(status().isFound());
verify(resolver).resolve(any(HttpServletRequest.class));
}
@@ -198,8 +198,8 @@ public class Saml2LoginConfigurerTests {
party -> party.verificationX509Credentials(c -> c.add(relyingPartyVerifyingCredential())))
.build();
String response = new String(samlDecode(SIGNED_RESPONSE));
when(CustomAuthenticationConverter.authenticationConverter.convert(any(HttpServletRequest.class)))
.thenReturn(new Saml2AuthenticationToken(relyingPartyRegistration, response));
given(CustomAuthenticationConverter.authenticationConverter.convert(any(HttpServletRequest.class)))
.willReturn(new Saml2AuthenticationToken(relyingPartyRegistration, response));
this.mvc.perform(post("/login/saml2/sso/" + relyingPartyRegistration.getRegistrationId()).param("SAMLResponse",
SIGNED_RESPONSE)).andExpect(redirectedUrl("/"));
verify(CustomAuthenticationConverter.authenticationConverter).convert(any(HttpServletRequest.class));
@@ -387,7 +387,7 @@ public class Saml2LoginConfigurerTests {
@Bean
RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
RelyingPartyRegistrationRepository repository = mock(RelyingPartyRegistrationRepository.class);
when(repository.findByRegistrationId(anyString())).thenReturn(relyingPartyRegistration().build());
given(repository.findByRegistrationId(anyString())).willReturn(relyingPartyRegistration().build());
return repository;
}

View File

@@ -33,7 +33,7 @@ import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.util.AntPathMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
@RunWith(MockitoJUnitRunner.class)
public class MessageSecurityMetadataSourceRegistryTests {
@@ -100,7 +100,7 @@ public class MessageSecurityMetadataSourceRegistryTests {
@Test
public void matchersTrue() {
when(this.matcher.matches(this.message)).thenReturn(true);
given(this.matcher.matches(this.message)).willReturn(true);
this.messages.matchers(this.matcher).permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");

View File

@@ -38,9 +38,9 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -68,7 +68,7 @@ public class AuthenticationConfigurationGh3935Tests {
public void delegateUsesExisitingAuthentication() {
String username = "user";
String password = "password";
when(this.uds.loadUserByUsername(username)).thenReturn(PasswordEncodedUser.user());
given(this.uds.loadUserByUsername(username)).willReturn(PasswordEncodedUser.user());
AuthenticationManager authenticationManager = this.adapter.authenticationManager;
assertThat(authenticationManager).isNotNull();

View File

@@ -55,7 +55,7 @@ import org.springframework.web.servlet.support.RequestDataValueProcessor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
@@ -318,11 +318,11 @@ public class CsrfConfigTests {
context.autowire();
RequestMatcher matcher = context.getContext().getBean(RequestMatcher.class);
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
given(matcher.matches(any(HttpServletRequest.class))).willReturn(false);
this.mvc.perform(post("/ok")).andExpect(status().isOk());
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
given(matcher.matches(any(HttpServletRequest.class))).willReturn(true);
this.mvc.perform(get("/ok")).andExpect(status().isForbidden());
}

View File

@@ -40,7 +40,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyObject;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -86,7 +86,7 @@ public class DefaultFilterChainValidatorTests {
@Test
public void validateCheckLoginPageIsntProtectedThrowsIllegalArgumentException() {
IllegalArgumentException toBeThrown = new IllegalArgumentException("failed to eval expression");
doThrow(toBeThrown).when(this.accessDecisionManager).decide(any(Authentication.class), anyObject(),
willThrow(toBeThrown).given(this.accessDecisionManager).decide(any(Authentication.class), anyObject(),
any(Collection.class));
this.validator.validate(this.fcp);
verify(this.logger).info(

View File

@@ -35,9 +35,9 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
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.patch;
@@ -212,10 +212,10 @@ public class InterceptUrlConfigTests {
private MockServletContext mockServletContext(String servletPath) {
MockServletContext servletContext = spy(new MockServletContext());
final ServletRegistration registration = mock(ServletRegistration.class);
when(registration.getMappings()).thenReturn(Collections.singleton(servletPath));
given(registration.getMappings()).willReturn(Collections.singleton(servletPath));
Answer<Map<String, ? extends ServletRegistration>> answer = invocation -> Collections.singletonMap("spring",
registration);
when(servletContext.getServletRegistrations()).thenAnswer(answer);
given(servletContext.getServletRegistrations()).willAnswer(answer);
return servletContext;
}

View File

@@ -112,11 +112,11 @@ import org.springframework.web.context.support.XmlWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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.x509;
@@ -451,7 +451,7 @@ public class MiscHttpConfigTests {
SecurityContextRepository repository = this.spring.getContext().getBean(SecurityContextRepository.class);
SecurityContext context = new SecurityContextImpl(new TestingAuthenticationToken("user", "password"));
when(repository.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(context);
given(repository.loadContext(any(HttpRequestResponseHolder.class))).willReturn(context);
MvcResult result = this.mvc.perform(get("/protected").with(httpBasic("user", "password")))
.andExpect(status().isOk()).andReturn();
@@ -479,8 +479,8 @@ public class MiscHttpConfigTests {
this.spring.configLocations(xml("ExpressionHandler")).autowire();
PermissionEvaluator permissionEvaluator = this.spring.getContext().getBean(PermissionEvaluator.class);
when(permissionEvaluator.hasPermission(any(Authentication.class), any(Object.class), any(Object.class)))
.thenReturn(false);
given(permissionEvaluator.hasPermission(any(Authentication.class), any(Object.class), any(Object.class)))
.willReturn(false);
this.mvc.perform(get("/").with(httpBasic("user", "password"))).andExpect(status().isForbidden());
@@ -585,7 +585,7 @@ public class MiscHttpConfigTests {
this.spring.configLocations(xml("JeeFilter")).autowire();
Principal user = mock(Principal.class);
when(user.getName()).thenReturn("joe");
given(user.getName()).willReturn("joe");
this.mvc.perform(get("/roles").principal(user).with(request -> {
request.addUserRole("admin");
@@ -603,7 +603,7 @@ public class MiscHttpConfigTests {
Object details = mock(Object.class);
AuthenticationDetailsSource source = this.spring.getContext().getBean(AuthenticationDetailsSource.class);
when(source.buildDetails(any(Object.class))).thenReturn(details);
given(source.buildDetails(any(Object.class))).willReturn(details);
this.mvc.perform(get("/details").with(httpBasic("user", "password")))
.andExpect(content().string(details.getClass().getName()));
@@ -627,7 +627,7 @@ public class MiscHttpConfigTests {
this.spring.configLocations(xml("Jaas")).autowire();
AuthorityGranter granter = this.spring.getContext().getBean(AuthorityGranter.class);
when(granter.grant(any(Principal.class))).thenReturn(new HashSet<>(Arrays.asList("USER")));
given(granter.grant(any(Principal.class))).willReturn(new HashSet<>(Arrays.asList("USER")));
this.mvc.perform(get("/username").with(httpBasic("user", "password"))).andExpect(content().string("user"));
}
@@ -644,8 +644,8 @@ public class MiscHttpConfigTests {
HttpServletResponse response = new MockHttpServletResponse();
HttpFirewall firewall = this.spring.getContext().getBean(HttpFirewall.class);
when(firewall.getFirewalledRequest(any(HttpServletRequest.class))).thenReturn(request);
when(firewall.getFirewalledResponse(any(HttpServletResponse.class))).thenReturn(response);
given(firewall.getFirewalledRequest(any(HttpServletRequest.class))).willReturn(request);
given(firewall.getFirewalledResponse(any(HttpServletResponse.class))).willReturn(response);
this.mvc.perform(get("/unprotected"));
verify(firewall).getFirewalledRequest(any(HttpServletRequest.class));
@@ -661,7 +661,7 @@ public class MiscHttpConfigTests {
RequestRejectedException rejected = new RequestRejectedException("failed");
HttpFirewall firewall = this.spring.getContext().getBean(HttpFirewall.class);
RequestRejectedHandler requestRejectedHandler = this.spring.getContext().getBean(RequestRejectedHandler.class);
when(firewall.getFirewalledRequest(any(HttpServletRequest.class))).thenThrow(rejected);
given(firewall.getFirewalledRequest(any(HttpServletRequest.class))).willThrow(rejected);
this.mvc.perform(get("/unprotected"));
verify(requestRejectedHandler).handle(any(), any(), any());
@@ -697,8 +697,8 @@ public class MiscHttpConfigTests {
private void redirectLogsTo(OutputStream os, Class<?> clazz) {
Logger logger = (Logger) LoggerFactory.getLogger(clazz);
Appender<ILoggingEvent> appender = mock(Appender.class);
when(appender.isStarted()).thenReturn(true);
doAnswer(writeTo(os)).when(appender).doAppend(any(ILoggingEvent.class));
given(appender.isStarted()).willReturn(true);
willAnswer(writeTo(os)).given(appender).doAppend(any(ILoggingEvent.class));
logger.addAppender(appender);
}

View File

@@ -53,8 +53,8 @@ import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.accessTokenResponse;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@@ -114,7 +114,7 @@ public class OAuth2ClientBeanDefinitionParserTests {
ClientRegistration clientRegistration = CommonOAuth2Provider.GOOGLE.getBuilder("google")
.clientId("google-client-id").clientSecret("google-client-secret")
.redirectUri("http://localhost/callback/google").scope("scope1", "scope2").build();
when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(clientRegistration);
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(clientRegistration);
MvcResult result = this.mvc.perform(get("/oauth2/authorization/google")).andExpect(status().is3xxRedirection())
.andReturn();
@@ -132,7 +132,7 @@ public class OAuth2ClientBeanDefinitionParserTests {
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest(clientRegistration);
when(this.authorizationRequestResolver.resolve(any())).thenReturn(authorizationRequest);
given(this.authorizationRequestResolver.resolve(any())).willReturn(authorizationRequest);
this.mvc.perform(get("/oauth2/authorization/google")).andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("https://accounts.google.com/o/oauth2/v2/auth?"
@@ -149,12 +149,12 @@ public class OAuth2ClientBeanDefinitionParserTests {
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest(clientRegistration);
when(this.authorizationRequestRepository.loadAuthorizationRequest(any())).thenReturn(authorizationRequest);
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -179,12 +179,12 @@ public class OAuth2ClientBeanDefinitionParserTests {
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest(clientRegistration);
when(this.authorizationRequestRepository.loadAuthorizationRequest(any())).thenReturn(authorizationRequest);
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -204,7 +204,7 @@ public class OAuth2ClientBeanDefinitionParserTests {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, "user",
TestOAuth2AccessTokens.noScopes());
when(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).thenReturn(authorizedClient);
given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).willReturn(authorizedClient);
this.mvc.perform(get("/authorized-client")).andExpect(status().isOk()).andExpect(content().string("resolved"));
}

View File

@@ -75,9 +75,9 @@ import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.accessTokenResponse;
import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.oidcAccessTokenResponse;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -211,14 +211,14 @@ public class OAuth2LoginBeanDefinitionParserTests {
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "github-login");
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.attributes(attributes).build();
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User oauth2User = TestOAuth2Users.create();
when(this.oauth2UserService.loadUser(any())).thenReturn(oauth2User);
given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -240,14 +240,14 @@ public class OAuth2LoginBeanDefinitionParserTests {
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "github-login");
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.attributes(attributes).build();
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User oauth2User = TestOAuth2Users.create();
when(this.oauth2UserService.loadUser(any())).thenReturn(oauth2User);
given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -266,14 +266,14 @@ public class OAuth2LoginBeanDefinitionParserTests {
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "google-login");
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.oidcRequest()
.attributes(attributes).build();
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
OAuth2AccessTokenResponse accessTokenResponse = oidcAccessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
Jwt jwt = TestJwts.user();
when(this.jwtDecoderFactory.createDecoder(any())).thenReturn(token -> jwt);
given(this.jwtDecoderFactory.createDecoder(any())).willReturn(token -> jwt);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -294,17 +294,17 @@ public class OAuth2LoginBeanDefinitionParserTests {
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "github-login");
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.attributes(attributes).build();
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User oauth2User = TestOAuth2Users.create();
when(this.oauth2UserService.loadUser(any())).thenReturn(oauth2User);
given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
when(this.userAuthoritiesMapper.mapAuthorities(any()))
.thenReturn((Collection) AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER"));
given(this.userAuthoritiesMapper.mapAuthorities(any()))
.willReturn((Collection) AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER"));
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -323,17 +323,17 @@ public class OAuth2LoginBeanDefinitionParserTests {
attributes = new HashMap<>();
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "google-login");
authorizationRequest = TestOAuth2AuthorizationRequests.oidcRequest().attributes(attributes).build();
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
accessTokenResponse = oidcAccessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
Jwt jwt = TestJwts.user();
when(this.jwtDecoderFactory.createDecoder(any())).thenReturn(token -> jwt);
given(this.jwtDecoderFactory.createDecoder(any())).willReturn(token -> jwt);
when(this.userAuthoritiesMapper.mapAuthorities(any()))
.thenReturn((Collection) AuthorityUtils.createAuthorityList("ROLE_OIDC_USER"));
given(this.userAuthoritiesMapper.mapAuthorities(any()))
.willReturn((Collection) AuthorityUtils.createAuthorityList("ROLE_OIDC_USER"));
this.mvc.perform(get("/login/oauth2/code/google-login").params(params)).andExpect(status().is2xxSuccessful());
@@ -356,14 +356,14 @@ public class OAuth2LoginBeanDefinitionParserTests {
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "github-login");
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.attributes(attributes).build();
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User oauth2User = TestOAuth2Users.create();
when(this.oauth2UserService.loadUser(any())).thenReturn(oauth2User);
given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -419,20 +419,20 @@ public class OAuth2LoginBeanDefinitionParserTests {
this.spring.configLocations(this.xml("WithCustomClientRegistrationRepository")).autowire();
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(clientRegistration);
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(clientRegistration);
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId());
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.attributes(attributes).build();
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User oauth2User = TestOAuth2Users.create();
when(this.oauth2UserService.loadUser(any())).thenReturn(oauth2User);
given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -447,20 +447,20 @@ public class OAuth2LoginBeanDefinitionParserTests {
this.spring.configLocations(this.xml("WithCustomAuthorizedClientRepository")).autowire();
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(clientRegistration);
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(clientRegistration);
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId());
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.attributes(attributes).build();
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User oauth2User = TestOAuth2Users.create();
when(this.oauth2UserService.loadUser(any())).thenReturn(oauth2User);
given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -475,20 +475,20 @@ public class OAuth2LoginBeanDefinitionParserTests {
this.spring.configLocations(this.xml("WithCustomAuthorizedClientService")).autowire();
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(clientRegistration);
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(clientRegistration);
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId());
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.attributes(attributes).build();
when(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.thenReturn(authorizationRequest);
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
.willReturn(authorizationRequest);
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User oauth2User = TestOAuth2Users.create();
when(this.oauth2UserService.loadUser(any())).thenReturn(oauth2User);
given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -507,7 +507,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, "user",
TestOAuth2AccessTokens.noScopes());
when(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).thenReturn(authorizedClient);
given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).willReturn(authorizedClient);
this.mvc.perform(get("/authorized-client")).andExpect(status().isOk()).andExpect(content().string("resolved"));
}

View File

@@ -46,8 +46,8 @@ import static org.assertj.core.api.Assertions.assertThatCode;
import static org.hamcrest.CoreMatchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.openid4java.discovery.yadis.YadisResolver.YADIS_XRDS_LOCATION;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@@ -116,8 +116,8 @@ public class OpenIDConfigTests {
openIDFilter.setReturnToUrlParameters(returnToUrlParameters);
OpenIDConsumer consumer = mock(OpenIDConsumer.class);
when(consumer.beginConsumption(any(HttpServletRequest.class), anyString(), anyString(), anyString()))
.then(invocation -> openIdEndpointUrl + invocation.getArgument(2));
given(consumer.beginConsumption(any(HttpServletRequest.class), anyString(), anyString(), anyString()))
.will(invocation -> openIdEndpointUrl + invocation.getArgument(2));
openIDFilter.setConsumer(consumer);
String expectedReturnTo = new StringBuilder("http://localhost/login/openid").append("?")

View File

@@ -39,9 +39,9 @@ import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.DEFAULT_PARAMETER;
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY;
@@ -228,8 +228,8 @@ public class RememberMeConfigTests {
this.spring.configLocations(this.xml("WithUserDetailsService")).autowire();
UserDetailsService userDetailsService = this.spring.getContext().getBean(UserDetailsService.class);
when(userDetailsService.loadUserByUsername("user"))
.thenAnswer((invocation) -> new User("user", "{noop}password", Collections.emptyList()));
given(userDetailsService.loadUserByUsername("user"))
.willAnswer((invocation) -> new User("user", "{noop}password", Collections.emptyList()));
MvcResult result = this.rememberAuthentication("user", "password").andReturn();

View File

@@ -39,7 +39,7 @@ import org.springframework.web.cors.reactive.CorsConfigurationSource;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -65,7 +65,7 @@ public class CorsSpecTests {
this.http = new TestingServerHttpSecurity().applicationContext(this.context);
CorsConfiguration value = new CorsConfiguration();
value.setAllowedOrigins(Arrays.asList("*"));
when(this.source.getCorsConfiguration(any())).thenReturn(value);
given(this.source.getCorsConfiguration(any())).willReturn(value);
}
@Test
@@ -86,9 +86,9 @@ public class CorsSpecTests {
@Test
public void corsWhenCorsConfigurationSourceBeanThenAccessControlAllowOriginAndSecurityHeaders() {
when(this.context.getBeanNamesForType(any(ResolvableType.class))).thenReturn(new String[] { "source" },
given(this.context.getBeanNamesForType(any(ResolvableType.class))).willReturn(new String[] { "source" },
new String[0]);
when(this.context.getBean("source")).thenReturn(this.source);
given(this.context.getBean("source")).willReturn(this.source);
this.expectedHeaders.set("Access-Control-Allow-Origin", "*");
this.expectedHeaders.set("X-Frame-Options", "DENY");
assertHeaders();
@@ -96,7 +96,7 @@ public class CorsSpecTests {
@Test
public void corsWhenNoConfigurationSourceThenNoCorsHeaders() {
when(this.context.getBeanNamesForType(any(ResolvableType.class))).thenReturn(new String[0]);
given(this.context.getBeanNamesForType(any(ResolvableType.class))).willReturn(new String[0]);
this.headerNamesNotPresent.add("Access-Control-Allow-Origin");
assertHeaders();
}

View File

@@ -31,8 +31,8 @@ import org.springframework.security.web.server.util.matcher.PathPatternParserSer
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.config.EnableWebFlux;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.security.config.Customizer.withDefaults;
/**
@@ -100,7 +100,7 @@ public class HttpsRedirectSpecTests {
this.spring.register(RedirectToHttpsViaCustomPortsConfig.class).autowire();
PortMapper portMapper = this.spring.getContext().getBean(PortMapper.class);
when(portMapper.lookupHttpsPort(4080)).thenReturn(4443);
given(portMapper.lookupHttpsPort(4080)).willReturn(4443);
this.client.get().uri("http://localhost:4080").exchange().expectStatus().isFound().expectHeader()
.valueEquals(HttpHeaders.LOCATION, "https://localhost:4443");
@@ -111,7 +111,7 @@ public class HttpsRedirectSpecTests {
this.spring.register(RedirectToHttpsViaCustomPortsInLambdaConfig.class).autowire();
PortMapper portMapper = this.spring.getContext().getBean(PortMapper.class);
when(portMapper.lookupHttpsPort(4080)).thenReturn(4443);
given(portMapper.lookupHttpsPort(4080)).willReturn(4443);
this.client.get().uri("http://localhost:4080").exchange().expectStatus().isFound().expectHeader()
.valueEquals(HttpHeaders.LOCATION, "https://localhost:4443");

View File

@@ -60,9 +60,9 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.config.EnableWebFlux;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -93,9 +93,9 @@ public class OAuth2ClientSpecTests {
.getBean(ReactiveClientRegistrationRepository.class);
ServerOAuth2AuthorizedClientRepository authorizedClientRepository = this.spring.getContext()
.getBean(ServerOAuth2AuthorizedClientRepository.class);
when(repository.findByRegistrationId(any()))
.thenReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
when(authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).thenReturn(Mono.empty());
given(repository.findByRegistrationId(any()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
given(authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
this.client.get().uri("/").exchange().expectStatus().is3xxRedirection();
}
@@ -107,9 +107,9 @@ public class OAuth2ClientSpecTests {
.getBean(ReactiveClientRegistrationRepository.class);
ServerOAuth2AuthorizedClientRepository authorizedClientRepository = this.spring.getContext()
.getBean(ServerOAuth2AuthorizedClientRepository.class);
when(repository.findByRegistrationId(any()))
.thenReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
when(authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).thenReturn(Mono.empty());
given(repository.findByRegistrationId(any()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
given(authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
this.client.get().uri("/").exchange().expectStatus().is3xxRedirection();
}
@@ -137,11 +137,11 @@ public class OAuth2ClientSpecTests {
OAuth2AuthorizationCodeAuthenticationToken result = new OAuth2AuthorizationCodeAuthenticationToken(
this.registration, authorizationExchange, accessToken);
when(authorizationRequestRepository.loadAuthorizationRequest(any()))
.thenReturn(Mono.just(authorizationRequest));
when(converter.convert(any())).thenReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
when(manager.authenticate(any())).thenReturn(Mono.just(result));
when(requestCache.getRedirectUri(any())).thenReturn(Mono.just(URI.create("/saved-request")));
given(authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(authorizationRequest));
given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
given(manager.authenticate(any())).willReturn(Mono.just(result));
given(requestCache.getRedirectUri(any())).willReturn(Mono.just(URI.create("/saved-request")));
this.client.get()
.uri(uriBuilder -> uriBuilder.path("/authorize/oauth2/code/registration-id")
@@ -178,11 +178,11 @@ public class OAuth2ClientSpecTests {
OAuth2AuthorizationCodeAuthenticationToken result = new OAuth2AuthorizationCodeAuthenticationToken(
this.registration, authorizationExchange, accessToken);
when(authorizationRequestRepository.loadAuthorizationRequest(any()))
.thenReturn(Mono.just(authorizationRequest));
when(converter.convert(any())).thenReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
when(manager.authenticate(any())).thenReturn(Mono.just(result));
when(requestCache.getRedirectUri(any())).thenReturn(Mono.just(URI.create("/saved-request")));
given(authorizationRequestRepository.loadAuthorizationRequest(any()))
.willReturn(Mono.just(authorizationRequest));
given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
given(manager.authenticate(any())).willReturn(Mono.just(result));
given(requestCache.getRedirectUri(any())).willReturn(Mono.just(URI.create("/saved-request")));
this.client.get()
.uri(uriBuilder -> uriBuilder.path("/authorize/oauth2/code/registration-id")

View File

@@ -104,10 +104,10 @@ import org.springframework.web.server.WebHandler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.oauth2.jwt.TestJwts.jwt;
/**
@@ -186,10 +186,10 @@ public class OAuth2LoginTests {
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = config.authorizationRequestRepository;
ServerRequestCache requestCache = config.requestCache;
when(authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).thenReturn(Mono.empty());
when(authorizationRequestRepository.saveAuthorizationRequest(any(), any())).thenReturn(Mono.empty());
when(requestCache.removeMatchingRequest(any())).thenReturn(Mono.empty());
when(requestCache.saveRequest(any())).thenReturn(Mono.empty());
given(authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(authorizationRequestRepository.saveAuthorizationRequest(any(), any())).willReturn(Mono.empty());
given(requestCache.removeMatchingRequest(any())).willReturn(Mono.empty());
given(requestCache.saveRequest(any())).willReturn(Mono.empty());
this.client.get().uri("/").exchange().expectStatus().is3xxRedirection();
@@ -222,11 +222,11 @@ public class OAuth2LoginTests {
OAuth2LoginAuthenticationToken result = new OAuth2LoginAuthenticationToken(github, exchange, user,
user.getAuthorities(), accessToken);
when(converter.convert(any())).thenReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
when(manager.authenticate(any())).thenReturn(Mono.just(result));
when(matcher.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(resolver.resolve(any())).thenReturn(Mono.empty());
when(successHandler.onAuthenticationSuccess(any(), any())).thenAnswer((Answer<Mono<Void>>) invocation -> {
given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
given(manager.authenticate(any())).willReturn(Mono.just(result));
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(resolver.resolve(any())).willReturn(Mono.empty());
given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) invocation -> {
WebFilterExchange webFilterExchange = invocation.getArgument(0);
Authentication authentication = invocation.getArgument(1);
@@ -263,19 +263,19 @@ public class OAuth2LoginTests {
ServerAuthenticationSuccessHandler successHandler = config.successHandler;
ServerAuthenticationFailureHandler failureHandler = config.failureHandler;
when(converter.convert(any())).thenReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
when(manager.authenticate(any()))
.thenReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("error"), "message")));
when(matcher.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(resolver.resolve(any())).thenReturn(Mono.empty());
when(successHandler.onAuthenticationSuccess(any(), any())).thenAnswer((Answer<Mono<Void>>) invocation -> {
given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
given(manager.authenticate(any()))
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("error"), "message")));
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(resolver.resolve(any())).willReturn(Mono.empty());
given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) invocation -> {
WebFilterExchange webFilterExchange = invocation.getArgument(0);
Authentication authentication = invocation.getArgument(1);
return new RedirectServerAuthenticationSuccessHandler(redirectLocation)
.onAuthenticationSuccess(webFilterExchange, authentication);
});
when(failureHandler.onAuthenticationFailure(any(), any())).thenAnswer((Answer<Mono<Void>>) invocation -> {
given(failureHandler.onAuthenticationFailure(any(), any())).willAnswer((Answer<Mono<Void>>) invocation -> {
WebFilterExchange webFilterExchange = invocation.getArgument(0);
AuthenticationException authenticationException = invocation.getArgument(1);
@@ -317,11 +317,11 @@ public class OAuth2LoginTests {
OAuth2LoginAuthenticationToken result = new OAuth2LoginAuthenticationToken(github, exchange, user,
user.getAuthorities(), accessToken);
when(converter.convert(any())).thenReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
when(manager.authenticate(any())).thenReturn(Mono.just(result));
when(matcher.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(resolver.resolve(any())).thenReturn(Mono.empty());
when(successHandler.onAuthenticationSuccess(any(), any())).thenAnswer((Answer<Mono<Void>>) invocation -> {
given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
given(manager.authenticate(any())).willReturn(Mono.just(result));
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(resolver.resolve(any())).willReturn(Mono.empty());
given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) invocation -> {
WebFilterExchange webFilterExchange = invocation.getArgument(0);
Authentication authentication = invocation.getArgument(1);
@@ -357,11 +357,11 @@ public class OAuth2LoginTests {
exchange, accessToken);
ServerAuthenticationConverter converter = config.authenticationConverter;
when(converter.convert(any())).thenReturn(Mono.just(token));
given(converter.convert(any())).willReturn(Mono.just(token));
ServerSecurityContextRepository securityContextRepository = config.securityContextRepository;
when(securityContextRepository.save(any(), any())).thenReturn(Mono.empty());
when(securityContextRepository.load(any())).thenReturn(authentication(token));
given(securityContextRepository.save(any(), any())).willReturn(Mono.empty());
given(securityContextRepository.load(any())).willReturn(authentication(token));
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put(OidcParameterNames.ID_TOKEN, "id-token");
@@ -369,11 +369,11 @@ public class OAuth2LoginTests {
.tokenType(accessToken.getTokenType()).scopes(accessToken.getScopes())
.additionalParameters(additionalParameters).build();
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> tokenResponseClient = config.tokenResponseClient;
when(tokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse));
given(tokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
OidcUser user = TestOidcUsers.create();
ReactiveOAuth2UserService<OidcUserRequest, OidcUser> userService = config.userService;
when(userService.loadUser(any())).thenReturn(Mono.just(user));
given(userService.loadUser(any())).willReturn(Mono.just(user));
webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection();
@@ -401,11 +401,11 @@ public class OAuth2LoginTests {
.getBean(OAuth2LoginWithCustomBeansConfig.class);
ServerAuthenticationConverter converter = config.authenticationConverter;
when(converter.convert(any())).thenReturn(Mono.just(authenticationToken));
given(converter.convert(any())).willReturn(Mono.just(authenticationToken));
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> tokenResponseClient = config.tokenResponseClient;
OAuth2Error oauth2Error = new OAuth2Error("invalid_request", "Invalid request", null);
when(tokenResponseClient.getTokenResponse(any())).thenThrow(new OAuth2AuthenticationException(oauth2Error));
given(tokenResponseClient.getTokenResponse(any())).willThrow(new OAuth2AuthenticationException(oauth2Error));
webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection().expectHeader()
.valueEquals("Location", "/login?error");
@@ -430,7 +430,7 @@ public class OAuth2LoginTests {
google, exchange, accessToken);
ServerAuthenticationConverter converter = config.authenticationConverter;
when(converter.convert(any())).thenReturn(Mono.just(authenticationToken));
given(converter.convert(any())).willReturn(Mono.just(authenticationToken));
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put(OidcParameterNames.ID_TOKEN, "id-token");
@@ -438,11 +438,11 @@ public class OAuth2LoginTests {
.tokenType(accessToken.getTokenType()).scopes(accessToken.getScopes())
.additionalParameters(additionalParameters).build();
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> tokenResponseClient = config.tokenResponseClient;
when(tokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse));
given(tokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = config.jwtDecoderFactory;
OAuth2Error oauth2Error = new OAuth2Error("invalid_id_token", "Invalid ID Token", null);
when(jwtDecoderFactory.createDecoder(any())).thenReturn(token -> Mono
given(jwtDecoderFactory.createDecoder(any())).willReturn(token -> Mono
.error(new JwtValidationException("ID Token validation failed", Collections.singleton(oauth2Error))));
webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection().expectHeader()
@@ -457,7 +457,7 @@ public class OAuth2LoginTests {
AuthorityUtils.NO_AUTHORITIES, getBean(ClientRegistration.class).getRegistrationId());
ServerSecurityContextRepository repository = getBean(ServerSecurityContextRepository.class);
when(repository.load(any())).thenReturn(authentication(token));
given(repository.load(any())).willReturn(authentication(token));
this.client.post().uri("/logout").exchange().expectHeader().valueEquals("Location",
"https://logout?id_token_hint=id-token");

View File

@@ -83,9 +83,9 @@ import static org.assertj.core.api.Assertions.assertThatCode;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.oauth2.jwt.TestJwts.jwt;
/**
@@ -196,7 +196,7 @@ public class OAuth2ResourceServerSpecTests {
this.spring.register(CustomDecoderConfig.class, RootController.class).autowire();
ReactiveJwtDecoder jwtDecoder = this.spring.getContext().getBean(ReactiveJwtDecoder.class);
when(jwtDecoder.decode(anyString())).thenReturn(Mono.just(this.jwt));
given(jwtDecoder.decode(anyString())).willReturn(Mono.just(this.jwt));
this.client.get().headers(headers -> headers.setBearerAuth("token")).exchange().expectStatus().isOk();
@@ -231,8 +231,8 @@ public class OAuth2ResourceServerSpecTests {
ReactiveAuthenticationManager authenticationManager = this.spring.getContext()
.getBean(ReactiveAuthenticationManager.class);
when(authenticationManager.authenticate(any(Authentication.class)))
.thenReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
given(authenticationManager.authenticate(any(Authentication.class)))
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isUnauthorized().expectHeader()
@@ -245,8 +245,8 @@ public class OAuth2ResourceServerSpecTests {
ReactiveAuthenticationManager authenticationManager = this.spring.getContext()
.getBean(ReactiveAuthenticationManager.class);
when(authenticationManager.authenticate(any(Authentication.class)))
.thenReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
given(authenticationManager.authenticate(any(Authentication.class)))
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isUnauthorized().expectHeader()
@@ -263,10 +263,10 @@ public class OAuth2ResourceServerSpecTests {
ReactiveAuthenticationManager authenticationManager = this.spring.getContext()
.getBean(ReactiveAuthenticationManager.class);
when(authenticationManagerResolver.resolve(any(ServerWebExchange.class)))
.thenReturn(Mono.just(authenticationManager));
when(authenticationManager.authenticate(any(Authentication.class)))
.thenReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
given(authenticationManagerResolver.resolve(any(ServerWebExchange.class)))
.willReturn(Mono.just(authenticationManager));
given(authenticationManager.authenticate(any(Authentication.class)))
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isUnauthorized().expectHeader()

View File

@@ -77,7 +77,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.test.util.ReflectionTestUtils.getField;
@@ -108,7 +107,7 @@ public class ServerHttpSecurityTests {
@Test
public void defaults() {
TestPublisher<SecurityContext> securityContext = TestPublisher.create();
when(this.contextRepository.load(any())).thenReturn(securityContext.mono());
given(this.contextRepository.load(any())).willReturn(securityContext.mono());
this.http.securityContextRepository(this.contextRepository);
WebTestClient client = buildClient();
@@ -411,7 +410,7 @@ public class ServerHttpSecurityTests {
@Test
public void postWhenCustomCsrfTokenRepositoryThenUsed() {
ServerCsrfTokenRepository customServerCsrfTokenRepository = mock(ServerCsrfTokenRepository.class);
when(customServerCsrfTokenRepository.loadToken(any(ServerWebExchange.class))).thenReturn(Mono.empty());
given(customServerCsrfTokenRepository.loadToken(any(ServerWebExchange.class))).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http
.csrf(csrf -> csrf.csrfTokenRepository(customServerCsrfTokenRepository)).build();
WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
@@ -453,8 +452,8 @@ public class ServerHttpSecurityTests {
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().build();
when(authorizationRequestRepository.removeAuthorizationRequest(any()))
.thenReturn(Mono.just(authorizationRequest));
given(authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(authorizationRequest));
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login()
.clientRegistrationRepository(clientRegistrationRepository)