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

@ -30,10 +30,10 @@ import org.springframework.security.core.Authentication;
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.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@ -51,8 +51,8 @@ public class AclPermissionCacheOptimizerTests {
pco.setSidRetrievalStrategy(sidStrat);
Object[] dos = { new Object(), null, new Object() };
ObjectIdentity[] oids = { new ObjectIdentityImpl("A", "1"), new ObjectIdentityImpl("A", "2") };
when(oidStrat.getObjectIdentity(dos[0])).thenReturn(oids[0]);
when(oidStrat.getObjectIdentity(dos[2])).thenReturn(oids[1]);
given(oidStrat.getObjectIdentity(dos[0])).willReturn(oids[0]);
given(oidStrat.getObjectIdentity(dos[2])).willReturn(oids[1]);
pco.cachePermissionsFor(mock(Authentication.class), Arrays.asList(dos));

View File

@ -30,8 +30,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@ -45,13 +45,13 @@ public class AclPermissionEvaluatorTests {
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
when(oidStrategy.getObjectIdentity(any(Object.class))).thenReturn(oid);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl);
when(acl.isGranted(anyList(), anyList(), eq(false))).thenReturn(true);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
}
@ -65,13 +65,13 @@ public class AclPermissionEvaluatorTests {
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
when(oidStrategy.getObjectIdentity(any(Object.class))).thenReturn(oid);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
when(service.readAclById(any(ObjectIdentity.class), anyList())).thenReturn(acl);
when(acl.isGranted(anyList(), anyList(), eq(false))).thenReturn(true);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue();

View File

@ -35,10 +35,10 @@ import org.springframework.security.core.Authentication;
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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@ -50,8 +50,8 @@ public class AclEntryAfterInvocationCollectionFilteringProviderTests {
public void objectsAreRemovedIfPermissionDenied() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
when(acl.isGranted(any(), any(), anyBoolean())).thenReturn(false);
when(service.readAclById(any(), any())).thenReturn(acl);
given(acl.isGranted(any(), any(), anyBoolean())).willReturn(false);
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider(
service, Arrays.asList(mock(Permission.class)));
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));

View File

@ -38,10 +38,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@ -64,8 +64,8 @@ public class AclEntryAfterInvocationProviderTests {
public void accessIsAllowedIfPermissionIsGranted() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(true);
when(service.readAclById(any(), any())).thenReturn(acl);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(true);
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service,
Arrays.asList(mock(Permission.class)));
provider.setMessageSource(new SpringSecurityMessageSource());
@ -104,10 +104,10 @@ public class AclEntryAfterInvocationProviderTests {
public void accessIsDeniedIfPermissionIsNotGranted() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(false);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(false);
// Try a second time with no permissions found
when(acl.isGranted(any(), any(List.class), anyBoolean())).thenThrow(new NotFoundException(""));
when(service.readAclById(any(), any())).thenReturn(acl);
given(acl.isGranted(any(), any(List.class), anyBoolean())).willThrow(new NotFoundException(""));
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service,
Arrays.asList(mock(Permission.class)));
provider.setProcessConfigAttribute("MY_ATTRIBUTE");

View File

@ -25,8 +25,8 @@ import org.springframework.security.acls.model.Sid;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for {@link AccessControlEntryImpl}.
@ -87,7 +87,7 @@ public class AccessControlImplEntryTests {
final Acl mockAcl = mock(Acl.class);
final ObjectIdentity oid = mock(ObjectIdentity.class);
when(mockAcl.getObjectIdentity()).thenReturn(oid);
given(mockAcl.getObjectIdentity()).willReturn(oid);
Sid sid = new PrincipalSid("johndoe");
AccessControlEntry ace = new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true,

View File

@ -26,8 +26,8 @@ import org.springframework.security.acls.model.AccessControlEntry;
import org.springframework.security.acls.model.AuditableAccessControlEntry;
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.when;
/**
* Test class for {@link ConsoleAuditLogger}.
@ -67,14 +67,14 @@ public class AuditLoggerTests {
@Test
public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() {
when(this.ace.isAuditSuccess()).thenReturn(false);
given(this.ace.isAuditSuccess()).willReturn(false);
this.logger.logIfNeeded(true, this.ace);
assertThat(this.bytes.size()).isZero();
}
@Test
public void successIsLoggedIfAceRequiresSuccessAudit() {
when(this.ace.isAuditSuccess()).thenReturn(true);
given(this.ace.isAuditSuccess()).willReturn(true);
this.logger.logIfNeeded(true, this.ace);
assertThat(this.bytes.toString()).startsWith("GRANTED due to ACE");
@ -82,14 +82,14 @@ public class AuditLoggerTests {
@Test
public void failureIsntLoggedIfAceDoesntRequireFailureAudit() {
when(this.ace.isAuditFailure()).thenReturn(false);
given(this.ace.isAuditFailure()).willReturn(false);
this.logger.logIfNeeded(false, this.ace);
assertThat(this.bytes.size()).isZero();
}
@Test
public void failureIsLoggedIfAceRequiresFailureAudit() {
when(this.ace.isAuditFailure()).thenReturn(true);
given(this.ace.isAuditFailure()).willReturn(true);
this.logger.logIfNeeded(false, this.ace);
assertThat(this.bytes.toString()).startsWith("DENIED due to ACE");
}

View File

@ -52,9 +52,9 @@ import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests {@link EhCacheBasedAclCache}
@ -220,14 +220,14 @@ public class EhCacheBasedAclCacheTests {
@Test
public void getFromCacheSerializable() {
when(this.cache.get(this.acl.getId())).thenReturn(new Element(this.acl.getId(), this.acl));
given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl));
assertThat(this.myCache.getFromCache(this.acl.getId())).isEqualTo(this.acl);
}
@Test
public void getFromCacheSerializablePopulatesTransient() {
when(this.cache.get(this.acl.getId())).thenReturn(new Element(this.acl.getId(), this.acl));
given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl));
this.myCache.putInCache(this.acl);
@ -242,14 +242,14 @@ public class EhCacheBasedAclCacheTests {
@Test
public void getFromCacheObjectIdentity() {
when(this.cache.get(this.acl.getId())).thenReturn(new Element(this.acl.getId(), this.acl));
given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl));
assertThat(this.myCache.getFromCache(this.acl.getId())).isEqualTo(this.acl);
}
@Test
public void getFromCacheObjectIdentityPopulatesTransient() {
when(this.cache.get(this.acl.getObjectIdentity())).thenReturn(new Element(this.acl.getId(), this.acl));
given(this.cache.get(this.acl.getObjectIdentity())).willReturn(new Element(this.acl.getId(), this.acl));
this.myCache.putInCache(this.acl);
@ -264,7 +264,7 @@ public class EhCacheBasedAclCacheTests {
@Test
public void evictCacheSerializable() {
when(this.cache.get(this.acl.getObjectIdentity())).thenReturn(new Element(this.acl.getId(), this.acl));
given(this.cache.get(this.acl.getObjectIdentity())).willReturn(new Element(this.acl.getId(), this.acl));
this.myCache.evictFromCache(this.acl.getObjectIdentity());
@ -274,7 +274,7 @@ public class EhCacheBasedAclCacheTests {
@Test
public void evictCacheObjectIdentity() {
when(this.cache.get(this.acl.getId())).thenReturn(new Element(this.acl.getId(), this.acl));
given(this.cache.get(this.acl.getId())).willReturn(new Element(this.acl.getId(), this.acl));
this.myCache.evictFromCache(this.acl.getId());

View File

@ -47,7 +47,7 @@ import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* Unit and Integration tests the ACL JdbcAclService using an in-memory database.
@ -93,7 +93,7 @@ public class JdbcAclServiceTests {
@Test(expected = NotFoundException.class)
public void readAclByIdMissingAcl() {
Map<ObjectIdentity, Acl> result = new HashMap<>();
when(this.lookupStrategy.readAclsById(anyList(), anyList())).thenReturn(result);
given(this.lookupStrategy.readAclsById(anyList(), anyList())).willReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 1);
List<Sid> sids = Arrays.<Sid>asList(new PrincipalSid("user"));
@ -105,7 +105,7 @@ public class JdbcAclServiceTests {
List<ObjectIdentity> result = new ArrayList<>();
result.add(new ObjectIdentityImpl(Object.class, "5577"));
Object[] args = { "1", "org.springframework.security.acls.jdbc.JdbcAclServiceTests$MockLongIdDomainObject" };
when(this.jdbcOperations.query(anyString(), aryEq(args), any(RowMapper.class))).thenReturn(result);
given(this.jdbcOperations.query(anyString(), aryEq(args), any(RowMapper.class))).willReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L);
List<ObjectIdentity> objectIdentities = this.aclService.findChildren(objectIdentity);

View File

@ -55,8 +55,8 @@ import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* Integration tests the ACL system using an in-memory database.
@ -537,7 +537,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
CustomJdbcMutableAclService customJdbcMutableAclService = spy(
new CustomJdbcMutableAclService(this.dataSource, this.lookupStrategy, this.aclCache));
CustomSid customSid = new CustomSid("Custom sid");
when(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).thenReturn(1L);
given(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).willReturn(1L);
Long result = customJdbcMutableAclService.createOrRetrieveSidPrimaryKey(customSid, false);

View File

@ -31,8 +31,8 @@ import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for {@link SidRetrievalStrategyImpl}
@ -69,7 +69,7 @@ public class SidRetrievalStrategyTests {
public void roleHierarchyIsUsedWhenSet() {
RoleHierarchy rh = mock(RoleHierarchy.class);
List rhAuthorities = AuthorityUtils.createAuthorityList("D");
when(rh.getReachableGrantedAuthorities(anyCollection())).thenReturn(rhAuthorities);
given(rh.getReachableGrantedAuthorities(anyCollection())).willReturn(rhAuthorities);
SidRetrievalStrategy strat = new SidRetrievalStrategyImpl(rh);
List<Sid> sids = strat.getSids(this.authentication);

View File

@ -43,10 +43,10 @@ import org.springframework.security.web.authentication.WebAuthenticationDetails;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
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;
/**
* Tests {@link CasAuthenticationProvider}.
@ -160,9 +160,9 @@ public class CasAuthenticationProviderTests {
public void authenticateAllNullService() throws Exception {
String serviceUrl = "https://service/context";
ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
when(details.getServiceUrl()).thenReturn(serviceUrl);
given(details.getServiceUrl()).willReturn(serviceUrl);
TicketValidator validator = mock(TicketValidator.class);
when(validator.validate(any(String.class), any(String.class))).thenReturn(new AssertionImpl("rod"));
given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);
@ -186,9 +186,9 @@ public class CasAuthenticationProviderTests {
public void authenticateAllAuthenticationIsSuccessful() throws Exception {
String serviceUrl = "https://service/context";
ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
when(details.getServiceUrl()).thenReturn(serviceUrl);
given(details.getServiceUrl()).willReturn(serviceUrl);
TicketValidator validator = mock(TicketValidator.class);
when(validator.validate(any(String.class), any(String.class))).thenReturn(new AssertionImpl("rod"));
given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);

View File

@ -29,8 +29,8 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
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.when;
/**
* @author Luke Taylor
@ -50,9 +50,9 @@ public class GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests {
attributes.put("c", "role_c");
attributes.put("d", null);
attributes.put("someother", "unused");
when(assertion.getPrincipal()).thenReturn(principal);
when(principal.getAttributes()).thenReturn(attributes);
when(principal.getName()).thenReturn("somebody");
given(assertion.getPrincipal()).willReturn(principal);
given(principal.getAttributes()).willReturn(attributes);
given(principal.getName()).willReturn("somebody");
CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken(assertion, "ticket");
UserDetails user = uds.loadUserDetails(token);
Set<String> roles = AuthorityUtils.authorityListToSet(user.getAuthorities());

View File

@ -37,11 +37,11 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand
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.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link CasAuthenticationFilter}.
@ -163,7 +163,7 @@ public class CasAuthenticationFilterTests {
AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class);
AuthenticationManager manager = mock(AuthenticationManager.class);
Authentication authentication = new TestingAuthenticationToken("un", "pwd", "ROLE_USER");
when(manager.authenticate(any(Authentication.class))).thenReturn(authentication);
given(manager.authenticate(any(Authentication.class))).willReturn(authentication);
ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);
MockHttpServletRequest request = new MockHttpServletRequest();

View File

@ -54,8 +54,8 @@ import org.springframework.util.MimeTypeUtils;
import static io.rsocket.metadata.WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION;
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.when;
/**
* @author Rob Winch
@ -97,7 +97,7 @@ public class JwtITests {
@Test
public void routeWhenBearerThenAuthorized() {
BearerTokenMetadata credentials = new BearerTokenMetadata("token");
when(this.decoder.decode(any())).thenReturn(Mono.just(jwt()));
given(this.decoder.decode(any())).willReturn(Mono.just(jwt()));
this.requester = requester()
.setupMetadata(credentials.getToken(), BearerTokenMetadata.BEARER_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
@ -112,7 +112,7 @@ public class JwtITests {
MimeType authenticationMimeType = MimeTypeUtils.parseMimeType(MESSAGE_RSOCKET_AUTHENTICATION.getString());
BearerTokenMetadata credentials = new BearerTokenMetadata("token");
when(this.decoder.decode(any())).thenReturn(Mono.just(jwt()));
given(this.decoder.decode(any())).willReturn(Mono.just(jwt()));
this.requester = requester().setupMetadata(credentials, authenticationMimeType)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();

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)

View File

@ -24,8 +24,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
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.when;
/**
* @author Luke Taylor
@ -55,7 +55,7 @@ public class SecurityExpressionRootTests {
public void rememberMeIsCorrectlyDetected() {
AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
this.root.setTrustResolver(atr);
when(atr.isRememberMe(JOE)).thenReturn(true);
given(atr.isRememberMe(JOE)).willReturn(true);
assertThat(this.root.isRememberMe()).isTrue();
assertThat(this.root.isFullyAuthenticated()).isFalse();
}

View File

@ -37,10 +37,10 @@ import org.springframework.security.core.context.SecurityContextHolder;
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.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DefaultMethodSecurityExpressionHandlerTests {
@ -59,8 +59,8 @@ public class DefaultMethodSecurityExpressionHandlerTests {
@Before
public void setup() {
this.handler = new DefaultMethodSecurityExpressionHandler();
when(this.methodInvocation.getThis()).thenReturn(new Foo());
when(this.methodInvocation.getMethod()).thenReturn(Foo.class.getMethods()[0]);
given(this.methodInvocation.getThis()).willReturn(new Foo());
given(this.methodInvocation.getMethod()).willReturn(Foo.class.getMethods()[0]);
}
@After

View File

@ -29,8 +29,8 @@ import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
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.when;
/**
* Tests for {@link MethodSecurityExpressionRoot}
@ -69,13 +69,13 @@ public class MethodSecurityExpressionRootTests {
@Test
public void isAnonymousReturnsTrueIfTrustResolverReportsAnonymous() {
when(this.trustResolver.isAnonymous(this.user)).thenReturn(true);
given(this.trustResolver.isAnonymous(this.user)).willReturn(true);
assertThat(this.root.isAnonymous()).isTrue();
}
@Test
public void isAnonymousReturnsFalseIfTrustResolverReportsNonAnonymous() {
when(this.trustResolver.isAnonymous(this.user)).thenReturn(false);
given(this.trustResolver.isAnonymous(this.user)).willReturn(false);
assertThat(this.root.isAnonymous()).isFalse();
}
@ -85,7 +85,7 @@ public class MethodSecurityExpressionRootTests {
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
this.ctx.setVariable("domainObject", dummyDomainObject);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(this.user, dummyDomainObject, "ignored")).thenReturn(false);
given(pe.hasPermission(this.user, dummyDomainObject, "ignored")).willReturn(false);
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isFalse();
@ -97,7 +97,7 @@ public class MethodSecurityExpressionRootTests {
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
this.ctx.setVariable("domainObject", dummyDomainObject);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(this.user, dummyDomainObject, "ignored")).thenReturn(true);
given(pe.hasPermission(this.user, dummyDomainObject, "ignored")).willReturn(true);
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isTrue();
}
@ -108,8 +108,7 @@ public class MethodSecurityExpressionRootTests {
this.ctx.setVariable("domainObject", dummyDomainObject);
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(eq(this.user), eq(dummyDomainObject), any(Integer.class))).thenReturn(true)
.thenReturn(true).thenReturn(false);
given(pe.hasPermission(eq(this.user), eq(dummyDomainObject), any(Integer.class))).willReturn(true, true, false);
Expression e = this.parser.parseExpression("hasPermission(#domainObject, 0xA)");
// evaluator returns true
@ -133,8 +132,8 @@ public class MethodSecurityExpressionRootTests {
Integer i = 2;
PermissionEvaluator pe = mock(PermissionEvaluator.class);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(this.user, targetObject, i)).thenReturn(true).thenReturn(false);
when(pe.hasPermission(this.user, "x", i)).thenReturn(true);
given(pe.hasPermission(this.user, targetObject, i)).willReturn(true, false);
given(pe.hasPermission(this.user, "x", i)).willReturn(true);
Expression e = this.parser.parseExpression("hasPermission(this, 2)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();

View File

@ -51,12 +51,12 @@ import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link MethodSecurityInterceptor}.
@ -150,21 +150,21 @@ public class MethodSecurityInterceptorTests {
@Test(expected = IllegalArgumentException.class)
public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation() throws Throwable {
when(this.mds.supports(MethodInvocation.class)).thenReturn(false);
given(this.mds.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation() throws Exception {
when(this.mds.supports(MethodInvocation.class)).thenReturn(true);
when(this.adm.supports(MethodInvocation.class)).thenReturn(false);
given(this.mds.supports(MethodInvocation.class)).willReturn(true);
given(this.adm.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation() throws Exception {
final RunAsManager ram = mock(RunAsManager.class);
when(ram.supports(MethodInvocation.class)).thenReturn(false);
given(ram.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.setRunAsManager(ram);
this.interceptor.afterPropertiesSet();
}
@ -172,21 +172,21 @@ public class MethodSecurityInterceptorTests {
@Test(expected = IllegalArgumentException.class)
public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation() throws Exception {
final AfterInvocationManager aim = mock(AfterInvocationManager.class);
when(aim.supports(MethodInvocation.class)).thenReturn(false);
given(aim.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.setAfterInvocationManager(aim);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes() throws Exception {
when(this.adm.supports(any(ConfigAttribute.class))).thenReturn(false);
given(this.adm.supports(any(ConfigAttribute.class))).willReturn(false);
this.interceptor.afterPropertiesSet();
}
@Test
public void validationNotAttemptedIfIsValidateConfigAttributesSetToFalse() throws Exception {
when(this.adm.supports(MethodInvocation.class)).thenReturn(true);
when(this.mds.supports(MethodInvocation.class)).thenReturn(true);
given(this.adm.supports(MethodInvocation.class)).willReturn(true);
given(this.mds.supports(MethodInvocation.class)).willReturn(true);
this.interceptor.setValidateConfigAttributes(false);
this.interceptor.afterPropertiesSet();
verify(this.mds, never()).getAllConfigAttributes();
@ -195,9 +195,9 @@ public class MethodSecurityInterceptorTests {
@Test
public void validationNotAttemptedIfMethodSecurityMetadataSourceReturnsNullForAttributes() throws Exception {
when(this.adm.supports(MethodInvocation.class)).thenReturn(true);
when(this.mds.supports(MethodInvocation.class)).thenReturn(true);
when(this.mds.getAllConfigAttributes()).thenReturn(null);
given(this.adm.supports(MethodInvocation.class)).willReturn(true);
given(this.mds.supports(MethodInvocation.class)).willReturn(true);
given(this.mds.getAllConfigAttributes()).willReturn(null);
this.interceptor.setValidateConfigAttributes(true);
this.interceptor.afterPropertiesSet();
@ -226,7 +226,7 @@ public class MethodSecurityInterceptorTests {
SecurityContextHolder.getContext().setAuthentication(token);
mdsReturnsUserRole();
when(this.authman.authenticate(token)).thenThrow(new BadCredentialsException("rejected"));
given(this.authman.authenticate(token)).willThrow(new BadCredentialsException("rejected"));
this.advisedTarget.makeLowerCase("HELLO");
}
@ -253,8 +253,8 @@ public class MethodSecurityInterceptorTests {
// so test would fail)
createTarget(true);
mdsReturnsUserRole();
when(this.authman.authenticate(this.token)).thenReturn(this.token);
doThrow(new AccessDeniedException("rejected")).when(this.adm).decide(any(Authentication.class),
given(this.authman.authenticate(this.token)).willReturn(this.token);
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(any(Authentication.class),
any(MethodInvocation.class), any(List.class));
try {
@ -281,7 +281,7 @@ public class MethodSecurityInterceptorTests {
TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
String result = this.advisedTarget.makeUpperCase("hello");
assertThat(result).isEqualTo("HELLO org.springframework.security.access.intercept.RunAsUserToken true");
@ -294,7 +294,7 @@ public class MethodSecurityInterceptorTests {
@Test
public void runAsReplacementCleansAfterException() {
createTarget(true);
when(this.realTarget.makeUpperCase(anyString())).thenThrow(new RuntimeException());
given(this.realTarget.makeUpperCase(anyString())).willThrow(new RuntimeException());
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
@ -303,7 +303,7 @@ public class MethodSecurityInterceptorTests {
TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
try {
this.advisedTarget.makeUpperCase("hello");
@ -333,7 +333,7 @@ public class MethodSecurityInterceptorTests {
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
when(mi.proceed()).thenThrow(new Throwable());
given(mi.proceed()).willThrow(new Throwable());
try {
this.interceptor.invoke(mi);
@ -346,11 +346,11 @@ public class MethodSecurityInterceptorTests {
}
void mdsReturnsNull() {
when(this.mds.getAttributes(any(MethodInvocation.class))).thenReturn(null);
given(this.mds.getAttributes(any(MethodInvocation.class))).willReturn(null);
}
void mdsReturnsUserRole() {
when(this.mds.getAttributes(any(MethodInvocation.class))).thenReturn(SecurityConfig.createList("ROLE_USER"));
given(this.mds.getAttributes(any(MethodInvocation.class))).willReturn(SecurityConfig.createList("ROLE_USER"));
}
}

View File

@ -25,8 +25,8 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.method.MethodSecurityMetadataSource;
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.when;
/**
* Tests {@link MethodSecurityMetadataSourceAdvisor}.
@ -41,7 +41,7 @@ public class MethodSecurityMetadataSourceAdvisorTests {
Method method = clazz.getMethod("makeLowerCase", new Class[] { String.class });
MethodSecurityMetadataSource mds = mock(MethodSecurityMetadataSource.class);
when(mds.getAttributes(method, clazz)).thenReturn(null);
given(mds.getAttributes(method, clazz)).willReturn(null);
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor("", mds, "");
assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isFalse();
}
@ -52,7 +52,7 @@ public class MethodSecurityMetadataSourceAdvisorTests {
Method method = clazz.getMethod("countLength", new Class[] { String.class });
MethodSecurityMetadataSource mds = mock(MethodSecurityMetadataSource.class);
when(mds.getAttributes(method, clazz)).thenReturn(SecurityConfig.createList("ROLE_A"));
given(mds.getAttributes(method, clazz)).willReturn(SecurityConfig.createList("ROLE_A"));
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor("", mds, "");
assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isTrue();
}

View File

@ -48,12 +48,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link AspectJMethodSecurityInterceptor}.
@ -91,17 +91,17 @@ public class AspectJMethodSecurityInterceptorTests {
this.joinPoint = mock(ProceedingJoinPoint.class); // new MockJoinPoint(new
// TargetObject(), method);
Signature sig = mock(Signature.class);
when(sig.getDeclaringType()).thenReturn(TargetObject.class);
given(sig.getDeclaringType()).willReturn(TargetObject.class);
JoinPoint.StaticPart staticPart = mock(JoinPoint.StaticPart.class);
when(this.joinPoint.getSignature()).thenReturn(sig);
when(this.joinPoint.getStaticPart()).thenReturn(staticPart);
given(this.joinPoint.getSignature()).willReturn(sig);
given(this.joinPoint.getStaticPart()).willReturn(staticPart);
CodeSignature codeSig = mock(CodeSignature.class);
when(codeSig.getName()).thenReturn("countLength");
when(codeSig.getDeclaringType()).thenReturn(TargetObject.class);
when(codeSig.getParameterTypes()).thenReturn(new Class[] { String.class });
when(staticPart.getSignature()).thenReturn(codeSig);
when(this.mds.getAttributes(any())).thenReturn(SecurityConfig.createList("ROLE_USER"));
when(this.authman.authenticate(this.token)).thenReturn(this.token);
given(codeSig.getName()).willReturn("countLength");
given(codeSig.getDeclaringType()).willReturn(TargetObject.class);
given(codeSig.getParameterTypes()).willReturn(new Class[] { String.class });
given(staticPart.getSignature()).willReturn(codeSig);
given(this.mds.getAttributes(any())).willReturn(SecurityConfig.createList("ROLE_USER"));
given(this.authman.authenticate(this.token)).willReturn(this.token);
}
@After
@ -122,7 +122,7 @@ public class AspectJMethodSecurityInterceptorTests {
@SuppressWarnings("unchecked")
@Test
public void callbackIsNotInvokedWhenPermissionDenied() {
doThrow(new AccessDeniedException("denied")).when(this.adm).decide(any(), any(), any());
willThrow(new AccessDeniedException("denied")).given(this.adm).decide(any(), any(), any());
SecurityContextHolder.getContext().setAuthentication(this.token);
try {
@ -139,8 +139,8 @@ public class AspectJMethodSecurityInterceptorTests {
TargetObject to = new TargetObject();
Method m = ClassUtils.getMethodIfAvailable(TargetObject.class, "countLength", new Class[] { String.class });
when(this.joinPoint.getTarget()).thenReturn(to);
when(this.joinPoint.getArgs()).thenReturn(new Object[] { "Hi" });
given(this.joinPoint.getTarget()).willReturn(to);
given(this.joinPoint.getArgs()).willReturn(new Object[] { "Hi" });
MethodInvocationAdapter mia = new MethodInvocationAdapter(this.joinPoint);
assertThat(mia.getArguments()[0]).isEqualTo("Hi");
assertThat(mia.getStaticPart()).isEqualTo(m);
@ -156,7 +156,7 @@ public class AspectJMethodSecurityInterceptorTests {
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
when(this.aspectJCallback.proceedWithObject()).thenThrow(new RuntimeException());
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
try {
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
@ -179,8 +179,8 @@ public class AspectJMethodSecurityInterceptorTests {
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(),
TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(this.aspectJCallback.proceedWithObject()).thenThrow(new RuntimeException());
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
try {
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
@ -205,8 +205,8 @@ public class AspectJMethodSecurityInterceptorTests {
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(),
TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(this.joinPoint.proceed()).thenThrow(new RuntimeException());
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.joinPoint.proceed()).willThrow(new RuntimeException());
try {
this.interceptor.invoke(this.joinPoint);

View File

@ -38,9 +38,9 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.util.MethodInvocationUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests
@ -80,7 +80,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
when(this.mds.getAttributes(mi)).thenReturn(this.role);
given(this.mds.getAttributes(mi)).willReturn(this.role);
mipe.setSecurityInterceptor(this.interceptor);
mipe.afterPropertiesSet();
@ -94,7 +94,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
"makeLowerCase", new Class[] { String.class }, new Object[] { "Hello world" });
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(this.interceptor);
when(this.mds.getAttributes(mi)).thenReturn(this.role);
given(this.mds.getAttributes(mi)).willReturn(this.role);
assertThat(mipe.isAllowed(mi, this.token)).isTrue();
}
@ -105,8 +105,8 @@ public class MethodInvocationPrivilegeEvaluatorTests {
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(this.interceptor);
when(this.mds.getAttributes(mi)).thenReturn(this.role);
doThrow(new AccessDeniedException("rejected")).when(this.adm).decide(this.token, mi, this.role);
given(this.mds.getAttributes(mi)).willReturn(this.role);
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(this.token, mi, this.role);
assertThat(mipe.isAllowed(mi, this.token)).isFalse();
}
@ -118,8 +118,8 @@ public class MethodInvocationPrivilegeEvaluatorTests {
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(this.interceptor);
when(this.mds.getAttributes(mi)).thenReturn(this.role);
doThrow(new AccessDeniedException("rejected")).when(this.adm).decide(this.token, mi, this.role);
given(this.mds.getAttributes(mi)).willReturn(this.role);
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(this.token, mi, this.role);
assertThat(mipe.isAllowed(mi, this.token)).isFalse();
}

View File

@ -29,8 +29,8 @@ import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.util.SimpleMethodInvocation;
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.when;
/**
* @author Luke Taylor
@ -44,8 +44,8 @@ public class DelegatingMethodSecurityMetadataSourceTests {
public void returnsEmptyListIfDelegateReturnsNull() throws Exception {
List sources = new ArrayList();
MethodSecurityMetadataSource delegate = mock(MethodSecurityMetadataSource.class);
when(delegate.getAttributes(ArgumentMatchers.<Method>any(), ArgumentMatchers.any(Class.class)))
.thenReturn(null);
given(delegate.getAttributes(ArgumentMatchers.<Method>any(), ArgumentMatchers.any(Class.class)))
.willReturn(null);
sources.add(delegate);
this.mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);
@ -63,7 +63,7 @@ public class DelegatingMethodSecurityMetadataSourceTests {
ConfigAttribute ca = mock(ConfigAttribute.class);
List attributes = Arrays.asList(ca);
Method toString = String.class.getMethod("toString");
when(delegate.getAttributes(toString, String.class)).thenReturn(attributes);
given(delegate.getAttributes(toString, String.class)).willReturn(attributes);
sources.add(delegate);
this.mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);

View File

@ -31,8 +31,8 @@ import org.springframework.security.core.Authentication;
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.when;
/**
* Tests {@link AffirmativeBased}.
@ -61,12 +61,12 @@ public class AffirmativeBasedTests {
this.abstain = mock(AccessDecisionVoter.class);
this.deny = mock(AccessDecisionVoter.class);
when(this.grant.vote(any(Authentication.class), any(Object.class), any(List.class)))
.thenReturn(AccessDecisionVoter.ACCESS_GRANTED);
when(this.abstain.vote(any(Authentication.class), any(Object.class), any(List.class)))
.thenReturn(AccessDecisionVoter.ACCESS_ABSTAIN);
when(this.deny.vote(any(Authentication.class), any(Object.class), any(List.class)))
.thenReturn(AccessDecisionVoter.ACCESS_DENIED);
given(this.grant.vote(any(Authentication.class), any(Object.class), any(List.class)))
.willReturn(AccessDecisionVoter.ACCESS_GRANTED);
given(this.abstain.vote(any(Authentication.class), any(Object.class), any(List.class)))
.willReturn(AccessDecisionVoter.ACCESS_ABSTAIN);
given(this.deny.vote(any(Authentication.class), any(Object.class), any(List.class)))
.willReturn(AccessDecisionVoter.ACCESS_DENIED);
}
@Test

View File

@ -27,10 +27,10 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests {@link AbstractAuthenticationToken}.
@ -128,7 +128,7 @@ public class AbstractAuthenticationTokenTests {
String principalName = "test";
AuthenticatedPrincipal principal = mock(AuthenticatedPrincipal.class);
when(principal.getName()).thenReturn(principalName);
given(principal.getName()).willReturn(principalName);
MockAuthenticationImpl token = new MockAuthenticationImpl(principal, "Password", this.authorities);
assertThat(token.getName()).isEqualTo(principalName);

View File

@ -29,7 +29,7 @@ import org.springframework.security.core.Authentication;
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;
/**
* @author Rob Winch
@ -49,8 +49,8 @@ public class DelegatingReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenEmptyAndNotThenReturnsNotEmpty() {
when(this.delegate1.authenticate(any())).thenReturn(Mono.empty());
when(this.delegate2.authenticate(any())).thenReturn(Mono.just(this.authentication));
given(this.delegate1.authenticate(any())).willReturn(Mono.empty());
given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
this.delegate2);
@ -62,8 +62,8 @@ public class DelegatingReactiveAuthenticationManagerTests {
public void authenticateWhenNotEmptyThenOtherDelegatesNotSubscribed() {
// delay to try and force delegate2 to finish (i.e. make sure we didn't use
// flatMap)
when(this.delegate1.authenticate(any()))
.thenReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
given(this.delegate1.authenticate(any()))
.willReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
this.delegate2);
@ -73,7 +73,7 @@ public class DelegatingReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenBadCredentialsThenDelegate2NotInvokedAndError() {
when(this.delegate1.authenticate(any())).thenReturn(Mono.error(new BadCredentialsException("Test")));
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
this.delegate2);

View File

@ -31,12 +31,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
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.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link ProviderManager}.
@ -121,7 +121,7 @@ public class ProviderManagerTests {
public void constructorWhenUsingListOfThenNoException() {
List<AuthenticationProvider> providers = spy(ArrayList.class);
// List.of(null) in JDK 9 throws a NullPointerException
when(providers.contains(eq(null))).thenThrow(NullPointerException.class);
given(providers.contains(eq(null))).willThrow(NullPointerException.class);
providers.add(mock(AuthenticationProvider.class));
new ProviderManager(providers);
}
@ -211,7 +211,7 @@ public class ProviderManagerTests {
public void parentAuthenticationIsUsedIfProvidersDontAuthenticate() {
AuthenticationManager parent = mock(AuthenticationManager.class);
Authentication authReq = mock(Authentication.class);
when(parent.authenticate(authReq)).thenReturn(authReq);
given(parent.authenticate(authReq)).willReturn(authReq);
ProviderManager mgr = new ProviderManager(Collections.singletonList(mock(AuthenticationProvider.class)),
parent);
assertThat(mgr.authenticate(authReq)).isSameAs(authReq);
@ -238,7 +238,7 @@ public class ProviderManagerTests {
final Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
AuthenticationManager parent = mock(AuthenticationManager.class);
when(parent.authenticate(authReq)).thenThrow(new ProviderNotFoundException(""));
given(parent.authenticate(authReq)).willThrow(new ProviderNotFoundException(""));
// Set a provider that throws an exception - this is the exception we expect to be
// propagated
@ -266,7 +266,7 @@ public class ProviderManagerTests {
// Set a provider that throws an exception - this is the exception we expect to be
// propagated
final BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
when(parent.authenticate(authReq)).thenThrow(expected);
given(parent.authenticate(authReq)).willThrow(expected);
try {
mgr.authenticate(authReq);
fail("Expected exception");
@ -339,16 +339,16 @@ public class ProviderManagerTests {
private AuthenticationProvider createProviderWhichThrows(final AuthenticationException e) {
AuthenticationProvider provider = mock(AuthenticationProvider.class);
when(provider.supports(any(Class.class))).thenReturn(true);
when(provider.authenticate(any(Authentication.class))).thenThrow(e);
given(provider.supports(any(Class.class))).willReturn(true);
given(provider.authenticate(any(Authentication.class))).willThrow(e);
return provider;
}
private AuthenticationProvider createProviderWhichReturns(final Authentication a) {
AuthenticationProvider provider = mock(AuthenticationProvider.class);
when(provider.supports(any(Class.class))).thenReturn(true);
when(provider.authenticate(any(Authentication.class))).thenReturn(a);
given(provider.supports(any(Class.class))).willReturn(true);
given(provider.authenticate(any(Authentication.class))).willReturn(a);
return provider;
}

View File

@ -28,7 +28,7 @@ import org.springframework.security.core.Authentication;
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;
/**
* @author Rob Winch
@ -62,8 +62,8 @@ public class ReactiveAuthenticationManagerAdapterTests {
@Test
public void authenticateWhenSuccessThenSuccess() {
when(this.delegate.authenticate(any())).thenReturn(this.authentication);
when(this.authentication.isAuthenticated()).thenReturn(true);
given(this.delegate.authenticate(any())).willReturn(this.authentication);
given(this.authentication.isAuthenticated()).willReturn(true);
Authentication result = this.manager.authenticate(this.authentication).block();
@ -72,7 +72,7 @@ public class ReactiveAuthenticationManagerAdapterTests {
@Test
public void authenticateWhenReturnNotAuthenticatedThenError() {
when(this.delegate.authenticate(any())).thenReturn(this.authentication);
given(this.delegate.authenticate(any())).willReturn(this.authentication);
Authentication result = this.manager.authenticate(this.authentication).block();
@ -81,7 +81,7 @@ public class ReactiveAuthenticationManagerAdapterTests {
@Test
public void authenticateWhenBadCredentialsThenError() {
when(this.delegate.authenticate(any())).thenThrow(new BadCredentialsException("Failed"));
given(this.delegate.authenticate(any())).willThrow(new BadCredentialsException("Failed"));
Mono<Authentication> result = this.manager.authenticate(this.authentication);

View File

@ -33,7 +33,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
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;
/**
* @author Rob Winch
@ -69,7 +69,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Test
public void authenticateWhenUserNotFoundThenBadCredentials() {
when(this.repository.findByUsername(this.username)).thenReturn(Mono.empty());
given(this.repository.findByUsername(this.username)).willReturn(Mono.empty());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);
@ -86,7 +86,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
.roles("USER")
.build();
// @formatter:on
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password + "INVALID");
@ -103,7 +103,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
.roles("USER")
.build();
// @formatter:on
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);
@ -115,9 +115,9 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Test
public void authenticateWhenPasswordEncoderAndSuccessThenSuccess() {
this.manager.setPasswordEncoder(this.passwordEncoder);
when(this.passwordEncoder.matches(any(), any())).thenReturn(true);
given(this.passwordEncoder.matches(any(), any())).willReturn(true);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);
@ -129,9 +129,9 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Test
public void authenticateWhenPasswordEncoderAndFailThenFail() {
this.manager.setPasswordEncoder(this.passwordEncoder);
when(this.passwordEncoder.matches(any(), any())).thenReturn(false);
given(this.passwordEncoder.matches(any(), any())).willReturn(false);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);

View File

@ -38,10 +38,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@ -78,7 +78,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Before
public void setup() {
this.manager = new UserDetailsRepositoryReactiveAuthenticationManager(this.userDetailsService);
when(this.scheduler.schedule(any())).thenAnswer(a -> {
given(this.scheduler.schedule(any())).willAnswer(a -> {
Runnable r = a.getArgument(0);
return Schedulers.immediate().schedule(r);
});
@ -91,8 +91,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authentiateWhenCustomSchedulerThenUsed() {
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
when(this.encoder.matches(any(), any())).thenReturn(true);
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setScheduler(this.scheduler);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
@ -106,11 +106,11 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenPasswordServiceThenUpdated() {
String encodedPassword = "encoded";
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
when(this.encoder.matches(any(), any())).thenReturn(true);
when(this.encoder.upgradeEncoding(any())).thenReturn(true);
when(this.encoder.encode(any())).thenReturn(encodedPassword);
when(this.userDetailsPasswordService.updatePassword(any(), any())).thenReturn(Mono.just(this.user));
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
given(this.encoder.upgradeEncoding(any())).willReturn(true);
given(this.encoder.encode(any())).willReturn(encodedPassword);
given(this.userDetailsPasswordService.updatePassword(any(), any())).willReturn(Mono.just(this.user));
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
@ -124,8 +124,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenPasswordServiceAndBadCredentialsThenNotUpdated() {
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
when(this.encoder.matches(any(), any())).thenReturn(false);
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
@ -138,9 +138,9 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenPasswordServiceAndUpgradeFalseThenNotUpdated() {
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
when(this.encoder.matches(any(), any())).thenReturn(true);
when(this.encoder.upgradeEncoding(any())).thenReturn(false);
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
given(this.encoder.upgradeEncoding(any())).willReturn(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
@ -153,9 +153,9 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenPostAuthenticationChecksFail() {
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
doThrow(new LockedException("account is locked")).when(this.postAuthenticationChecks).check(any());
when(this.encoder.matches(any(), any())).thenReturn(true);
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
willThrow(new LockedException("account is locked")).given(this.postAuthenticationChecks).check(any());
given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setPostAuthenticationChecks(this.postAuthenticationChecks);
@ -168,8 +168,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenPostAuthenticationChecksNotSet() {
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
when(this.encoder.matches(any(), any())).thenReturn(true);
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
@ -190,7 +190,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.accountExpired(true)
.build();
// @formatter:on
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(expiredUser));
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(expiredUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(expiredUser,
expiredUser.getPassword());
@ -208,7 +208,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.accountLocked(true)
.build();
// @formatter:on
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(lockedUser));
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(lockedUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(lockedUser,
lockedUser.getPassword());
@ -227,7 +227,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.disabled(true)
.build();
// @formatter:on
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(disabledUser));
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(disabledUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(disabledUser,
disabledUser.getPassword());

View File

@ -55,11 +55,11 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
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.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link DaoAuthenticationProvider}.
@ -398,11 +398,11 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
when(encoder.matches(any(), any())).thenReturn(true);
when(encoder.upgradeEncoding(any())).thenReturn(true);
when(encoder.encode(any())).thenReturn(encodedPassword);
when(userDetailsService.loadUserByUsername(any())).thenReturn(user);
when(passwordManager.updatePassword(any(), any())).thenReturn(user);
given(encoder.matches(any(), any())).willReturn(true);
given(encoder.upgradeEncoding(any())).willReturn(true);
given(encoder.encode(any())).willReturn(encodedPassword);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
given(passwordManager.updatePassword(any(), any())).willReturn(user);
Authentication result = provider.authenticate(token);
@ -423,8 +423,8 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
when(encoder.matches(any(), any())).thenReturn(false);
when(userDetailsService.loadUserByUsername(any())).thenReturn(user);
given(encoder.matches(any(), any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
assertThatThrownBy(() -> provider.authenticate(token)).isInstanceOf(BadCredentialsException.class);
@ -444,9 +444,9 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
when(encoder.matches(any(), any())).thenReturn(true);
when(encoder.upgradeEncoding(any())).thenReturn(false);
when(userDetailsService.loadUserByUsername(any())).thenReturn(user);
given(encoder.matches(any(), any())).willReturn(true);
given(encoder.upgradeEncoding(any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
Authentication result = provider.authenticate(token);
@ -564,7 +564,7 @@ public class DaoAuthenticationProviderTests {
public void testUserNotFoundEncodesPassword() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", "koala");
PasswordEncoder encoder = mock(PasswordEncoder.class);
when(encoder.encode(anyString())).thenReturn("koala");
given(encoder.encode(anyString())).willReturn("koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false);
provider.setPasswordEncoder(encoder);

View File

@ -47,11 +47,11 @@ import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class DefaultJaasAuthenticationProviderTests {
@ -76,7 +76,7 @@ public class DefaultJaasAuthenticationProviderTests {
AppConfigurationEntry[] aces = new AppConfigurationEntry[] {
new AppConfigurationEntry(TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED,
Collections.<String, Object>emptyMap()) };
when(configuration.getAppConfigurationEntry(this.provider.getLoginContextName())).thenReturn(aces);
given(configuration.getAppConfigurationEntry(this.provider.getLoginContextName())).willReturn(aces);
this.token = new UsernamePasswordAuthenticationToken("user", "password");
ReflectionTestUtils.setField(this.provider, "log", this.log);
@ -141,9 +141,9 @@ public class DefaultJaasAuthenticationProviderTests {
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
when(securityContext.getAuthentication()).thenReturn(token);
when(token.getLoginContext()).thenReturn(context);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
this.provider.onApplicationEvent(event);
@ -170,7 +170,7 @@ public class DefaultJaasAuthenticationProviderTests {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
this.provider.handleLogout(event);
@ -185,8 +185,8 @@ public class DefaultJaasAuthenticationProviderTests {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
when(securityContext.getAuthentication()).thenReturn(this.token);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(this.token);
this.provider.handleLogout(event);
@ -202,8 +202,8 @@ public class DefaultJaasAuthenticationProviderTests {
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
when(securityContext.getAuthentication()).thenReturn(token);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
@ -221,10 +221,10 @@ public class DefaultJaasAuthenticationProviderTests {
LoginContext context = mock(LoginContext.class);
LoginException loginException = new LoginException("Failed Login");
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
when(securityContext.getAuthentication()).thenReturn(token);
when(token.getLoginContext()).thenReturn(context);
doThrow(loginException).when(context).logout();
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
willThrow(loginException).given(context).logout();
this.provider.onApplicationEvent(event);

View File

@ -47,8 +47,8 @@ import org.springframework.security.core.session.SessionDestroyedEvent;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for the JaasAuthenticationProvider
@ -258,7 +258,7 @@ public class JaasAuthenticationProviderTests {
context.setAuthentication(token);
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(context));
given(event.getSecurityContexts()).willReturn(Arrays.asList(context));
this.jaasProvider.handleLogout(event);

View File

@ -25,8 +25,8 @@ import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link RemoteAuthenticationManagerImpl}.
@ -39,7 +39,7 @@ public class RemoteAuthenticationManagerImplTests {
public void testFailedAuthenticationReturnsRemoteAuthenticationException() {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
manager.setAuthenticationManager(am);
manager.attemptAuthentication("rod", "password");
@ -65,7 +65,7 @@ public class RemoteAuthenticationManagerImplTests {
public void testSuccessfulAuthentication() {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenReturn(new TestingAuthenticationToken("u", "p", "A"));
given(am.authenticate(any(Authentication.class))).willReturn(new TestingAuthenticationToken("u", "p", "A"));
manager.setAuthenticationManager(am);
manager.attemptAuthentication("rod", "password");

View File

@ -27,8 +27,8 @@ import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
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.when;
/**
* @author Rob Winch
@ -45,7 +45,7 @@ public class AuthenticatedReactiveAuthorizationManagerTests {
@Test
public void checkWhenAuthenticatedThenReturnTrue() {
when(this.authentication.isAuthenticated()).thenReturn(true);
given(this.authentication.isAuthenticated()).willReturn(true);
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();

View File

@ -29,7 +29,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@ -66,8 +66,8 @@ public class AuthorityReactiveAuthorizationManagerTests {
@Test
public void checkWhenHasAuthorityAndAuthenticatedAndNoAuthoritiesThenReturnFalse() {
when(this.authentication.isAuthenticated()).thenReturn(true);
when(this.authentication.getAuthorities()).thenReturn(Collections.emptyList());
given(this.authentication.isAuthenticated()).willReturn(true);
given(this.authentication.getAuthorities()).willReturn(Collections.emptyList());
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();

View File

@ -26,8 +26,8 @@ import org.junit.Test;
import org.mockito.Mock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Abstract class for testing {@link DelegatingSecurityContextExecutorService} which
@ -97,7 +97,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
@Test
public void submitCallable() {
when(this.delegate.submit(this.wrappedCallable)).thenReturn(this.expectedFutureObject);
given(this.delegate.submit(this.wrappedCallable)).willReturn(this.expectedFutureObject);
Future<Object> result = this.executor.submit(this.callable);
verify(this.delegate).submit(this.wrappedCallable);
assertThat(result).isEqualTo(this.expectedFutureObject);
@ -105,7 +105,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
@Test
public void submitRunnableWithResult() {
when(this.delegate.submit(this.wrappedRunnable, this.resultArg)).thenReturn(this.expectedFutureObject);
given(this.delegate.submit(this.wrappedRunnable, this.resultArg)).willReturn(this.expectedFutureObject);
Future<Object> result = this.executor.submit(this.runnable, this.resultArg);
verify(this.delegate).submit(this.wrappedRunnable, this.resultArg);
assertThat(result).isEqualTo(this.expectedFutureObject);
@ -114,7 +114,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
@Test
@SuppressWarnings("unchecked")
public void submitRunnable() {
when((Future<Object>) this.delegate.submit(this.wrappedRunnable)).thenReturn(this.expectedFutureObject);
given((Future<Object>) this.delegate.submit(this.wrappedRunnable)).willReturn(this.expectedFutureObject);
Future<?> result = this.executor.submit(this.runnable);
verify(this.delegate).submit(this.wrappedRunnable);
assertThat(result).isEqualTo(this.expectedFutureObject);
@ -125,7 +125,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
public void invokeAll() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAll(wrappedCallables)).thenReturn(exectedResult);
given(this.delegate.invokeAll(wrappedCallables)).willReturn(exectedResult);
List<Future<Object>> result = this.executor.invokeAll(Arrays.asList(this.callable));
verify(this.delegate).invokeAll(wrappedCallables);
assertThat(result).isEqualTo(exectedResult);
@ -136,7 +136,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
public void invokeAllTimeout() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAll(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
given(this.delegate.invokeAll(wrappedCallables, 1, TimeUnit.SECONDS)).willReturn(exectedResult);
List<Future<Object>> result = this.executor.invokeAll(Arrays.asList(this.callable), 1, TimeUnit.SECONDS);
verify(this.delegate).invokeAll(wrappedCallables, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(exectedResult);
@ -147,7 +147,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
public void invokeAny() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAny(wrappedCallables)).thenReturn(exectedResult);
given(this.delegate.invokeAny(wrappedCallables)).willReturn(exectedResult);
Object result = this.executor.invokeAny(Arrays.asList(this.callable));
verify(this.delegate).invokeAny(wrappedCallables);
assertThat(result).isEqualTo(exectedResult);
@ -158,7 +158,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
public void invokeAnyTimeout() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAny(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
given(this.delegate.invokeAny(wrappedCallables, 1, TimeUnit.SECONDS)).willReturn(exectedResult);
Object result = this.executor.invokeAny(Arrays.asList(this.callable), 1, TimeUnit.SECONDS);
verify(this.delegate).invokeAny(wrappedCallables, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(exectedResult);

View File

@ -23,8 +23,8 @@ import org.junit.Test;
import org.mockito.Mock;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Abstract class for testing {@link DelegatingSecurityContextScheduledExecutorService}
@ -52,8 +52,8 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
@SuppressWarnings("unchecked")
public void scheduleRunnable() {
when((ScheduledFuture<Object>) this.delegate.schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS))
.thenReturn(this.expectedResult);
given((ScheduledFuture<Object>) this.delegate.schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS))
.willReturn(this.expectedResult);
ScheduledFuture<?> result = this.executor.schedule(this.runnable, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS);
@ -61,7 +61,7 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
public void scheduleCallable() {
when(this.delegate.schedule(this.wrappedCallable, 1, TimeUnit.SECONDS)).thenReturn(this.expectedResult);
given(this.delegate.schedule(this.wrappedCallable, 1, TimeUnit.SECONDS)).willReturn(this.expectedResult);
ScheduledFuture<Object> result = this.executor.schedule(this.callable, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).schedule(this.wrappedCallable, 1, TimeUnit.SECONDS);
@ -70,8 +70,8 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
@SuppressWarnings("unchecked")
public void scheduleAtFixedRate() {
when((ScheduledFuture<Object>) this.delegate.scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS))
.thenReturn(this.expectedResult);
given((ScheduledFuture<Object>) this.delegate.scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS))
.willReturn(this.expectedResult);
ScheduledFuture<?> result = this.executor.scheduleAtFixedRate(this.runnable, 1, 2, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS);
@ -80,8 +80,8 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
@SuppressWarnings("unchecked")
public void scheduleWithFixedDelay() {
when((ScheduledFuture<Object>) this.delegate.scheduleWithFixedDelay(this.wrappedRunnable, 1, 2,
TimeUnit.SECONDS)).thenReturn(this.expectedResult);
given((ScheduledFuture<Object>) this.delegate.scheduleWithFixedDelay(this.wrappedRunnable, 1, 2,
TimeUnit.SECONDS)).willReturn(this.expectedResult);
ScheduledFuture<?> result = this.executor.scheduleWithFixedDelay(this.runnable, 1, 2, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).scheduleWithFixedDelay(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS);

View File

@ -33,8 +33,8 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@ -62,7 +62,7 @@ public class DelegatingSecurityContextCallableTests {
@SuppressWarnings("serial")
public void setUp() throws Exception {
this.originalSecurityContext = SecurityContextHolder.createEmptyContext();
when(this.delegate.call()).thenAnswer(new Returns(this.callableResult) {
given(this.delegate.call()).willAnswer(new Returns(this.callableResult) {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
assertThat(SecurityContextHolder.getContext())

View File

@ -33,7 +33,7 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.verify;
/**
@ -61,10 +61,10 @@ public class DelegatingSecurityContextRunnableTests {
@Before
public void setUp() {
this.originalSecurityContext = SecurityContextHolder.createEmptyContext();
doAnswer((Answer<Object>) invocation -> {
willAnswer((Answer<Object>) invocation -> {
assertThat(SecurityContextHolder.getContext()).isEqualTo(this.securityContext);
return null;
}).when(this.delegate).run();
}).given(this.delegate).run();
this.executor = Executors.newFixedThreadPool(1);
}

View File

@ -25,9 +25,9 @@ import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DelegatingApplicationListenerTests {
@ -56,8 +56,8 @@ public class DelegatingApplicationListenerTests {
@Test
public void processEventSuccess() {
when(this.delegate.supportsEventType(this.event.getClass())).thenReturn(true);
when(this.delegate.supportsSourceType(this.event.getSource().getClass())).thenReturn(true);
given(this.delegate.supportsEventType(this.event.getClass())).willReturn(true);
given(this.delegate.supportsSourceType(this.event.getSource().getClass())).willReturn(true);
this.listener.onApplicationEvent(this.event);
verify(this.delegate).onApplicationEvent(this.event);
@ -72,7 +72,7 @@ public class DelegatingApplicationListenerTests {
@Test
public void processEventSourceTypeNotSupported() {
when(this.delegate.supportsEventType(this.event.getClass())).thenReturn(true);
given(this.delegate.supportsEventType(this.event.getClass())).willReturn(true);
this.listener.onApplicationEvent(this.event);
verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class));

View File

@ -45,8 +45,8 @@ import org.springframework.security.core.userdetails.UserDetails;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for {@link JdbcUserDetailsManager}
@ -225,7 +225,7 @@ public class JdbcUserDetailsManagerTests {
insertJoe();
Authentication currentAuth = authenticateJoe();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(currentAuth)).thenReturn(currentAuth);
given(am.authenticate(currentAuth)).willReturn(currentAuth);
this.manager.setAuthenticationManager(am);
this.manager.changePassword("password", "newPassword");
@ -245,7 +245,7 @@ public class JdbcUserDetailsManagerTests {
insertJoe();
authenticateJoe();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
this.manager.setAuthenticationManager(am);

View File

@ -26,8 +26,8 @@ import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.keygen.BytesKeyGenerator;
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.when;
import static org.springframework.security.crypto.encrypt.AesBytesEncryptor.CipherAlgorithm.GCM;
import static org.springframework.security.crypto.encrypt.CipherUtils.newSecretKey;
import static org.springframework.security.crypto.password.Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA1;
@ -48,8 +48,8 @@ public class AesBytesEncryptorTests {
@Before
public void setUp() {
this.generator = mock(BytesKeyGenerator.class);
when(this.generator.generateKey()).thenReturn(Hex.decode("4b0febebd439db7ca77153cb254520c3"));
when(this.generator.getKeyLength()).thenReturn(16);
given(this.generator.generateKey()).willReturn(Hex.decode("4b0febebd439db7ca77153cb254520c3"));
given(this.generator.getKeyLength()).willReturn(16);
}
@Test

View File

@ -29,9 +29,9 @@ import org.mockito.junit.MockitoJUnitRunner;
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.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@ -101,14 +101,14 @@ public class DelegatingPasswordEncoderTests {
@Test
public void encodeWhenValidThenUsesIdForEncode() {
when(this.bcrypt.encode(this.rawPassword)).thenReturn(this.encodedPassword);
given(this.bcrypt.encode(this.rawPassword)).willReturn(this.encodedPassword);
assertThat(this.passwordEncoder.encode(this.rawPassword)).isEqualTo(this.bcryptEncodedPassword);
}
@Test
public void matchesWhenBCryptThenDelegatesToBCrypt() {
when(this.bcrypt.matches(this.rawPassword, this.encodedPassword)).thenReturn(true);
given(this.bcrypt.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
assertThat(this.passwordEncoder.matches(this.rawPassword, this.bcryptEncodedPassword)).isTrue();
@ -118,7 +118,7 @@ public class DelegatingPasswordEncoderTests {
@Test
public void matchesWhenNoopThenDelegatesToNoop() {
when(this.noop.matches(this.rawPassword, this.encodedPassword)).thenReturn(true);
given(this.noop.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
assertThat(this.passwordEncoder.matches(this.rawPassword, this.noopEncodedPassword)).isTrue();
@ -188,7 +188,7 @@ public class DelegatingPasswordEncoderTests {
public void matchesWhenNullIdThenDelegatesToInvalidId() {
this.delegates.put(null, this.invalidId);
this.passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates);
when(this.invalidId.matches(this.rawPassword, this.encodedPassword)).thenReturn(true);
given(this.invalidId.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
assertThat(this.passwordEncoder.matches(this.rawPassword, this.encodedPassword)).isTrue();
@ -225,7 +225,7 @@ public class DelegatingPasswordEncoderTests {
@Test
public void upgradeEncodingWhenSameIdAndEncoderTrueThenEncoderDecidesTrue() {
when(this.bcrypt.upgradeEncoding(any())).thenReturn(true);
given(this.bcrypt.upgradeEncoding(any())).willReturn(true);
assertThat(this.passwordEncoder.upgradeEncoding(this.bcryptEncodedPassword)).isTrue();

View File

@ -3,7 +3,6 @@
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<suppress files=".*" checks="RegexpSinglelineJava" />
<suppress files=".*" checks="SimplifyBooleanExpression" />
<suppress files=".*" checks="SimplifyBooleanReturn" />
<suppress files=".*" checks="SpringAvoidStaticImport" />

View File

@ -22,9 +22,9 @@ import javax.naming.directory.DirContext;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link LdapUtils}
@ -36,7 +36,7 @@ public class LdapUtilsTests {
@Test
public void testCloseContextSwallowsNamingException() throws Exception {
final DirContext dirCtx = mock(DirContext.class);
doThrow(new NamingException()).when(dirCtx).close();
willThrow(new NamingException()).given(dirCtx).close();
LdapUtils.closeContext(dirCtx);
}
@ -45,7 +45,7 @@ public class LdapUtilsTests {
public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception {
final DirContext mockCtx = mock(DirContext.class);
when(mockCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
given(mockCtx.getNameInNamespace()).willReturn("dc=springframework,dc=org");
assertThat(LdapUtils.getRelativeName("dc=springframework,dc=org", mockCtx)).isEqualTo("");
}
@ -53,7 +53,7 @@ public class LdapUtilsTests {
@Test
public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception {
final DirContext mockCtx = mock(DirContext.class);
when(mockCtx.getNameInNamespace()).thenReturn("");
given(mockCtx.getNameInNamespace()).willReturn("");
assertThat(LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx))
.isEqualTo("cn=jane,dc=springframework,dc=org");
@ -62,7 +62,7 @@ public class LdapUtilsTests {
@Test
public void testGetRelativeNameWorksWithArbitrarySpaces() throws Exception {
final DirContext mockCtx = mock(DirContext.class);
when(mockCtx.getNameInNamespace()).thenReturn("dc=springsecurity,dc = org");
given(mockCtx.getNameInNamespace()).willReturn("dc=springsecurity,dc = org");
assertThat(LdapUtils.getRelativeName("cn=jane smith, dc = springsecurity , dc=org", mockCtx))
.isEqualTo("cn=jane smith");

View File

@ -33,8 +33,8 @@ import org.springframework.ldap.core.DistinguishedName;
import static org.assertj.core.api.Assertions.assertThat;
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.when;
@RunWith(MockitoJUnitRunner.class)
public class SpringSecurityLdapTemplateTests {
@ -60,11 +60,11 @@ public class SpringSecurityLdapTemplateTests {
Object[] params = new Object[] {};
DirContextAdapter searchResultObject = mock(DirContextAdapter.class);
when(this.ctx.search(any(DistinguishedName.class), eq(filter), eq(params), this.searchControls.capture()))
.thenReturn(this.resultsEnum);
when(this.resultsEnum.hasMore()).thenReturn(true, false);
when(this.resultsEnum.next()).thenReturn(this.searchResult);
when(this.searchResult.getObject()).thenReturn(searchResultObject);
given(this.ctx.search(any(DistinguishedName.class), eq(filter), eq(params), this.searchControls.capture()))
.willReturn(this.resultsEnum);
given(this.resultsEnum.hasMore()).willReturn(true, false);
given(this.resultsEnum.next()).willReturn(this.searchResult);
given(this.searchResult.getObject()).willReturn(searchResultObject);
SpringSecurityLdapTemplate.searchForSingleEntryInternal(this.ctx, mock(SearchControls.class), base, filter,
params);

View File

@ -37,8 +37,8 @@ import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link LdapAuthenticationProvider}.
@ -89,7 +89,7 @@ public class LdapAuthenticationProviderTests {
public void usernameNotFoundExceptionIsHiddenByDefault() {
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
when(authenticator.authenticate(joe)).thenThrow(new UsernameNotFoundException("nobody"));
given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
provider.authenticate(joe);
@ -99,7 +99,7 @@ public class LdapAuthenticationProviderTests {
public void usernameNotFoundExceptionIsNotHiddenIfConfigured() {
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
when(authenticator.authenticate(joe)).thenThrow(new UsernameNotFoundException("nobody"));
given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
provider.setHideUserNotFoundExceptions(false);
@ -165,7 +165,7 @@ public class LdapAuthenticationProviderTests {
"benspassword");
LdapAuthenticator mockAuthenticator = mock(LdapAuthenticator.class);
CommunicationException expectedCause = new CommunicationException(new javax.naming.CommunicationException());
when(mockAuthenticator.authenticate(authRequest)).thenThrow(expectedCause);
given(mockAuthenticator.authenticate(authRequest)).willThrow(expectedCause);
LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(mockAuthenticator);
try {

View File

@ -29,8 +29,8 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
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.when;
/**
* @author Luke Taylor
@ -49,15 +49,15 @@ public class PasswordComparisonAuthenticatorMockTests {
authenticator.setUserDnPatterns(new String[] { "cn={0},ou=people" });
// Get the mock to return an empty attribute set
when(source.getReadOnlyContext()).thenReturn(dirCtx);
when(dirCtx.getAttributes(eq("cn=Bob,ou=people"), any(String[].class))).thenReturn(attrs);
when(dirCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
given(source.getReadOnlyContext()).willReturn(dirCtx);
given(dirCtx.getAttributes(eq("cn=Bob,ou=people"), any(String[].class))).willReturn(attrs);
given(dirCtx.getNameInNamespace()).willReturn("dc=springframework,dc=org");
// Setup a single return value (i.e. success)
final NamingEnumeration searchResults = new BasicAttributes("", null).getAll();
when(dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class),
any(SearchControls.class))).thenReturn(searchResults);
given(dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class),
any(SearchControls.class))).willReturn(searchResults);
authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob", "bobspassword"));
}

View File

@ -56,9 +56,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
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.verify;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@ -100,12 +100,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
String customSearchFilter = "(&(objectClass=user)(sAMAccountName={0}))";
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
DirContextAdapter dca = new DirContextAdapter();
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
when(ctx.search(any(Name.class), eq(customSearchFilter), any(Object[].class), any(SearchControls.class)))
.thenReturn(new MockNamingEnumeration(sr));
given(ctx.search(any(Name.class), eq(customSearchFilter), any(Object[].class), any(SearchControls.class)))
.willReturn(new MockNamingEnumeration(sr));
ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider(
"mydomain.eu", "ldap://192.168.1.200/");
@ -125,12 +125,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
final String defaultSearchFilter = "(&(objectClass=user)(userPrincipalName={0}))";
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
DirContextAdapter dca = new DirContextAdapter();
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
when(ctx.search(any(Name.class), eq(defaultSearchFilter), any(Object[].class), any(SearchControls.class)))
.thenReturn(new MockNamingEnumeration(sr));
given(ctx.search(any(Name.class), eq(defaultSearchFilter), any(Object[].class), any(SearchControls.class)))
.willReturn(new MockNamingEnumeration(sr));
ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider(
"mydomain.eu", "ldap://192.168.1.200/");
@ -153,12 +153,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
ArgumentCaptor<Object[]> captor = ArgumentCaptor.forClass(Object[].class);
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
DirContextAdapter dca = new DirContextAdapter();
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
when(ctx.search(any(Name.class), eq(defaultSearchFilter), captor.capture(), any(SearchControls.class)))
.thenReturn(new MockNamingEnumeration(sr));
given(ctx.search(any(Name.class), eq(defaultSearchFilter), captor.capture(), any(SearchControls.class)))
.willReturn(new MockNamingEnumeration(sr));
ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider(
"mydomain.eu", "ldap://192.168.1.200/");
@ -186,12 +186,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
public void nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal() throws Exception {
this.provider = new ActiveDirectoryLdapAuthenticationProvider(null, "ldap://192.168.1.200/");
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
DirContextAdapter dca = new DirContextAdapter();
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
when(ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class),
any(SearchControls.class))).thenReturn(new MockNamingEnumeration(sr));
given(ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class),
any(SearchControls.class))).willReturn(new MockNamingEnumeration(sr));
this.provider.contextFactory = createContextFactoryReturning(ctx);
try {
@ -207,9 +207,9 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Test(expected = BadCredentialsException.class)
public void failedUserSearchCausesBadCredentials() throws Exception {
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenThrow(new NameNotFoundException());
given(ctx.getNameInNamespace()).willReturn("");
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.willThrow(new NameNotFoundException());
this.provider.contextFactory = createContextFactoryReturning(ctx);
@ -220,9 +220,9 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Test(expected = BadCredentialsException.class)
public void noUserSearchCausesUsernameNotFound() throws Exception {
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenReturn(new EmptyEnumeration<>());
given(ctx.getNameInNamespace()).willReturn("");
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.willReturn(new EmptyEnumeration<>());
this.provider.contextFactory = createContextFactoryReturning(ctx);
@ -239,14 +239,14 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Test(expected = IncorrectResultSizeDataAccessException.class)
public void duplicateUserSearchCausesError() throws Exception {
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
NamingEnumeration<SearchResult> searchResults = mock(NamingEnumeration.class);
when(searchResults.hasMore()).thenReturn(true, true, false);
given(searchResults.hasMore()).willReturn(true, true, false);
SearchResult searchResult = mock(SearchResult.class);
when(searchResult.getObject()).thenReturn(new DirContextAdapter("ou=1"), new DirContextAdapter("ou=2"));
when(searchResults.next()).thenReturn(searchResult);
when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenReturn(searchResults);
given(searchResult.getObject()).willReturn(new DirContextAdapter("ou=1"), new DirContextAdapter("ou=2"));
given(searchResults.next()).willReturn(searchResult);
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.willReturn(searchResults);
this.provider.contextFactory = createContextFactoryReturning(ctx);
@ -440,14 +440,14 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
private void checkAuthentication(String rootDn, ActiveDirectoryLdapAuthenticationProvider provider)
throws NamingException {
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
DirContextAdapter dca = new DirContextAdapter();
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
@SuppressWarnings("deprecation")
DistinguishedName searchBaseDn = new DistinguishedName(rootDn);
when(ctx.search(eq(searchBaseDn), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenReturn(new MockNamingEnumeration(sr)).thenReturn(new MockNamingEnumeration(sr));
given(ctx.search(eq(searchBaseDn), any(String.class), any(Object[].class), any(SearchControls.class)))
.willReturn(new MockNamingEnumeration(sr)).willReturn(new MockNamingEnumeration(sr));
provider.contextFactory = createContextFactoryReturning(ctx);

View File

@ -30,10 +30,10 @@ import org.springframework.ldap.UncategorizedLdapException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@ -69,17 +69,17 @@ public class PasswordPolicyAwareContextSourceTests {
@Test(expected = UncategorizedLdapException.class)
public void standardExceptionIsPropagatedWhenExceptionRaisedAndNoControlsAreSet() throws Exception {
doThrow(new NamingException("some LDAP exception")).when(this.ctx).reconnect(any(Control[].class));
willThrow(new NamingException("some LDAP exception")).given(this.ctx).reconnect(any(Control[].class));
this.ctxSource.getContext("user", "ignored");
}
@Test(expected = PasswordPolicyException.class)
public void lockedPasswordPolicyControlRaisesPasswordPolicyException() throws Exception {
when(this.ctx.getResponseControls()).thenReturn(new Control[] {
given(this.ctx.getResponseControls()).willReturn(new Control[] {
new PasswordPolicyResponseControl(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL) });
doThrow(new NamingException("locked message")).when(this.ctx).reconnect(any(Control[].class));
willThrow(new NamingException("locked message")).given(this.ctx).reconnect(any(Control[].class));
this.ctxSource.getContext("user", "ignored");
}

View File

@ -20,8 +20,8 @@ import javax.naming.ldap.Control;
import org.junit.Test;
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.when;
/**
* @author Luke Taylor
@ -33,7 +33,7 @@ public class PasswordPolicyControlFactoryTests {
PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory();
Control wrongCtrl = mock(Control.class);
when(wrongCtrl.getID()).thenReturn("wrongId");
given(wrongCtrl.getID()).willReturn("wrongId");
assertThat(ctrlFactory.getControlInstance(wrongCtrl)).isNull();
}
@ -42,8 +42,8 @@ public class PasswordPolicyControlFactoryTests {
PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory();
Control control = mock(Control.class);
when(control.getID()).thenReturn(PasswordPolicyControl.OID);
when(control.getEncodedValue()).thenReturn(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL);
given(control.getID()).willReturn(PasswordPolicyControl.OID);
given(control.getEncodedValue()).willReturn(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL);
Control result = ctrlFactory.getControlInstance(control);
assertThat(result).isNotNull();
assertThat(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL).isEqualTo(result.getEncodedValue());

View File

@ -28,8 +28,8 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.ldap.authentication.UserDetailsServiceLdapAuthoritiesPopulator;
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.when;
/**
* @author Luke Taylor
@ -40,9 +40,9 @@ public class UserDetailsServiceLdapAuthoritiesPopulatorTests {
public void delegationToUserDetailsServiceReturnsCorrectRoles() {
UserDetailsService uds = mock(UserDetailsService.class);
UserDetails user = mock(UserDetails.class);
when(uds.loadUserByUsername("joe")).thenReturn(user);
given(uds.loadUserByUsername("joe")).willReturn(user);
List authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
when(user.getAuthorities()).thenReturn(authorities);
given(user.getAuthorities()).willReturn(authorities);
UserDetailsServiceLdapAuthoritiesPopulator populator = new UserDetailsServiceLdapAuthoritiesPopulator(uds);
Collection<? extends GrantedAuthority> auths = populator.getGrantedAuthorities(new DirContextAdapter(), "joe");

View File

@ -35,7 +35,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
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 DefaultMessageSecurityExpressionHandlerTests {
@ -80,7 +80,7 @@ public class DefaultMessageSecurityExpressionHandlerTests {
this.handler.setTrustResolver(this.trustResolver);
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.message);
Expression expression = this.handler.getExpressionParser().parseExpression("authenticated");
when(this.trustResolver.isAnonymous(this.authentication)).thenReturn(false);
given(this.trustResolver.isAnonymous(this.authentication)).willReturn(false);
assertThat(ExpressionUtils.evaluateAsBoolean(expression, context)).isTrue();
}
@ -102,7 +102,7 @@ public class DefaultMessageSecurityExpressionHandlerTests {
this.handler.setPermissionEvaluator(this.permissionEvaluator);
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.message);
Expression expression = this.handler.getExpressionParser().parseExpression("hasPermission(message, 'read')");
when(this.permissionEvaluator.hasPermission(this.authentication, this.message, "read")).thenReturn(true);
given(this.permissionEvaluator.hasPermission(this.authentication, this.message, "read")).willReturn(true);
assertThat(ExpressionUtils.evaluateAsBoolean(expression, context)).isTrue();
}

View File

@ -30,9 +30,9 @@ import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.security.messaging.util.matcher.SimpDestinationMessageMatcher;
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;
@RunWith(MockitoJUnitRunner.class)
public class MessageExpressionConfigAttributeTests {
@ -72,7 +72,7 @@ public class MessageExpressionConfigAttributeTests {
@Test
public void toStringUsesExpressionString() {
when(this.expression.getExpressionString()).thenReturn("toString");
given(this.expression.getExpressionString()).willReturn("toString");
assertThat(this.attribute.toString()).isEqualTo(this.expression.getExpressionString());
}

View File

@ -36,9 +36,9 @@ import org.springframework.security.messaging.util.matcher.MessageMatcher;
import static org.assertj.core.api.Assertions.assertThat;
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.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.access.AccessDecisionVoter.ACCESS_ABSTAIN;
import static org.springframework.security.access.AccessDecisionVoter.ACCESS_DENIED;
import static org.springframework.security.access.AccessDecisionVoter.ACCESS_GRANTED;
@ -78,13 +78,13 @@ public class MessageExpressionVoterTests {
@Test
public void voteGranted() {
when(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).thenReturn(true);
given(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).willReturn(true);
assertThat(this.voter.vote(this.authentication, this.message, this.attributes)).isEqualTo(ACCESS_GRANTED);
}
@Test
public void voteDenied() {
when(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).thenReturn(false);
given(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).willReturn(false);
assertThat(this.voter.vote(this.authentication, this.message, this.attributes)).isEqualTo(ACCESS_DENIED);
}
@ -122,9 +122,9 @@ public class MessageExpressionVoterTests {
@Test
public void customExpressionHandler() {
this.voter.setExpressionHandler(this.expressionHandler);
when(this.expressionHandler.createEvaluationContext(this.authentication, this.message))
.thenReturn(this.evaluationContext);
when(this.expression.getValue(this.evaluationContext, Boolean.class)).thenReturn(true);
given(this.expressionHandler.createEvaluationContext(this.authentication, this.message))
.willReturn(this.evaluationContext);
given(this.expression.getValue(this.evaluationContext, Boolean.class)).willReturn(true);
assertThat(this.voter.vote(this.authentication, this.message, this.attributes)).isEqualTo(ACCESS_GRANTED);
@ -135,12 +135,12 @@ public class MessageExpressionVoterTests {
public void postProcessEvaluationContext() {
final MessageExpressionConfigAttribute configAttribute = mock(MessageExpressionConfigAttribute.class);
this.voter.setExpressionHandler(this.expressionHandler);
when(this.expressionHandler.createEvaluationContext(this.authentication, this.message))
.thenReturn(this.evaluationContext);
when(configAttribute.getAuthorizeExpression()).thenReturn(this.expression);
given(this.expressionHandler.createEvaluationContext(this.authentication, this.message))
.willReturn(this.evaluationContext);
given(configAttribute.getAuthorizeExpression()).willReturn(this.expression);
this.attributes = Arrays.<ConfigAttribute>asList(configAttribute);
when(configAttribute.postProcess(this.evaluationContext, this.message)).thenReturn(this.evaluationContext);
when(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).thenReturn(true);
given(configAttribute.postProcess(this.evaluationContext, this.message)).willReturn(this.evaluationContext);
given(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).willReturn(true);
assertThat(this.voter.vote(this.authentication, this.message, this.attributes)).isEqualTo(ACCESS_GRANTED);
verify(configAttribute).postProcess(this.evaluationContext, this.message);

View File

@ -40,8 +40,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
@RunWith(MockitoJUnitRunner.class)
public class ChannelSecurityInterceptorTests {
@ -108,7 +108,7 @@ public class ChannelSecurityInterceptorTests {
@Test
public void preSendGrant() {
when(this.source.getAttributes(this.message)).thenReturn(this.attrs);
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
Message<?> result = this.interceptor.preSend(this.message, this.channel);
@ -117,8 +117,8 @@ public class ChannelSecurityInterceptorTests {
@Test(expected = AccessDeniedException.class)
public void preSendDeny() {
when(this.source.getAttributes(this.message)).thenReturn(this.attrs);
doThrow(new AccessDeniedException("")).when(this.accessDecisionManager).decide(any(Authentication.class),
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
willThrow(new AccessDeniedException("")).given(this.accessDecisionManager).decide(any(Authentication.class),
eq(this.message), eq(this.attrs));
this.interceptor.preSend(this.message, this.channel);
@ -127,9 +127,9 @@ public class ChannelSecurityInterceptorTests {
@SuppressWarnings("unchecked")
@Test
public void preSendPostSendRunAs() {
when(this.source.getAttributes(this.message)).thenReturn(this.attrs);
when(this.runAsManager.buildRunAs(any(Authentication.class), any(), any(Collection.class)))
.thenReturn(this.runAs);
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
given(this.runAsManager.buildRunAs(any(Authentication.class), any(), any(Collection.class)))
.willReturn(this.runAs);
Message<?> preSend = this.interceptor.preSend(this.message, this.channel);
@ -148,9 +148,9 @@ public class ChannelSecurityInterceptorTests {
@SuppressWarnings("unchecked")
@Test
public void preSendFinallySendRunAs() {
when(this.source.getAttributes(this.message)).thenReturn(this.attrs);
when(this.runAsManager.buildRunAs(any(Authentication.class), any(), any(Collection.class)))
.thenReturn(this.runAs);
given(this.source.getAttributes(this.message)).willReturn(this.attrs);
given(this.runAsManager.buildRunAs(any(Authentication.class), any(), any(Collection.class)))
.willReturn(this.runAs);
Message<?> preSend = this.interceptor.preSend(this.message, this.channel);

View File

@ -27,7 +27,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.messaging.Message;
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 AndMessageMatcherTests {
@ -76,7 +76,7 @@ public class AndMessageMatcherTests {
@Test
public void matchesSingleTrue() {
when(this.delegate.matches(this.message)).thenReturn(true);
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new AndMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isTrue();
@ -84,8 +84,8 @@ public class AndMessageMatcherTests {
@Test
public void matchesMultiTrue() {
when(this.delegate.matches(this.message)).thenReturn(true);
when(this.delegate2.matches(this.message)).thenReturn(true);
given(this.delegate.matches(this.message)).willReturn(true);
given(this.delegate2.matches(this.message)).willReturn(true);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
@ -93,7 +93,7 @@ public class AndMessageMatcherTests {
@Test
public void matchesSingleFalse() {
when(this.delegate.matches(this.message)).thenReturn(false);
given(this.delegate.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isFalse();
@ -101,7 +101,7 @@ public class AndMessageMatcherTests {
@Test
public void matchesMultiBothFalse() {
when(this.delegate.matches(this.message)).thenReturn(false);
given(this.delegate.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
@ -109,8 +109,8 @@ public class AndMessageMatcherTests {
@Test
public void matchesMultiSingleFalse() {
when(this.delegate.matches(this.message)).thenReturn(true);
when(this.delegate2.matches(this.message)).thenReturn(false);
given(this.delegate.matches(this.message)).willReturn(true);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();

View File

@ -27,7 +27,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.messaging.Message;
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 OrMessageMatcherTests {
@ -76,7 +76,7 @@ public class OrMessageMatcherTests {
@Test
public void matchesSingleTrue() {
when(this.delegate.matches(this.message)).thenReturn(true);
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isTrue();
@ -84,7 +84,7 @@ public class OrMessageMatcherTests {
@Test
public void matchesMultiTrue() {
when(this.delegate.matches(this.message)).thenReturn(true);
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
@ -92,7 +92,7 @@ public class OrMessageMatcherTests {
@Test
public void matchesSingleFalse() {
when(this.delegate.matches(this.message)).thenReturn(false);
given(this.delegate.matches(this.message)).willReturn(false);
this.matcher = new OrMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isFalse();
@ -100,8 +100,8 @@ public class OrMessageMatcherTests {
@Test
public void matchesMultiBothFalse() {
when(this.delegate.matches(this.message)).thenReturn(false);
when(this.delegate2.matches(this.message)).thenReturn(false);
given(this.delegate.matches(this.message)).willReturn(false);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
@ -109,7 +109,7 @@ public class OrMessageMatcherTests {
@Test
public void matchesMultiSingleFalse() {
when(this.delegate.matches(this.message)).thenReturn(true);
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();

View File

@ -38,12 +38,12 @@ import static org.assertj.core.api.Assertions.assertThatCode;
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.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* Tests for {@link AuthorizedClientServiceOAuth2AuthorizedClientManager}.
@ -163,8 +163,8 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndUnsupportedProviderThenNotAuthorized() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(this.clientRegistration);
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(this.clientRegistration);
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -187,11 +187,11 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(this.clientRegistration);
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(this.clientRegistration);
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(this.authorizedClient);
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(this.authorizedClient);
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -215,16 +215,16 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(this.clientRegistration);
when(this.authorizedClientService.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal.getName()))).thenReturn(this.authorizedClient);
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(this.clientRegistration);
given(this.authorizedClientService.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal.getName()))).willReturn(this.authorizedClient);
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(reauthorizedClient);
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(reauthorizedClient);
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -271,8 +271,8 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(reauthorizedClient);
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(reauthorizedClient);
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
@ -298,8 +298,8 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(reauthorizedClient);
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(reauthorizedClient);
// Override the mock with the default
this.authorizedClientManager.setContextAttributesMapper(
@ -333,8 +333,8 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null),
this.clientRegistration.getRegistrationId());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenThrow(authorizationException);
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willThrow(authorizationException);
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
@ -353,8 +353,8 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
ClientAuthorizationException authorizationException = new ClientAuthorizationException(
new OAuth2Error("non-matching-error-code", null, null), this.clientRegistration.getRegistrationId());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenThrow(authorizationException);
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willThrow(authorizationException);
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();

View File

@ -42,10 +42,10 @@ import static org.assertj.core.api.Assertions.assertThatCode;
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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager}.
@ -83,14 +83,14 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
this.clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
this.authorizedClientService = mock(ReactiveOAuth2AuthorizedClientService.class);
this.saveAuthorizedClientProbe = PublisherProbe.empty();
when(this.authorizedClientService.saveAuthorizedClient(any(), any()))
.thenReturn(this.saveAuthorizedClientProbe.mono());
given(this.authorizedClientService.saveAuthorizedClient(any(), any()))
.willReturn(this.saveAuthorizedClientProbe.mono());
this.removeAuthorizedClientProbe = PublisherProbe.empty();
when(this.authorizedClientService.removeAuthorizedClient(any(), any()))
.thenReturn(this.removeAuthorizedClientProbe.mono());
given(this.authorizedClientService.removeAuthorizedClient(any(), any()))
.willReturn(this.removeAuthorizedClientProbe.mono());
this.authorizedClientProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
this.contextAttributesMapper = mock(Function.class);
when(this.contextAttributesMapper.apply(any())).thenReturn(Mono.empty());
given(this.contextAttributesMapper.apply(any())).willReturn(Mono.empty());
this.authorizedClientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientService);
this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider);
@ -151,7 +151,7 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
String clientRegistrationId = "invalid-registration-id";
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId)
.principal(this.principal).build();
when(this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).thenReturn(Mono.empty());
given(this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(Mono.empty());
StepVerifier.create(this.authorizedClientManager.authorize(authorizeRequest))
.verifyError(IllegalArgumentException.class);
@ -160,11 +160,11 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndUnsupportedProviderThenNotAuthorized() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(Mono.just(this.clientRegistration));
when(this.authorizedClientService.loadAuthorizedClient(any(), any())).thenReturn(Mono.empty());
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
when(this.authorizedClientProvider.authorize(any())).thenReturn(Mono.empty());
given(this.authorizedClientProvider.authorize(any())).willReturn(Mono.empty());
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
@ -187,13 +187,13 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(Mono.just(this.clientRegistration));
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
when(this.authorizedClientService.loadAuthorizedClient(any(), any())).thenReturn(Mono.empty());
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(Mono.just(this.authorizedClient));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(this.authorizedClient));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -218,13 +218,13 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndSupportedProviderAndCustomSuccessHandlerThenInvokeCustomSuccessHandler() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(Mono.just(this.clientRegistration));
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
when(this.authorizedClientService.loadAuthorizedClient(any(), any())).thenReturn(Mono.empty());
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(Mono.just(this.authorizedClient));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(this.authorizedClient));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -252,10 +252,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@Test
public void authorizeWhenInvalidTokenThenRemoveAuthorizedClient() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(Mono.just(this.clientRegistration));
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
when(this.authorizedClientService.loadAuthorizedClient(any(), any())).thenReturn(Mono.empty());
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -265,8 +265,8 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, null, null),
this.clientRegistration.getRegistrationId());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(Mono.error(exception));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
@ -286,10 +286,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@Test
public void authorizeWhenInvalidGrantThenRemoveAuthorizedClient() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(Mono.just(this.clientRegistration));
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
when(this.authorizedClientService.loadAuthorizedClient(any(), any())).thenReturn(Mono.empty());
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -299,8 +299,8 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null),
this.clientRegistration.getRegistrationId());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(Mono.error(exception));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
@ -320,10 +320,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@Test
public void authorizeWhenServerErrorThenDoNotRemoveAuthorizedClient() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(Mono.just(this.clientRegistration));
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
when(this.authorizedClientService.loadAuthorizedClient(any(), any())).thenReturn(Mono.empty());
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -333,8 +333,8 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, null, null),
this.clientRegistration.getRegistrationId());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(Mono.error(exception));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
@ -352,10 +352,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@Test
public void authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedClient() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(Mono.just(this.clientRegistration));
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
when(this.authorizedClientService.loadAuthorizedClient(any(), any())).thenReturn(Mono.empty());
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -364,8 +364,8 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(Mono.error(exception));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
@ -383,10 +383,10 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@Test
public void authorizeWhenOAuth2AuthorizationExceptionAndCustomFailureHandlerThenInvokeCustomFailureHandler() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(Mono.just(this.clientRegistration));
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
when(this.authorizedClientService.loadAuthorizedClient(any(), any())).thenReturn(Mono.empty());
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -395,8 +395,8 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(Mono.error(exception));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
PublisherProbe<Void> authorizationFailureHandlerProbe = PublisherProbe.empty();
this.authorizedClientManager.setAuthorizationFailureHandler(
@ -420,16 +420,16 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() {
when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.thenReturn(Mono.just(this.clientRegistration));
when(this.authorizedClientService.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal.getName()))).thenReturn(Mono.just(this.authorizedClient));
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal.getName()))).willReturn(Mono.just(this.authorizedClient));
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(Mono.just(reauthorizedClient));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(reauthorizedClient));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
@ -453,7 +453,7 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenUnsupportedProviderThenNotReauthorized() {
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).thenReturn(Mono.empty());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(Mono.empty());
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
@ -477,8 +477,8 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(Mono.just(reauthorizedClient));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(reauthorizedClient));
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
@ -505,8 +505,8 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.thenReturn(Mono.just(reauthorizedClient));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(reauthorizedClient));
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).attribute(OAuth2ParameterNames.SCOPE, "read write").build();

View File

@ -35,8 +35,8 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenRe
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;
/**
* Tests for {@link ClientCredentialsOAuth2AuthorizedClientProvider}.
@ -104,7 +104,7 @@ public class ClientCredentialsOAuth2AuthorizedClientProviderTests {
@Test
public void authorizeWhenClientCredentialsAndNotAuthorizedThenAuthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration).principal(this.principal).build();
@ -125,7 +125,7 @@ public class ClientCredentialsOAuth2AuthorizedClientProviderTests {
this.principal.getName(), accessToken);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient).principal(this.principal).build();
@ -162,7 +162,7 @@ public class ClientCredentialsOAuth2AuthorizedClientProviderTests {
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse);
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient).principal(this.principal).build();

View File

@ -36,8 +36,8 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenRe
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;
/**
* Tests for {@link ClientCredentialsReactiveOAuth2AuthorizedClientProvider}.
@ -105,7 +105,7 @@ public class ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests {
@Test
public void authorizeWhenClientCredentialsAndNotAuthorizedThenAuthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse));
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration).principal(this.principal).build();
@ -126,7 +126,7 @@ public class ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests {
this.principal.getName(), accessToken);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse));
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient).principal(this.principal).build();
@ -163,7 +163,7 @@ public class ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests {
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse));
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient).principal(this.principal).build();

Some files were not shown because too many files have changed in this diff Show More