diff --git a/acl/src/test/java/org/springframework/security/acls/AclPermissionCacheOptimizerTests.java b/acl/src/test/java/org/springframework/security/acls/AclPermissionCacheOptimizerTests.java index 482508791c..221e1b0cac 100644 --- a/acl/src/test/java/org/springframework/security/acls/AclPermissionCacheOptimizerTests.java +++ b/acl/src/test/java/org/springframework/security/acls/AclPermissionCacheOptimizerTests.java @@ -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)); diff --git a/acl/src/test/java/org/springframework/security/acls/AclPermissionEvaluatorTests.java b/acl/src/test/java/org/springframework/security/acls/AclPermissionEvaluatorTests.java index be86bd47a3..c0100858b9 100644 --- a/acl/src/test/java/org/springframework/security/acls/AclPermissionEvaluatorTests.java +++ b/acl/src/test/java/org/springframework/security/acls/AclPermissionEvaluatorTests.java @@ -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(); diff --git a/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProviderTests.java b/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProviderTests.java index b3be3ab76f..dae0fd62c2 100644 --- a/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProviderTests.java +++ b/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProviderTests.java @@ -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)); diff --git a/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java b/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java index 25bd9eb591..8a7787577c 100644 --- a/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java +++ b/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java @@ -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"); diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java index fcff571629..11b01e2c56 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java @@ -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, diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java index 095983b49c..7e087b54d1 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java @@ -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"); } diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java index d8a48ccf8b..edadf05442 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java @@ -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()); diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java index a6e7ac36ce..373a270587 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java @@ -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 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 sids = Arrays.asList(new PrincipalSid("user")); @@ -105,7 +105,7 @@ public class JdbcAclServiceTests { List 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 objectIdentities = this.aclService.findChildren(objectIdentity); diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java index 61f8388499..d0f964ec0d 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java @@ -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); diff --git a/acl/src/test/java/org/springframework/security/acls/sid/SidRetrievalStrategyTests.java b/acl/src/test/java/org/springframework/security/acls/sid/SidRetrievalStrategyTests.java index 2202be86ea..b25bf3c50a 100644 --- a/acl/src/test/java/org/springframework/security/acls/sid/SidRetrievalStrategyTests.java +++ b/acl/src/test/java/org/springframework/security/acls/sid/SidRetrievalStrategyTests.java @@ -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 sids = strat.getSids(this.authentication); diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java index 60313ef8de..1d680d1683 100644 --- a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java +++ b/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java @@ -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); diff --git a/cas/src/test/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests.java b/cas/src/test/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests.java index 32cf90adec..c140dfad92 100644 --- a/cas/src/test/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests.java +++ b/cas/src/test/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests.java @@ -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 roles = AuthorityUtils.authorityListToSet(user.getAuthorities()); diff --git a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java index c48d102ee8..f8c141f7b4 100644 --- a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java +++ b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java @@ -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(); diff --git a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/JwtITests.java b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/JwtITests.java index 7e0bfc0ba5..36008b73b1 100644 --- a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/JwtITests.java +++ b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/JwtITests.java @@ -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(); diff --git a/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java b/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java index fa6bf9e5fa..d311138de0 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java @@ -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 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(); diff --git a/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java index e091dcecb1..3112f51221 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfigurationTests.java @@ -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 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")); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java index 96ec318fb6..474713b393 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/EnableReactiveMethodSecurityTests.java @@ -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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L)) .subscriberContext(this.withUser); diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java index 697f72734a..e2dc8e56bf 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java @@ -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 diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.java index 4744963b5c..f630566f8d 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/builders/NamespaceHttpTests.java @@ -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(); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java index 08af641427..3824048542 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java @@ -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; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java index c5eb62cd68..af7ad3ab0d 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java @@ -61,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(); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java index 4aa9547949..eace9809e5 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/CsrfConfigurerTests.java @@ -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()); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurerTests.java index d3aff8f656..0ed4745f88 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurerTests.java @@ -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()) diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurerTests.java index 46b097a6b9..3ce299689d 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/JeeConfigurerTests.java @@ -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"); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpJeeTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpJeeTests.java index 7cc239f3ab..61e103645f 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpJeeTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpJeeTests.java @@ -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")); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java index 81133d4084..f06590f03c 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java @@ -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")); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.java index 548c700491..241cdf5bac 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.java @@ -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())); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceSessionManagementTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceSessionManagementTests.java index 4cea822c91..d15f595e64 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceSessionManagementTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceSessionManagementTests.java @@ -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"))) diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java index 9de0c521d8..a0030c867e 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.java @@ -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")); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.java index 4d7b7e052d..4d232ac77f 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.java @@ -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("/")); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerTests.java index 267135d6cf..4022a9d2d0 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerTests.java @@ -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(); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurerTests.java index f7e3689a68..a82fc9bbca 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2ClientConfigurerTests.java @@ -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(); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java index 1583f1fa7d..81f12e07cf 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java @@ -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; } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java index 04c077fd60..d48878e014 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java @@ -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 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 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 bean(Class beanClass) { diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java index f2882e78f0..f546583a5d 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java @@ -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()) { diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java index d387b12037..b70773de04 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java @@ -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; } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/messaging/MessageSecurityMetadataSourceRegistryTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/messaging/MessageSecurityMetadataSourceRegistryTests.java index 76fd74d14b..06208c6364 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/messaging/MessageSecurityMetadataSourceRegistryTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/messaging/MessageSecurityMetadataSourceRegistryTests.java @@ -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"); diff --git a/config/src/test/java/org/springframework/security/config/authentication/AuthenticationConfigurationGh3935Tests.java b/config/src/test/java/org/springframework/security/config/authentication/AuthenticationConfigurationGh3935Tests.java index 95006401b7..c1a5d9125e 100644 --- a/config/src/test/java/org/springframework/security/config/authentication/AuthenticationConfigurationGh3935Tests.java +++ b/config/src/test/java/org/springframework/security/config/authentication/AuthenticationConfigurationGh3935Tests.java @@ -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(); diff --git a/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java b/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java index edff3fe164..2801c4e593 100644 --- a/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java @@ -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()); } diff --git a/config/src/test/java/org/springframework/security/config/http/DefaultFilterChainValidatorTests.java b/config/src/test/java/org/springframework/security/config/http/DefaultFilterChainValidatorTests.java index c2795425e7..016c20c74a 100644 --- a/config/src/test/java/org/springframework/security/config/http/DefaultFilterChainValidatorTests.java +++ b/config/src/test/java/org/springframework/security/config/http/DefaultFilterChainValidatorTests.java @@ -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( diff --git a/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java b/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java index 565bea71d1..e21bf32cab 100644 --- a/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/InterceptUrlConfigTests.java @@ -35,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> answer = invocation -> Collections.singletonMap("spring", registration); - when(servletContext.getServletRegistrations()).thenAnswer(answer); + given(servletContext.getServletRegistrations()).willAnswer(answer); return servletContext; } diff --git a/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java b/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java index 604880a82a..c3b59f29fc 100644 --- a/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java @@ -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 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); } diff --git a/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java index 5d9be3a411..7b86dd796a 100644 --- a/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java @@ -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 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 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")); } diff --git a/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java index 6f5608d751..b2162505f5 100644 --- a/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java @@ -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 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 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 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 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 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 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 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 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 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 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 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")); } diff --git a/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java b/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java index 886be53bb5..04e92bdc43 100644 --- a/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java @@ -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("?") diff --git a/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java b/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java index 8f8731f10e..ea8243372a 100644 --- a/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java @@ -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(); diff --git a/config/src/test/java/org/springframework/security/config/web/server/CorsSpecTests.java b/config/src/test/java/org/springframework/security/config/web/server/CorsSpecTests.java index df1cd46980..6407d13d9a 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/CorsSpecTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/CorsSpecTests.java @@ -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(); } diff --git a/config/src/test/java/org/springframework/security/config/web/server/HttpsRedirectSpecTests.java b/config/src/test/java/org/springframework/security/config/web/server/HttpsRedirectSpecTests.java index f935125a03..71583b5a6c 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/HttpsRedirectSpecTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/HttpsRedirectSpecTests.java @@ -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"); diff --git a/config/src/test/java/org/springframework/security/config/web/server/OAuth2ClientSpecTests.java b/config/src/test/java/org/springframework/security/config/web/server/OAuth2ClientSpecTests.java index ea814e54fc..cf7ef9d962 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/OAuth2ClientSpecTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/OAuth2ClientSpecTests.java @@ -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") diff --git a/config/src/test/java/org/springframework/security/config/web/server/OAuth2LoginTests.java b/config/src/test/java/org/springframework/security/config/web/server/OAuth2LoginTests.java index 2bb5aaee8c..71703fa63d 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/OAuth2LoginTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/OAuth2LoginTests.java @@ -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 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>) 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>) 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>) 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>) 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>) invocation -> { + given(failureHandler.onAuthenticationFailure(any(), any())).willAnswer((Answer>) 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>) 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>) 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 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 tokenResponseClient = config.tokenResponseClient; - when(tokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(tokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); OidcUser user = TestOidcUsers.create(); ReactiveOAuth2UserService 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 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 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 tokenResponseClient = config.tokenResponseClient; - when(tokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(tokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); ReactiveJwtDecoderFactory 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"); diff --git a/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java b/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java index 5d4962a5fa..2367e23eb8 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java @@ -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() diff --git a/config/src/test/java/org/springframework/security/config/web/server/ServerHttpSecurityTests.java b/config/src/test/java/org/springframework/security/config/web/server/ServerHttpSecurityTests.java index 014e2d689f..425c8b7c84 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/ServerHttpSecurityTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/ServerHttpSecurityTests.java @@ -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 = 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) diff --git a/core/src/test/java/org/springframework/security/access/expression/SecurityExpressionRootTests.java b/core/src/test/java/org/springframework/security/access/expression/SecurityExpressionRootTests.java index 814dc67422..28d28fd39f 100644 --- a/core/src/test/java/org/springframework/security/access/expression/SecurityExpressionRootTests.java +++ b/core/src/test/java/org/springframework/security/access/expression/SecurityExpressionRootTests.java @@ -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(); } diff --git a/core/src/test/java/org/springframework/security/access/expression/method/DefaultMethodSecurityExpressionHandlerTests.java b/core/src/test/java/org/springframework/security/access/expression/method/DefaultMethodSecurityExpressionHandlerTests.java index 443a3c4ed7..9201f6f56e 100644 --- a/core/src/test/java/org/springframework/security/access/expression/method/DefaultMethodSecurityExpressionHandlerTests.java +++ b/core/src/test/java/org/springframework/security/access/expression/method/DefaultMethodSecurityExpressionHandlerTests.java @@ -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 diff --git a/core/src/test/java/org/springframework/security/access/expression/method/MethodSecurityExpressionRootTests.java b/core/src/test/java/org/springframework/security/access/expression/method/MethodSecurityExpressionRootTests.java index 4867824140..cba5c7c8bc 100644 --- a/core/src/test/java/org/springframework/security/access/expression/method/MethodSecurityExpressionRootTests.java +++ b/core/src/test/java/org/springframework/security/access/expression/method/MethodSecurityExpressionRootTests.java @@ -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(); diff --git a/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptorTests.java b/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptorTests.java index 87293e45be..b510aeb697 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptorTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptorTests.java @@ -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")); } } diff --git a/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityMetadataSourceAdvisorTests.java b/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityMetadataSourceAdvisorTests.java index 7e5b953fdf..d9ea3b8857 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityMetadataSourceAdvisorTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityMetadataSourceAdvisorTests.java @@ -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(); } diff --git a/core/src/test/java/org/springframework/security/access/intercept/aspectj/AspectJMethodSecurityInterceptorTests.java b/core/src/test/java/org/springframework/security/access/intercept/aspectj/AspectJMethodSecurityInterceptorTests.java index 7eb19045b9..f156277895 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/aspectj/AspectJMethodSecurityInterceptorTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/aspectj/AspectJMethodSecurityInterceptorTests.java @@ -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); diff --git a/core/src/test/java/org/springframework/security/access/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java b/core/src/test/java/org/springframework/security/access/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java index b98b4c3487..bd0a55037d 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java @@ -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(); } diff --git a/core/src/test/java/org/springframework/security/access/method/DelegatingMethodSecurityMetadataSourceTests.java b/core/src/test/java/org/springframework/security/access/method/DelegatingMethodSecurityMetadataSourceTests.java index 9cb4449776..ac07025682 100644 --- a/core/src/test/java/org/springframework/security/access/method/DelegatingMethodSecurityMetadataSourceTests.java +++ b/core/src/test/java/org/springframework/security/access/method/DelegatingMethodSecurityMetadataSourceTests.java @@ -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.any(), ArgumentMatchers.any(Class.class))) - .thenReturn(null); + given(delegate.getAttributes(ArgumentMatchers.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); diff --git a/core/src/test/java/org/springframework/security/access/vote/AffirmativeBasedTests.java b/core/src/test/java/org/springframework/security/access/vote/AffirmativeBasedTests.java index 78cb5f1e62..e03cbc3cb9 100644 --- a/core/src/test/java/org/springframework/security/access/vote/AffirmativeBasedTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/AffirmativeBasedTests.java @@ -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 diff --git a/core/src/test/java/org/springframework/security/authentication/AbstractAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/authentication/AbstractAuthenticationTokenTests.java index a880b06f0f..fa7219294a 100644 --- a/core/src/test/java/org/springframework/security/authentication/AbstractAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/authentication/AbstractAuthenticationTokenTests.java @@ -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); diff --git a/core/src/test/java/org/springframework/security/authentication/DelegatingReactiveAuthenticationManagerTests.java b/core/src/test/java/org/springframework/security/authentication/DelegatingReactiveAuthenticationManagerTests.java index 0a7dd80588..23394aef94 100644 --- a/core/src/test/java/org/springframework/security/authentication/DelegatingReactiveAuthenticationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/DelegatingReactiveAuthenticationManagerTests.java @@ -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); diff --git a/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java b/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java index da36c6221d..f8616313af 100644 --- a/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java @@ -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 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; } diff --git a/core/src/test/java/org/springframework/security/authentication/ReactiveAuthenticationManagerAdapterTests.java b/core/src/test/java/org/springframework/security/authentication/ReactiveAuthenticationManagerAdapterTests.java index 93621f82df..99cb38c3d3 100644 --- a/core/src/test/java/org/springframework/security/authentication/ReactiveAuthenticationManagerAdapterTests.java +++ b/core/src/test/java/org/springframework/security/authentication/ReactiveAuthenticationManagerAdapterTests.java @@ -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 result = this.manager.authenticate(this.authentication); diff --git a/core/src/test/java/org/springframework/security/authentication/ReactiveUserDetailsServiceAuthenticationManagerTests.java b/core/src/test/java/org/springframework/security/authentication/ReactiveUserDetailsServiceAuthenticationManagerTests.java index 55c85a7954..69ff1b9aad 100644 --- a/core/src/test/java/org/springframework/security/authentication/ReactiveUserDetailsServiceAuthenticationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/ReactiveUserDetailsServiceAuthenticationManagerTests.java @@ -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); diff --git a/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java b/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java index 6cd9900f1f..a551d8fcb8 100644 --- a/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/UserDetailsRepositoryReactiveAuthenticationManagerTests.java @@ -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()); diff --git a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java index b3993f2f5d..90bbd2336f 100644 --- a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java @@ -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); diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java index 190e116a80..7951b5cc61 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java @@ -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.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); diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java index 7a20b359ae..4fd27e898b 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java @@ -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); diff --git a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java b/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java index 06327a9b68..3602d38288 100644 --- a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java +++ b/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java @@ -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"); diff --git a/core/src/test/java/org/springframework/security/authorization/AuthenticatedReactiveAuthorizationManagerTests.java b/core/src/test/java/org/springframework/security/authorization/AuthenticatedReactiveAuthorizationManagerTests.java index fb8f606b39..788fb05eb1 100644 --- a/core/src/test/java/org/springframework/security/authorization/AuthenticatedReactiveAuthorizationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authorization/AuthenticatedReactiveAuthorizationManagerTests.java @@ -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(); diff --git a/core/src/test/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManagerTests.java b/core/src/test/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManagerTests.java index 0a97cec9df..eeb5fe479d 100644 --- a/core/src/test/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManagerTests.java +++ b/core/src/test/java/org/springframework/security/authorization/AuthorityReactiveAuthorizationManagerTests.java @@ -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(); diff --git a/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextExecutorServiceTests.java b/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextExecutorServiceTests.java index e13de8e6c1..effd99686a 100644 --- a/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextExecutorServiceTests.java +++ b/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextExecutorServiceTests.java @@ -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 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 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) this.delegate.submit(this.wrappedRunnable)).thenReturn(this.expectedFutureObject); + given((Future) 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> exectedResult = Arrays.asList(this.expectedFutureObject); List> wrappedCallables = Arrays.asList(this.wrappedCallable); - when(this.delegate.invokeAll(wrappedCallables)).thenReturn(exectedResult); + given(this.delegate.invokeAll(wrappedCallables)).willReturn(exectedResult); List> 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> exectedResult = Arrays.asList(this.expectedFutureObject); List> 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> 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> exectedResult = Arrays.asList(this.expectedFutureObject); List> 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> exectedResult = Arrays.asList(this.expectedFutureObject); List> 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); diff --git a/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextScheduledExecutorServiceTests.java b/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextScheduledExecutorServiceTests.java index d46f018dcf..62de21e806 100644 --- a/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextScheduledExecutorServiceTests.java +++ b/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextScheduledExecutorServiceTests.java @@ -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) this.delegate.schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS)) - .thenReturn(this.expectedResult); + given((ScheduledFuture) 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 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) this.delegate.scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS)) - .thenReturn(this.expectedResult); + given((ScheduledFuture) 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) this.delegate.scheduleWithFixedDelay(this.wrappedRunnable, 1, 2, - TimeUnit.SECONDS)).thenReturn(this.expectedResult); + given((ScheduledFuture) 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); diff --git a/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextCallableTests.java b/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextCallableTests.java index dd47ea392b..0d386424f6 100644 --- a/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextCallableTests.java +++ b/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextCallableTests.java @@ -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()) diff --git a/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnableTests.java b/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnableTests.java index a444ff0dc0..12365b4fc1 100644 --- a/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnableTests.java +++ b/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnableTests.java @@ -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) invocation -> { + willAnswer((Answer) invocation -> { assertThat(SecurityContextHolder.getContext()).isEqualTo(this.securityContext); return null; - }).when(this.delegate).run(); + }).given(this.delegate).run(); this.executor = Executors.newFixedThreadPool(1); } diff --git a/core/src/test/java/org/springframework/security/context/DelegatingApplicationListenerTests.java b/core/src/test/java/org/springframework/security/context/DelegatingApplicationListenerTests.java index 3c4a7c50bf..2fcd276cc2 100644 --- a/core/src/test/java/org/springframework/security/context/DelegatingApplicationListenerTests.java +++ b/core/src/test/java/org/springframework/security/context/DelegatingApplicationListenerTests.java @@ -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)); diff --git a/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java b/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java index 7253bbe02e..424a344aa0 100644 --- a/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java +++ b/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java @@ -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); diff --git a/crypto/src/test/java/org/springframework/security/crypto/encrypt/AesBytesEncryptorTests.java b/crypto/src/test/java/org/springframework/security/crypto/encrypt/AesBytesEncryptorTests.java index f977ae835b..124889e337 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/encrypt/AesBytesEncryptorTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/encrypt/AesBytesEncryptorTests.java @@ -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 diff --git a/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java b/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java index b9ab13312c..e53288afcc 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/password/DelegatingPasswordEncoderTests.java @@ -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(); diff --git a/etc/checkstyle/checkstyle-suppressions.xml b/etc/checkstyle/checkstyle-suppressions.xml index 99a5d4b17a..92888c1f7f 100644 --- a/etc/checkstyle/checkstyle-suppressions.xml +++ b/etc/checkstyle/checkstyle-suppressions.xml @@ -3,7 +3,6 @@ "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN" "https://checkstyle.org/dtds/suppressions_1_2.dtd"> - diff --git a/ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java b/ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java index 69f8ff8c68..7978c18b4b 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java @@ -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"); diff --git a/ldap/src/test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateTests.java b/ldap/src/test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateTests.java index 069a4561db..2eb15fbbcd 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateTests.java @@ -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); diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java index c2504eb53b..fc090ac0a7 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java @@ -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 { diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorMockTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorMockTests.java index e81d8f5db8..e5c10d8798 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorMockTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorMockTests.java @@ -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")); } diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java index c1a11c0980..17436f2945 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java @@ -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 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 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); diff --git a/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSourceTests.java b/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSourceTests.java index d215282ad5..45681bb1d6 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSourceTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyAwareContextSourceTests.java @@ -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"); } diff --git a/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlFactoryTests.java b/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlFactoryTests.java index 41ff2a17f7..54c1bd06b5 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlFactoryTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/ppolicy/PasswordPolicyControlFactoryTests.java @@ -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()); diff --git a/ldap/src/test/java/org/springframework/security/ldap/userdetails/UserDetailsServiceLdapAuthoritiesPopulatorTests.java b/ldap/src/test/java/org/springframework/security/ldap/userdetails/UserDetailsServiceLdapAuthoritiesPopulatorTests.java index c93f66885f..0909c65191 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/userdetails/UserDetailsServiceLdapAuthoritiesPopulatorTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/userdetails/UserDetailsServiceLdapAuthoritiesPopulatorTests.java @@ -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 auths = populator.getGrantedAuthorities(new DirContextAdapter(), "joe"); diff --git a/messaging/src/test/java/org/springframework/security/messaging/access/expression/DefaultMessageSecurityExpressionHandlerTests.java b/messaging/src/test/java/org/springframework/security/messaging/access/expression/DefaultMessageSecurityExpressionHandlerTests.java index 6501d44e9a..ce7350fe4a 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/access/expression/DefaultMessageSecurityExpressionHandlerTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/access/expression/DefaultMessageSecurityExpressionHandlerTests.java @@ -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(); } diff --git a/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionConfigAttributeTests.java b/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionConfigAttributeTests.java index df89b68aef..f75956e8e6 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionConfigAttributeTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionConfigAttributeTests.java @@ -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()); } diff --git a/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionVoterTests.java b/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionVoterTests.java index e30e730fee..1462d8fecd 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionVoterTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionVoterTests.java @@ -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.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); diff --git a/messaging/src/test/java/org/springframework/security/messaging/access/intercept/ChannelSecurityInterceptorTests.java b/messaging/src/test/java/org/springframework/security/messaging/access/intercept/ChannelSecurityInterceptorTests.java index 6743902f11..fd24be8296 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/access/intercept/ChannelSecurityInterceptorTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/access/intercept/ChannelSecurityInterceptorTests.java @@ -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); diff --git a/messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTests.java b/messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTests.java index 68e50f17e5..68f654ad1e 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/util/matcher/AndMessageMatcherTests.java @@ -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(); diff --git a/messaging/src/test/java/org/springframework/security/messaging/util/matcher/OrMessageMatcherTests.java b/messaging/src/test/java/org/springframework/security/messaging/util/matcher/OrMessageMatcherTests.java index bc1b89e9c2..8eef7e11e9 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/util/matcher/OrMessageMatcherTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/util/matcher/OrMessageMatcherTests.java @@ -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(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java index dd11f065b4..67191de80c 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java @@ -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(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java index 3d308eef94..365560202b 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java @@ -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 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 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(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java index a73b3fe666..b14f9ca94c 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java @@ -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(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java index e6c0fff247..422da2aab9 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java @@ -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(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java index 9e8f49d452..821fda1717 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java @@ -28,8 +28,8 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * Tests for {@link DelegatingOAuth2AuthorizedClientProvider}. @@ -62,7 +62,7 @@ public class DelegatingOAuth2AuthorizedClientProviderTests { TestOAuth2AccessTokens.noScopes()); OAuth2AuthorizedClientProvider authorizedClientProvider = mock(OAuth2AuthorizedClientProvider.class); - when(authorizedClientProvider.authorize(any())).thenReturn(authorizedClient); + given(authorizedClientProvider.authorize(any())).willReturn(authorizedClient); DelegatingOAuth2AuthorizedClientProvider delegate = new DelegatingOAuth2AuthorizedClientProvider( mock(OAuth2AuthorizedClientProvider.class), mock(OAuth2AuthorizedClientProvider.class), diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java index 9ceebf12af..04225c7cf1 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java @@ -29,8 +29,8 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * Tests for {@link DelegatingReactiveOAuth2AuthorizedClientProvider}. @@ -64,13 +64,13 @@ public class DelegatingReactiveOAuth2AuthorizedClientProviderTests { ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock( ReactiveOAuth2AuthorizedClientProvider.class); - when(authorizedClientProvider1.authorize(any())).thenReturn(Mono.empty()); + given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty()); ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock( ReactiveOAuth2AuthorizedClientProvider.class); - when(authorizedClientProvider2.authorize(any())).thenReturn(Mono.empty()); + given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty()); ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider3 = mock( ReactiveOAuth2AuthorizedClientProvider.class); - when(authorizedClientProvider3.authorize(any())).thenReturn(Mono.just(authorizedClient)); + given(authorizedClientProvider3.authorize(any())).willReturn(Mono.just(authorizedClient)); DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider( authorizedClientProvider1, authorizedClientProvider2, authorizedClientProvider3); @@ -88,10 +88,10 @@ public class DelegatingReactiveOAuth2AuthorizedClientProviderTests { ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock( ReactiveOAuth2AuthorizedClientProvider.class); - when(authorizedClientProvider1.authorize(any())).thenReturn(Mono.empty()); + given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty()); ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock( ReactiveOAuth2AuthorizedClientProvider.class); - when(authorizedClientProvider2.authorize(any())).thenReturn(Mono.empty()); + given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty()); DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider( authorizedClientProvider1, authorizedClientProvider2); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java index ff8f9988db..bf04958ad3 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java @@ -30,8 +30,8 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * Tests for {@link InMemoryOAuth2AuthorizedClientService}. @@ -77,7 +77,7 @@ public class InMemoryOAuth2AuthorizedClientServiceTests { new OAuth2AuthorizedClientId(this.registration3.getRegistrationId(), this.principalName1), mock(OAuth2AuthorizedClient.class)); ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class); - when(clientRegistrationRepository.findByRegistrationId(eq(registrationId))).thenReturn(this.registration3); + given(clientRegistrationRepository.findByRegistrationId(eq(registrationId))).willReturn(this.registration3); InMemoryOAuth2AuthorizedClientService authorizedClientService = new InMemoryOAuth2AuthorizedClientService( clientRegistrationRepository, authorizedClients); @@ -112,7 +112,7 @@ public class InMemoryOAuth2AuthorizedClientServiceTests { @Test public void loadAuthorizedClientWhenClientRegistrationFoundAndAssociatedToPrincipalThenReturnAuthorizedClient() { Authentication authentication = mock(Authentication.class); - when(authentication.getName()).thenReturn(this.principalName1); + given(authentication.getName()).willReturn(this.principalName1); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1, mock(OAuth2AccessToken.class)); @@ -136,7 +136,7 @@ public class InMemoryOAuth2AuthorizedClientServiceTests { @Test public void saveAuthorizedClientWhenSavedThenCanLoad() { Authentication authentication = mock(Authentication.class); - when(authentication.getName()).thenReturn(this.principalName2); + given(authentication.getName()).willReturn(this.principalName2); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration3, this.principalName2, mock(OAuth2AccessToken.class)); @@ -160,7 +160,7 @@ public class InMemoryOAuth2AuthorizedClientServiceTests { @Test public void removeAuthorizedClientWhenSavedThenRemoved() { Authentication authentication = mock(Authentication.class); - when(authentication.getName()).thenReturn(this.principalName2); + given(authentication.getName()).willReturn(this.principalName2); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName2, mock(OAuth2AccessToken.class)); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java index a2a7702fa9..d782405489 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java @@ -36,7 +36,7 @@ import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.OAuth2AccessToken; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -114,8 +114,8 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests { @Test public void loadAuthorizedClientWhenClientRegistrationIdNotFoundThenEmpty() { - when(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId)) - .thenReturn(Mono.empty()); + given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId)) + .willReturn(Mono.empty()); StepVerifier.create( this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)) .verifyComplete(); @@ -123,8 +123,8 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests { @Test public void loadAuthorizedClientWhenClientRegistrationFoundAndNotAuthorizedClientThenEmpty() { - when(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId)) - .thenReturn(Mono.just(this.clientRegistration)); + given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId)) + .willReturn(Mono.just(this.clientRegistration)); StepVerifier.create( this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName)) .verifyComplete(); @@ -132,8 +132,8 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests { @Test public void loadAuthorizedClientWhenClientRegistrationFoundThenFound() { - when(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId)) - .thenReturn(Mono.just(this.clientRegistration)); + given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId)) + .willReturn(Mono.just(this.clientRegistration)); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principalName, this.accessToken); Mono saveAndLoad = this.authorizedClientService @@ -191,8 +191,8 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests { @Test public void removeAuthorizedClientWhenClientIdThenNoException() { - when(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId)) - .thenReturn(Mono.empty()); + given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId)) + .willReturn(Mono.empty()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principalName, this.accessToken); Mono saveAndDeleteAndLoad = this.authorizedClientService @@ -204,8 +204,8 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests { @Test public void removeAuthorizedClientWhenClientRegistrationFoundRemovedThenNotFound() { - when(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId)) - .thenReturn(Mono.just(this.clientRegistration)); + given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId)) + .willReturn(Mono.just(this.clientRegistration)); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principalName, this.accessToken); Mono saveAndDeleteAndLoad = this.authorizedClientService diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java index db04ad48c5..0d77243605 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java @@ -57,10 +57,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.within; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; +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; /** * Tests for {@link JdbcOAuth2AuthorizedClientService}. @@ -88,7 +88,7 @@ public class JdbcOAuth2AuthorizedClientServiceTests { public void setUp() { this.clientRegistration = TestClientRegistrations.clientRegistration().build(); this.clientRegistrationRepository = mock(ClientRegistrationRepository.class); - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(this.clientRegistration); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(this.clientRegistration); this.db = createDb(); this.jdbcOperations = new JdbcTemplate(this.db); this.authorizedClientService = new JdbcOAuth2AuthorizedClientService(this.jdbcOperations, @@ -175,7 +175,7 @@ public class JdbcOAuth2AuthorizedClientServiceTests { @Test public void loadAuthorizedClientWhenExistsButNotFoundInClientRegistrationRepositoryThenThrowDataRetrievalFailureException() { - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(null); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(null); Authentication principal = createPrincipal(); OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java index 03b266b3dd..7a1aac6beb 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java @@ -41,10 +41,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.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2AuthorizedClientProviderBuilder}. @@ -68,8 +68,8 @@ public class OAuth2AuthorizedClientProviderBuilderTests { public void setup() { OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); this.accessTokenClient = mock(RestOperations.class); - when(this.accessTokenClient.exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class))) - .thenReturn(new ResponseEntity(accessTokenResponse, HttpStatus.OK)); + given(this.accessTokenClient.exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class))) + .willReturn(new ResponseEntity(accessTokenResponse, HttpStatus.OK)); this.refreshTokenTokenResponseClient = new DefaultRefreshTokenTokenResponseClient(); this.refreshTokenTokenResponseClient.setRestOperations(this.accessTokenClient); this.clientCredentialsTokenResponseClient = new DefaultClientCredentialsTokenResponseClient(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java index 51bac59ef9..4ff28da3a6 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java @@ -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 PasswordOAuth2AuthorizedClientProvider}. @@ -122,7 +122,7 @@ public class PasswordOAuth2AuthorizedClientProviderTests { @Test public void authorizeWhenPasswordAndNotAuthorizedThenAuthorize() { 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) @@ -145,7 +145,7 @@ public class PasswordOAuth2AuthorizedClientProviderTests { this.principal.getName(), accessToken); // without refresh token OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext .withAuthorizedClient(authorizedClient) @@ -196,7 +196,7 @@ public class PasswordOAuth2AuthorizedClientProviderTests { 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) diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java index 78762ffe16..d6525a74ac 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java @@ -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 PasswordReactiveOAuth2AuthorizedClientProvider}. @@ -123,7 +123,7 @@ public class PasswordReactiveOAuth2AuthorizedClientProviderTests { @Test public void authorizeWhenPasswordAndNotAuthorizedThenAuthorize() { 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) @@ -146,7 +146,7 @@ public class PasswordReactiveOAuth2AuthorizedClientProviderTests { this.principal.getName(), accessToken); // without refresh token 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) @@ -197,7 +197,7 @@ public class PasswordReactiveOAuth2AuthorizedClientProviderTests { 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) diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java index 6bec75a33c..c182d271a2 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java @@ -39,9 +39,9 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.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; /** * Tests for {@link ReactiveOAuth2AuthorizedClientProviderBuilder}. @@ -229,7 +229,7 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests { @Test public void buildWhenCustomProviderThenProviderCalled() { ReactiveOAuth2AuthorizedClientProvider customProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class); - when(customProvider.authorize(any())).thenReturn(Mono.empty()); + given(customProvider.authorize(any())).willReturn(Mono.empty()); ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder .builder().provider(customProvider).build(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java index 0eaa623124..137a0968ab 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java @@ -39,9 +39,9 @@ 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.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link RefreshTokenOAuth2AuthorizedClientProvider}. @@ -137,7 +137,7 @@ public class RefreshTokenOAuth2AuthorizedClientProviderTests { public void authorizeWhenAuthorizedAndAccessTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() { OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse() .refreshToken("new-refresh-token").build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); Instant now = Instant.now(); Instant issuedAt = now.minus(Duration.ofMinutes(60)); @@ -166,7 +166,7 @@ public class RefreshTokenOAuth2AuthorizedClientProviderTests { public void authorizeWhenAuthorizedAndAccessTokenExpiredThenReauthorize() { OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse() .refreshToken("new-refresh-token").build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext .withAuthorizedClient(this.authorizedClient).principal(this.principal).build(); @@ -183,7 +183,7 @@ public class RefreshTokenOAuth2AuthorizedClientProviderTests { public void authorizeWhenAuthorizedAndRequestScopeProvidedThenScopeRequested() { OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse() .refreshToken("new-refresh-token").build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); String[] requestScope = new String[] { "read", "write" }; OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java index 350bb39254..0e2867d660 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java @@ -40,9 +40,9 @@ 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.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link RefreshTokenReactiveOAuth2AuthorizedClientProvider}. @@ -138,7 +138,7 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests { public void authorizeWhenAuthorizedAndAccessTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() { OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse() .refreshToken("new-refresh-token").build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); Instant now = Instant.now(); Instant issuedAt = now.minus(Duration.ofMinutes(60)); @@ -168,7 +168,7 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests { public void authorizeWhenAuthorizedAndAccessTokenExpiredThenReauthorize() { OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse() .refreshToken("new-refresh-token").build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext .withAuthorizedClient(this.authorizedClient).principal(this.principal).build(); @@ -186,7 +186,7 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests { public void authorizeWhenAuthorizedAndRequestScopeProvidedThenScopeRequested() { OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse() .refreshToken("new-refresh-token").build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); String[] requestScope = new String[] { "read", "write" }; OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java index 46e79722d2..c745de44fd 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java @@ -35,8 +35,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResp 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.client.registration.TestClientRegistrations.clientRegistration; import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.accessTokenResponse; import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; @@ -105,7 +105,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @Test public void authenticateWhenAuthorizationSuccessResponseThenExchangedForAccessToken() { OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().refreshToken("refresh").build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, success().build()); @@ -133,7 +133,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().additionalParameters(additionalParameters) .build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, success().build()); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java index 101adcf47b..1e956bd75d 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java @@ -40,7 +40,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2Authorization 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.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -81,7 +81,7 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests { @Test public void authenticateWhenValidThenSuccess() { - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(this.tokenResponse.build())); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(this.tokenResponse.build())); OAuth2AuthorizationCodeAuthenticationToken result = authenticate(); @@ -90,7 +90,7 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests { @Test public void authenticateWhenEmptyThenEmpty() { - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.empty()); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.empty()); OAuth2AuthorizationCodeAuthenticationToken result = authenticate(); @@ -99,8 +99,8 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests { @Test public void authenticateWhenOAuth2AuthorizationExceptionThenOAuth2AuthorizationException() { - when(this.accessTokenResponseClient.getTokenResponse(any())) - .thenReturn(Mono.error(() -> new OAuth2AuthorizationException(new OAuth2Error("error")))); + given(this.accessTokenResponseClient.getTokenResponse(any())) + .willReturn(Mono.error(() -> new OAuth2AuthorizationException(new OAuth2Error("error")))); assertThatCode(() -> authenticate()).isInstanceOf(OAuth2AuthorizationException.class); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationProviderTests.java index c60f2ce919..e62a2724f4 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationProviderTests.java @@ -51,8 +51,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; 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.when; import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.error; @@ -160,12 +160,12 @@ public class OAuth2LoginAuthenticationProviderTests { @Test public void authenticateWhenLoginSuccessThenReturnAuthentication() { OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2User principal = mock(OAuth2User.class); List authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); - when(principal.getAuthorities()).thenAnswer((Answer>) invocation -> authorities); - when(this.userService.loadUser(any())).thenReturn(principal); + given(principal.getAuthorities()).willAnswer((Answer>) invocation -> authorities); + given(this.userService.loadUser(any())).willReturn(principal); OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider .authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)); @@ -183,17 +183,17 @@ public class OAuth2LoginAuthenticationProviderTests { @Test public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() { OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2User principal = mock(OAuth2User.class); List authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); - when(principal.getAuthorities()).thenAnswer((Answer>) invocation -> authorities); - when(this.userService.loadUser(any())).thenReturn(principal); + given(principal.getAuthorities()).willAnswer((Answer>) invocation -> authorities); + given(this.userService.loadUser(any())).willReturn(principal); List mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER"); GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class); - when(authoritiesMapper.mapAuthorities(anyCollection())) - .thenAnswer((Answer>) invocation -> mappedAuthorities); + given(authoritiesMapper.mapAuthorities(anyCollection())) + .willAnswer((Answer>) invocation -> mappedAuthorities); this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper); OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider @@ -206,13 +206,13 @@ public class OAuth2LoginAuthenticationProviderTests { @Test public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() { OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2User principal = mock(OAuth2User.class); List authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); - when(principal.getAuthorities()).thenAnswer((Answer>) invocation -> authorities); + given(principal.getAuthorities()).willAnswer((Answer>) invocation -> authorities); ArgumentCaptor userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class); - when(this.userService.loadUser(userRequestArgCaptor.capture())).thenReturn(principal); + given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal); this.authenticationProvider .authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManagerTests.java index 45ef576d48..f16c1db8c6 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManagerTests.java @@ -56,8 +56,8 @@ 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.anyCollection; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -144,8 +144,8 @@ public class OAuth2LoginReactiveAuthenticationManagerTests { public void authenticationWhenOAuth2UserNotFoundThenEmpty() { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo") .tokenType(OAuth2AccessToken.TokenType.BEARER).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); - when(this.userService.loadUser(any())).thenReturn(Mono.empty()); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); + given(this.userService.loadUser(any())).willReturn(Mono.empty()); assertThat(this.manager.authenticate(loginToken()).block()).isNull(); } @@ -153,10 +153,10 @@ public class OAuth2LoginReactiveAuthenticationManagerTests { public void authenticationWhenOAuth2UserFoundThenSuccess() { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo") .tokenType(OAuth2AccessToken.TokenType.BEARER).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user"); - when(this.userService.loadUser(any())).thenReturn(Mono.just(user)); + given(this.userService.loadUser(any())).willReturn(Mono.just(user)); OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken()) .block(); @@ -174,11 +174,11 @@ public class OAuth2LoginReactiveAuthenticationManagerTests { additionalParameters.put("param2", "value2"); OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo") .tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(additionalParameters).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user"); ArgumentCaptor userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class); - when(this.userService.loadUser(userRequestArgCaptor.capture())).thenReturn(Mono.just(user)); + given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user)); this.manager.authenticate(loginToken()).block(); @@ -190,14 +190,14 @@ public class OAuth2LoginReactiveAuthenticationManagerTests { public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo") .tokenType(OAuth2AccessToken.TokenType.BEARER).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user"); - when(this.userService.loadUser(any())).thenReturn(Mono.just(user)); + given(this.userService.loadUser(any())).willReturn(Mono.just(user)); List mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH_USER"); GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class); - when(authoritiesMapper.mapAuthorities(anyCollection())) - .thenAnswer((Answer>) invocation -> mappedAuthorities); + given(authoritiesMapper.mapAuthorities(anyCollection())) + .willAnswer((Answer>) invocation -> mappedAuthorities); this.manager.setAuthoritiesMapper(authoritiesMapper); OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken()) diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java index d95f458da6..16f7d1c589 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClientTests.java @@ -42,10 +42,10 @@ import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.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 @@ -271,7 +271,7 @@ public class WebClientReactiveAuthorizationCodeTokenResponseClientTests { @Test public void setCustomWebClientThenCustomWebClientIsUsed() { WebClient customClient = mock(WebClient.class); - when(customClient.post()).thenReturn(WebClient.builder().build().post()); + given(customClient.post()).willReturn(WebClient.builder().build().post()); this.tokenResponseClient.setWebClient(customClient); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClientTests.java index 5a38145e56..b28b286f59 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClientTests.java @@ -35,11 +35,11 @@ import org.springframework.web.reactive.function.client.WebClientResponseExcepti import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.validateMockitoUsage; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -126,7 +126,7 @@ public class WebClientReactiveClientCredentialsTokenResponseClientTests { @Test public void setWebClientCustomThenCustomClientIsUsed() { WebClient customClient = mock(WebClient.class); - when(customClient.post()).thenReturn(WebClient.builder().build().post()); + given(customClient.post()).willReturn(WebClient.builder().build().post()); this.client.setWebClient(customClient); ClientRegistration registration = this.clientRegistration.build(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeAuthenticationProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeAuthenticationProviderTests.java index fff4999dc1..6cad3746f6 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeAuthenticationProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeAuthenticationProviderTests.java @@ -63,8 +63,8 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; 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.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider.createHash; import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; @@ -129,7 +129,7 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { this.authenticationProvider = new OidcAuthorizationCodeAuthenticationProvider(this.accessTokenResponseClient, this.userService); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(this.accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(this.accessTokenResponse); } @Test @@ -206,7 +206,7 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse .withResponse(this.accessTokenSuccessResponse()).additionalParameters(Collections.emptyMap()).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); this.authenticationProvider .authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)); @@ -229,7 +229,7 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { this.exception.expectMessage(containsString("[invalid_id_token] ID Token Validation Error")); JwtDecoder jwtDecoder = mock(JwtDecoder.class); - when(jwtDecoder.decode(anyString())).thenThrow(new JwtException("ID Token Validation Error")); + given(jwtDecoder.decode(anyString())).willThrow(new JwtException("ID Token Validation Error")); this.authenticationProvider.setJwtDecoderFactory(registration -> jwtDecoder); this.authenticationProvider @@ -265,8 +265,8 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { OidcUser principal = mock(OidcUser.class); List authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); - when(principal.getAuthorities()).thenAnswer((Answer>) invocation -> authorities); - when(this.userService.loadUser(any())).thenReturn(principal); + given(principal.getAuthorities()).willAnswer((Answer>) invocation -> authorities); + given(this.userService.loadUser(any())).willReturn(principal); OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider .authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)); @@ -293,13 +293,13 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { OidcUser principal = mock(OidcUser.class); List authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); - when(principal.getAuthorities()).thenAnswer((Answer>) invocation -> authorities); - when(this.userService.loadUser(any())).thenReturn(principal); + given(principal.getAuthorities()).willAnswer((Answer>) invocation -> authorities); + given(this.userService.loadUser(any())).willReturn(principal); List mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER"); GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class); - when(authoritiesMapper.mapAuthorities(anyCollection())) - .thenAnswer((Answer>) invocation -> mappedAuthorities); + given(authoritiesMapper.mapAuthorities(anyCollection())) + .willAnswer((Answer>) invocation -> mappedAuthorities); this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper); OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider @@ -321,9 +321,9 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { OidcUser principal = mock(OidcUser.class); List authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); - when(principal.getAuthorities()).thenAnswer((Answer>) invocation -> authorities); + given(principal.getAuthorities()).willAnswer((Answer>) invocation -> authorities); ArgumentCaptor userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class); - when(this.userService.loadUser(userRequestArgCaptor.capture())).thenReturn(principal); + given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal); this.authenticationProvider .authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)); @@ -335,7 +335,7 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { private void setUpIdToken(Map claims) { Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); JwtDecoder jwtDecoder = mock(JwtDecoder.class); - when(jwtDecoder.decode(anyString())).thenReturn(idToken); + given(jwtDecoder.decode(anyString())).willReturn(idToken); this.authenticationProvider.setJwtDecoderFactory(registration -> jwtDecoder); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java index 3e5c059c68..74bbe392bd 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java @@ -69,8 +69,8 @@ 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.anyCollection; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeReactiveAuthenticationManager.createHash; import static org.springframework.security.oauth2.jwt.TestJwts.jwt; @@ -172,9 +172,9 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { .tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters( Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue())) .build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); - when(this.jwtDecoder.decode(any())).thenThrow(new JwtException("ID Token Validation Error")); + given(this.jwtDecoder.decode(any())).willThrow(new JwtException("ID Token Validation Error")); this.manager.setJwtDecoderFactory(c -> this.jwtDecoder); assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block()) @@ -198,8 +198,8 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.NONCE, "invalid-nonce-hash"); Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); - when(this.jwtDecoder.decode(any())).thenReturn(Mono.just(idToken)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); + given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken)); this.manager.setJwtDecoderFactory(c -> this.jwtDecoder); assertThatThrownBy(() -> this.manager.authenticate(authorizationCodeAuthentication).block()) @@ -223,9 +223,9 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.NONCE, this.nonceHash); Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); - when(this.userService.loadUser(any())).thenReturn(Mono.empty()); - when(this.jwtDecoder.decode(any())).thenReturn(Mono.just(idToken)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); + given(this.userService.loadUser(any())).willReturn(Mono.empty()); + given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken)); this.manager.setJwtDecoderFactory(c -> this.jwtDecoder); assertThat(this.manager.authenticate(authorizationCodeAuthentication).block()).isNull(); } @@ -246,10 +246,10 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.NONCE, this.nonceHash); Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken); - when(this.userService.loadUser(any())).thenReturn(Mono.just(user)); - when(this.jwtDecoder.decode(any())).thenReturn(Mono.just(idToken)); + given(this.userService.loadUser(any())).willReturn(Mono.just(user)); + given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken)); this.manager.setJwtDecoderFactory(c -> this.jwtDecoder); OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager @@ -277,10 +277,10 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.NONCE, this.nonceHash); Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken); - when(this.userService.loadUser(any())).thenReturn(Mono.just(user)); - when(this.jwtDecoder.decode(any())).thenReturn(Mono.just(idToken)); + given(this.userService.loadUser(any())).willReturn(Mono.just(user)); + given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken)); this.manager.setJwtDecoderFactory(c -> this.jwtDecoder); OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager @@ -312,11 +312,11 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.NONCE, this.nonceHash); Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken); ArgumentCaptor userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class); - when(this.userService.loadUser(userRequestArgCaptor.capture())).thenReturn(Mono.just(user)); - when(this.jwtDecoder.decode(any())).thenReturn(Mono.just(idToken)); + given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user)); + given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken)); this.manager.setJwtDecoderFactory(c -> this.jwtDecoder); this.manager.authenticate(authorizationCodeAuthentication).block(); @@ -342,16 +342,16 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.NONCE, this.nonceHash); Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); - when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken); ArgumentCaptor userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class); - when(this.userService.loadUser(userRequestArgCaptor.capture())).thenReturn(Mono.just(user)); + given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user)); List mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER"); GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class); - when(authoritiesMapper.mapAuthorities(anyCollection())) - .thenAnswer((Answer>) invocation -> mappedAuthorities); - when(this.jwtDecoder.decode(any())).thenReturn(Mono.just(idToken)); + given(authoritiesMapper.mapAuthorities(anyCollection())) + .willAnswer((Answer>) invocation -> mappedAuthorities); + given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken)); this.manager.setJwtDecoderFactory(c -> this.jwtDecoder); this.manager.setAuthoritiesMapper(authoritiesMapper); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java index 3267549be6..c9275d69c1 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactoryTests.java @@ -37,9 +37,9 @@ import org.springframework.security.oauth2.jwt.Jwt; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.same; +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 Joe Grandja @@ -148,8 +148,8 @@ public class OidcIdTokenDecoderFactoryTests { ClientRegistration clientRegistration = this.registration.build(); - when(customJwtValidatorFactory.apply(same(clientRegistration))) - .thenReturn(new OidcIdTokenValidator(clientRegistration)); + given(customJwtValidatorFactory.apply(same(clientRegistration))) + .willReturn(new OidcIdTokenValidator(clientRegistration)); this.idTokenDecoderFactory.createDecoder(clientRegistration); @@ -163,7 +163,7 @@ public class OidcIdTokenDecoderFactoryTests { ClientRegistration clientRegistration = this.registration.build(); - when(customJwsAlgorithmResolver.apply(same(clientRegistration))).thenReturn(MacAlgorithm.HS256); + given(customJwsAlgorithmResolver.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256); this.idTokenDecoderFactory.createDecoder(clientRegistration); @@ -178,8 +178,8 @@ public class OidcIdTokenDecoderFactoryTests { ClientRegistration clientRegistration = this.registration.build(); - when(customClaimTypeConverterFactory.apply(same(clientRegistration))) - .thenReturn(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters())); + given(customClaimTypeConverterFactory.apply(same(clientRegistration))) + .willReturn(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters())); this.idTokenDecoderFactory.createDecoder(clientRegistration); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java index 5cbeefeeb4..f9158a160d 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactoryTests.java @@ -37,9 +37,9 @@ import org.springframework.security.oauth2.jwt.Jwt; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.same; +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 Joe Grandja @@ -148,8 +148,8 @@ public class ReactiveOidcIdTokenDecoderFactoryTests { ClientRegistration clientRegistration = this.registration.build(); - when(customJwtValidatorFactory.apply(same(clientRegistration))) - .thenReturn(new OidcIdTokenValidator(clientRegistration)); + given(customJwtValidatorFactory.apply(same(clientRegistration))) + .willReturn(new OidcIdTokenValidator(clientRegistration)); this.idTokenDecoderFactory.createDecoder(clientRegistration); @@ -163,7 +163,7 @@ public class ReactiveOidcIdTokenDecoderFactoryTests { ClientRegistration clientRegistration = this.registration.build(); - when(customJwsAlgorithmResolver.apply(same(clientRegistration))).thenReturn(MacAlgorithm.HS256); + given(customJwsAlgorithmResolver.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256); this.idTokenDecoderFactory.createDecoder(clientRegistration); @@ -178,8 +178,8 @@ public class ReactiveOidcIdTokenDecoderFactoryTests { ClientRegistration clientRegistration = this.registration.build(); - when(customClaimTypeConverterFactory.apply(same(clientRegistration))) - .thenReturn(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters())); + given(customClaimTypeConverterFactory.apply(same(clientRegistration))) + .willReturn(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters())); this.idTokenDecoderFactory.createDecoder(clientRegistration); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java index eb334875a6..04a51b5d20 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java @@ -55,9 +55,9 @@ 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.same; +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.client.registration.TestClientRegistrations.clientRegistration; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.scopes; @@ -114,7 +114,7 @@ public class OidcReactiveOAuth2UserServiceTests { @Test public void loadUserWhenOAuth2UserEmptyThenNullUserInfo() { - when(this.oauth2UserService.loadUser(any())).thenReturn(Mono.empty()); + given(this.oauth2UserService.loadUser(any())).willReturn(Mono.empty()); OidcUser user = this.userService.loadUser(userRequest()).block(); @@ -125,7 +125,7 @@ public class OidcReactiveOAuth2UserServiceTests { public void loadUserWhenOAuth2UserSubjectNullThenOAuth2AuthenticationException() { OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user"); - when(this.oauth2UserService.loadUser(any())).thenReturn(Mono.just(oauth2User)); + given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User)); assertThatCode(() -> this.userService.loadUser(userRequest()).block()) .isInstanceOf(OAuth2AuthenticationException.class); @@ -138,7 +138,7 @@ public class OidcReactiveOAuth2UserServiceTests { attributes.put("user", "rob"); OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes, "user"); - when(this.oauth2UserService.loadUser(any())).thenReturn(Mono.just(oauth2User)); + given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User)); assertThatCode(() -> this.userService.loadUser(userRequest()).block()) .isInstanceOf(OAuth2AuthenticationException.class); @@ -151,7 +151,7 @@ public class OidcReactiveOAuth2UserServiceTests { attributes.put("user", "rob"); OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes, "user"); - when(this.oauth2UserService.loadUser(any())).thenReturn(Mono.just(oauth2User)); + given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User)); assertThat(this.userService.loadUser(userRequest()).block().getUserInfo()).isNotNull(); } @@ -164,7 +164,7 @@ public class OidcReactiveOAuth2UserServiceTests { attributes.put("user", "rob"); OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes, "user"); - when(this.oauth2UserService.loadUser(any())).thenReturn(Mono.just(oauth2User)); + given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User)); assertThat(this.userService.loadUser(userRequest()).block().getName()).isEqualTo("rob"); } @@ -176,7 +176,7 @@ public class OidcReactiveOAuth2UserServiceTests { attributes.put("user", "rob"); OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes, "user"); - when(this.oauth2UserService.loadUser(any())).thenReturn(Mono.just(oauth2User)); + given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User)); OidcUserRequest userRequest = userRequest(); @@ -184,8 +184,8 @@ public class OidcReactiveOAuth2UserServiceTests { Function.class); this.userService.setClaimTypeConverterFactory(customClaimTypeConverterFactory); - when(customClaimTypeConverterFactory.apply(same(userRequest.getClientRegistration()))) - .thenReturn(new ClaimTypeConverter(OidcReactiveOAuth2UserService.createDefaultClaimTypeConverters())); + given(customClaimTypeConverterFactory.apply(same(userRequest.getClientRegistration()))) + .willReturn(new ClaimTypeConverter(OidcReactiveOAuth2UserService.createDefaultClaimTypeConverters())); this.userService.loadUser(userRequest).block().getUserInfo(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java index 0be3918606..229e38c64f 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java @@ -55,9 +55,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.ArgumentMatchers.same; +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.client.registration.TestClientRegistrations.clientRegistration; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.scopes; @@ -423,8 +423,8 @@ public class OidcUserServiceTests { Function.class); this.userService.setClaimTypeConverterFactory(customClaimTypeConverterFactory); - when(customClaimTypeConverterFactory.apply(same(clientRegistration))) - .thenReturn(new ClaimTypeConverter(OidcUserService.createDefaultClaimTypeConverters())); + given(customClaimTypeConverterFactory.apply(same(clientRegistration))) + .willReturn(new ClaimTypeConverter(OidcUserService.createDefaultClaimTypeConverters())); this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java index f78af6725e..21103b9cde 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java @@ -43,8 +43,8 @@ import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcClientInitiatedServerLogoutSuccessHandler} @@ -67,8 +67,8 @@ public class OidcClientInitiatedServerLogoutSuccessHandlerTests { @Before public void setup() { this.exchange = mock(ServerWebExchange.class); - when(this.exchange.getResponse()).thenReturn(new MockServerHttpResponse()); - when(this.exchange.getRequest()).thenReturn(MockServerHttpRequest.get("/").build()); + given(this.exchange.getResponse()).willReturn(new MockServerHttpResponse()); + given(this.exchange.getRequest()).willReturn(MockServerHttpRequest.get("/").build()); this.chain = mock(WebFilterChain.class); this.handler = new OidcClientInitiatedServerLogoutSuccessHandler(this.repository); } @@ -78,7 +78,7 @@ public class OidcClientInitiatedServerLogoutSuccessHandlerTests { OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(), AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId()); - when(this.exchange.getPrincipal()).thenReturn(Mono.just(token)); + given(this.exchange.getPrincipal()).willReturn(Mono.just(token)); WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain); this.handler.onLogoutSuccess(f, token).block(); @@ -89,7 +89,7 @@ public class OidcClientInitiatedServerLogoutSuccessHandlerTests { public void logoutWhenNotOAuth2AuthenticationThenDefaults() { Authentication token = mock(Authentication.class); - when(this.exchange.getPrincipal()).thenReturn(Mono.just(token)); + given(this.exchange.getPrincipal()).willReturn(Mono.just(token)); WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain); this.handler.setLogoutSuccessUrl(URI.create("https://default")); @@ -103,7 +103,7 @@ public class OidcClientInitiatedServerLogoutSuccessHandlerTests { OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOAuth2Users.create(), AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId()); - when(this.exchange.getPrincipal()).thenReturn(Mono.just(token)); + given(this.exchange.getPrincipal()).willReturn(Mono.just(token)); WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain); this.handler.setLogoutSuccessUrl(URI.create("https://default")); @@ -124,7 +124,7 @@ public class OidcClientInitiatedServerLogoutSuccessHandlerTests { OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(), AuthorityUtils.NO_AUTHORITIES, registration.getRegistrationId()); - when(this.exchange.getPrincipal()).thenReturn(Mono.just(token)); + given(this.exchange.getPrincipal()).willReturn(Mono.just(token)); WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain); handler.setLogoutSuccessUrl(URI.create("https://default")); @@ -139,7 +139,7 @@ public class OidcClientInitiatedServerLogoutSuccessHandlerTests { OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(), AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId()); - when(this.exchange.getPrincipal()).thenReturn(Mono.just(token)); + given(this.exchange.getPrincipal()).willReturn(Mono.just(token)); WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain); this.handler.setPostLogoutRedirectUri(URI.create("https://postlogout?encodedparam=value")); @@ -155,9 +155,9 @@ public class OidcClientInitiatedServerLogoutSuccessHandlerTests { OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(), AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId()); - when(this.exchange.getPrincipal()).thenReturn(Mono.just(token)); + given(this.exchange.getPrincipal()).willReturn(Mono.just(token)); MockServerHttpRequest request = MockServerHttpRequest.get("https://rp.example.org/").build(); - when(this.exchange.getRequest()).thenReturn(request); + given(this.exchange.getRequest()).willReturn(request); WebFilterExchange f = new WebFilterExchange(this.exchange, this.chain); this.handler.setPostLogoutRedirectUri("{baseUrl}"); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java index 2343e07b14..b4256a3b0b 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java @@ -51,8 +51,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.scopes; @@ -361,8 +361,8 @@ public class DefaultOAuth2UserServiceTests { ResponseEntity> responseEntity = new ResponseEntity<>(response, HttpStatus.OK); Converter> requestEntityConverter = mock(Converter.class); RestOperations rest = mock(RestOperations.class); - when(rest.exchange(nullable(RequestEntity.class), any(ParameterizedTypeReference.class))) - .thenReturn(responseEntity); + given(rest.exchange(nullable(RequestEntity.class), any(ParameterizedTypeReference.class))) + .willReturn(responseEntity); DefaultOAuth2UserService userService = new DefaultOAuth2UserService(); userService.setRequestEntityConverter(requestEntityConverter); userService.setRestOperations(rest); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java index c4bbe2b1e2..2e98a22fe2 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java @@ -52,9 +52,9 @@ import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.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.when; import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.scopes; @@ -255,10 +255,10 @@ public class DefaultReactiveOAuth2UserServiceTests { WebClient.RequestHeadersUriSpec spec = spy(real.post()); WebClient rest = spy(WebClient.class); WebClient.ResponseSpec clientResponse = mock(WebClient.ResponseSpec.class); - when(rest.get()).thenReturn(spec); - when(spec.retrieve()).thenReturn(clientResponse); - when(clientResponse.onStatus(any(Predicate.class), any(Function.class))).thenReturn(clientResponse); - when(clientResponse.bodyToMono(any(ParameterizedTypeReference.class))).thenReturn(Mono.just(body)); + given(rest.get()).willReturn(spec); + given(spec.retrieve()).willReturn(clientResponse); + given(clientResponse.onStatus(any(Predicate.class), any(Function.class))).willReturn(clientResponse); + given(clientResponse.bodyToMono(any(ParameterizedTypeReference.class))).willReturn(Mono.just(body)); DefaultReactiveOAuth2UserService userService = new DefaultReactiveOAuth2UserService(); userService.setWebClient(rest); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DelegatingOAuth2UserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DelegatingOAuth2UserServiceTests.java index 6038e10130..91040781e3 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DelegatingOAuth2UserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DelegatingOAuth2UserServiceTests.java @@ -24,8 +24,8 @@ import org.springframework.security.oauth2.core.user.OAuth2User; 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 for {@link DelegatingOAuth2UserService}. @@ -60,7 +60,7 @@ public class DelegatingOAuth2UserServiceTests { OAuth2UserService userService2 = mock(OAuth2UserService.class); OAuth2UserService userService3 = mock(OAuth2UserService.class); OAuth2User mockUser = mock(OAuth2User.class); - when(userService3.loadUser(any(OAuth2UserRequest.class))).thenReturn(mockUser); + given(userService3.loadUser(any(OAuth2UserRequest.class))).willReturn(mockUser); DelegatingOAuth2UserService delegatingUserService = new DelegatingOAuth2UserService<>( Arrays.asList(userService1, userService2, userService3)); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java index 9595ff01fc..2746905e9a 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java @@ -53,12 +53,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 DefaultOAuth2AuthorizedClientManager}. @@ -205,8 +205,8 @@ public class DefaultOAuth2AuthorizedClientManagerTests { @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) @@ -232,11 +232,11 @@ public class DefaultOAuth2AuthorizedClientManagerTests { @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) @@ -264,16 +264,16 @@ public class DefaultOAuth2AuthorizedClientManagerTests { @SuppressWarnings("unchecked") @Test public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() { - when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) - .thenReturn(this.clientRegistration); - when(this.authorizedClientRepository.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()), - eq(this.principal), eq(this.request))).thenReturn(this.authorizedClient); + given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) + .willReturn(this.clientRegistration); + given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()), + eq(this.principal), eq(this.request))).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) @@ -300,11 +300,11 @@ public class DefaultOAuth2AuthorizedClientManagerTests { @Test public void authorizeWhenRequestParameterUsernamePasswordThenMappedToContext() { - 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); // Set custom contextAttributesMapper this.authorizedClientManager.setContextAttributesMapper(authorizeRequest -> { @@ -369,8 +369,8 @@ public class DefaultOAuth2AuthorizedClientManagerTests { 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).attributes(attrs -> { @@ -399,8 +399,8 @@ public class DefaultOAuth2AuthorizedClientManagerTests { 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 @@ -429,8 +429,8 @@ public class DefaultOAuth2AuthorizedClientManagerTests { 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).attributes(attrs -> { @@ -452,8 +452,8 @@ public class DefaultOAuth2AuthorizedClientManagerTests { 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).attributes(attrs -> { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManagerTests.java index 8987e12067..94929d5c33 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManagerTests.java @@ -55,10 +55,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; 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; /** * Tests for {@link DefaultReactiveOAuth2AuthorizedClientManager}. @@ -99,22 +99,22 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @Before public void setup() { this.clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class); - when(this.clientRegistrationRepository.findByRegistrationId(anyString())).thenReturn(Mono.empty()); + given(this.clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.empty()); this.authorizedClientRepository = mock(ServerOAuth2AuthorizedClientRepository.class); this.loadAuthorizedClientProbe = PublisherProbe.empty(); - when(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(Authentication.class), - any(ServerWebExchange.class))).thenReturn(this.loadAuthorizedClientProbe.mono()); + given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(Authentication.class), + any(ServerWebExchange.class))).willReturn(this.loadAuthorizedClientProbe.mono()); this.saveAuthorizedClientProbe = PublisherProbe.empty(); - when(this.authorizedClientRepository.saveAuthorizedClient(any(OAuth2AuthorizedClient.class), + given(this.authorizedClientRepository.saveAuthorizedClient(any(OAuth2AuthorizedClient.class), any(Authentication.class), any(ServerWebExchange.class))) - .thenReturn(this.saveAuthorizedClientProbe.mono()); + .willReturn(this.saveAuthorizedClientProbe.mono()); this.removeAuthorizedClientProbe = PublisherProbe.empty(); - when(this.authorizedClientRepository.removeAuthorizedClient(any(String.class), any(Authentication.class), - any(ServerWebExchange.class))).thenReturn(this.removeAuthorizedClientProbe.mono()); + given(this.authorizedClientRepository.removeAuthorizedClient(any(String.class), any(Authentication.class), + any(ServerWebExchange.class))).willReturn(this.removeAuthorizedClientProbe.mono()); this.authorizedClientProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class); - when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).thenReturn(Mono.empty()); + given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(Mono.empty()); this.contextAttributesMapper = mock(Function.class); - when(this.contextAttributesMapper.apply(any())).thenReturn(Mono.just(Collections.emptyMap())); + given(this.contextAttributesMapper.apply(any())).willReturn(Mono.just(Collections.emptyMap())); this.authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager( this.clientRegistrationRepository, this.authorizedClientRepository); this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider); @@ -196,8 +196,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @SuppressWarnings("unchecked") @Test public void authorizeWhenNotAuthorizedAndUnsupportedProviderThenNotAuthorized() { - 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)); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) @@ -221,10 +221,10 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @SuppressWarnings("unchecked") @Test public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() { - when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) - .thenReturn(Mono.just(this.clientRegistration)); - when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) - .thenReturn(Mono.just(this.authorizedClient)); + given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) + .willReturn(Mono.just(this.clientRegistration)); + given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) + .willReturn(Mono.just(this.authorizedClient)); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) @@ -250,10 +250,10 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @SuppressWarnings("unchecked") @Test public void authorizeWhenNotAuthorizedAndSupportedProviderAndCustomSuccessHandlerThenInvokeCustomSuccessHandler() { - when(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) - .thenReturn(Mono.just(this.clientRegistration)); - when(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) - .thenReturn(Mono.just(this.authorizedClient)); + given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))) + .willReturn(Mono.just(this.clientRegistration)); + given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) + .willReturn(Mono.just(this.authorizedClient)); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) @@ -283,8 +283,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @SuppressWarnings("unchecked") @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)); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) @@ -294,8 +294,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { 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).subscriberContext(this.context).block()) @@ -318,8 +318,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @SuppressWarnings("unchecked") @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)); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) @@ -329,8 +329,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { 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).subscriberContext(this.context).block()) @@ -353,8 +353,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @SuppressWarnings("unchecked") @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)); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) @@ -364,8 +364,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { 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).subscriberContext(this.context).block()) @@ -386,8 +386,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @SuppressWarnings("unchecked") @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)); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) @@ -396,8 +396,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { 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).subscriberContext(this.context).block()) @@ -418,8 +418,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @SuppressWarnings("unchecked") @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)); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest .withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal) @@ -428,8 +428,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { 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 authorizationFailureHandlerProbe = PublisherProbe.empty(); this.authorizedClientManager.setAuthorizationFailureHandler( @@ -455,17 +455,17 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @SuppressWarnings("unchecked") @Test public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() { - 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)); this.loadAuthorizedClientProbe = PublisherProbe.of(Mono.just(this.authorizedClient)); - when(this.authorizedClientRepository.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()), - eq(this.principal), eq(this.serverWebExchange))).thenReturn(this.loadAuthorizedClientProbe.mono()); + given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()), + eq(this.principal), eq(this.serverWebExchange))).willReturn(this.loadAuthorizedClientProbe.mono()); 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) @@ -490,11 +490,11 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { @Test public void authorizeWhenRequestFormParameterUsernamePasswordThenMappedToContext() { - 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.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) - .thenReturn(Mono.just(this.authorizedClient)); + given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))) + .willReturn(Mono.just(this.authorizedClient)); // Set custom contextAttributesMapper capable of mapping the form parameters this.authorizedClientManager.setContextAttributesMapper( @@ -552,8 +552,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { 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(); @@ -580,8 +580,8 @@ public class DefaultReactiveOAuth2AuthorizedClientManagerTests { 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)); // Override the mock with the default this.authorizedClientManager.setContextAttributesMapper( diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java index 50c850d9d7..13eb23d8f5 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java @@ -59,12 +59,12 @@ import org.springframework.util.CollectionUtils; 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.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; import static org.springframework.security.oauth2.core.TestOAuth2RefreshTokens.refreshToken; import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges.success; @@ -281,8 +281,8 @@ public class OAuth2AuthorizationCodeGrantFilterTests { this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1); OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT); - when(this.authenticationManager.authenticate(any(Authentication.class))) - .thenThrow(new OAuth2AuthorizationException(error)); + given(this.authenticationManager.authenticate(any(Authentication.class))) + .willThrow(new OAuth2AuthorizationException(error)); this.filter.doFilter(authorizationResponse, response, filterChain); @@ -481,7 +481,7 @@ public class OAuth2AuthorizationCodeGrantFilterTests { private void setUpAuthenticationResult(ClientRegistration registration) { OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( registration, success(), noScopes(), refreshToken()); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authentication); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authentication); } } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java index 3523691a71..fac30550f6 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java @@ -46,12 +46,12 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.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.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2AuthorizationRequestRedirectFilter}. @@ -253,7 +253,7 @@ public class OAuth2AuthorizationRequestRedirectFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); - doThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).when(filterChain) + willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain) .doFilter(any(ServletRequest.class), any(ServletResponse.class)); this.filter.doFilter(request, response, filterChain); @@ -275,7 +275,7 @@ public class OAuth2AuthorizationRequestRedirectFilterTests { MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); - doThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).when(filterChain) + willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain) .doFilter(any(ServletRequest.class), any(ServletResponse.class)); OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class); @@ -311,7 +311,7 @@ public class OAuth2AuthorizationRequestRedirectFilterTests { OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest .from(defaultAuthorizationRequestResolver.resolve(request)) .additionalParameters(Collections.singletonMap("idp", request.getParameter("idp"))).build(); - when(resolver.resolve(any())).thenReturn(result); + given(resolver.resolve(any())).willReturn(result); OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver); filter.doFilter(request, response, filterChain); @@ -353,7 +353,7 @@ public class OAuth2AuthorizationRequestRedirectFilterTests { .from(defaultAuthorizationRequestResolver.resolve(request)) .additionalParameters(Collections.singletonMap("idp", request.getParameter("idp"))) .authorizationRequestUri(customAuthorizationRequestUri).build(); - when(resolver.resolve(any())).thenReturn(result); + given(resolver.resolve(any())).willReturn(result); OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java index 25e3b6171d..c632f1b81e 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java @@ -59,12 +59,12 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.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.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges.success; /** @@ -446,7 +446,7 @@ public class OAuth2LoginAuthenticationFilterTests { request.addParameter(OAuth2ParameterNames.STATE, state); WebAuthenticationDetails webAuthenticationDetails = mock(WebAuthenticationDetails.class); - when(this.authenticationDetailsSource.buildDetails(any())).thenReturn(webAuthenticationDetails); + given(this.authenticationDetailsSource.buildDetails(any())).willReturn(webAuthenticationDetails); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -484,17 +484,17 @@ public class OAuth2LoginAuthenticationFilterTests { private void setUpAuthenticationResult(ClientRegistration registration) { OAuth2User user = mock(OAuth2User.class); - when(user.getName()).thenReturn(this.principalName1); + given(user.getName()).willReturn(this.principalName1); this.loginAuthentication = mock(OAuth2LoginAuthenticationToken.class); - when(this.loginAuthentication.getPrincipal()).thenReturn(user); - when(this.loginAuthentication.getName()).thenReturn(this.principalName1); - when(this.loginAuthentication.getAuthorities()).thenReturn(AuthorityUtils.createAuthorityList("ROLE_USER")); - when(this.loginAuthentication.getClientRegistration()).thenReturn(registration); - when(this.loginAuthentication.getAuthorizationExchange()).thenReturn(success()); - when(this.loginAuthentication.getAccessToken()).thenReturn(mock(OAuth2AccessToken.class)); - when(this.loginAuthentication.getRefreshToken()).thenReturn(mock(OAuth2RefreshToken.class)); - when(this.loginAuthentication.isAuthenticated()).thenReturn(true); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(this.loginAuthentication); + given(this.loginAuthentication.getPrincipal()).willReturn(user); + given(this.loginAuthentication.getName()).willReturn(this.principalName1); + given(this.loginAuthentication.getAuthorities()).willReturn(AuthorityUtils.createAuthorityList("ROLE_USER")); + given(this.loginAuthentication.getClientRegistration()).willReturn(registration); + given(this.loginAuthentication.getAuthorizationExchange()).willReturn(success()); + given(this.loginAuthentication.getAccessToken()).willReturn(mock(OAuth2AccessToken.class)); + given(this.loginAuthentication.getRefreshToken()).willReturn(mock(OAuth2RefreshToken.class)); + given(this.loginAuthentication.isAuthenticated()).willReturn(true); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(this.loginAuthentication); } } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java index 6942c53c7d..e3564117d4 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java @@ -66,9 +66,9 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; 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.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2AuthorizedClientArgumentResolver}. @@ -131,12 +131,12 @@ public class OAuth2AuthorizedClientArgumentResolverTests { this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager); this.authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName, mock(OAuth2AccessToken.class)); - when(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration1.getRegistrationId()), - any(Authentication.class), any(HttpServletRequest.class))).thenReturn(this.authorizedClient1); + given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration1.getRegistrationId()), + any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient1); this.authorizedClient2 = new OAuth2AuthorizedClient(this.registration2, this.principalName, mock(OAuth2AccessToken.class)); - when(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration2.getRegistrationId()), - any(Authentication.class), any(HttpServletRequest.class))).thenReturn(this.authorizedClient2); + given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration2.getRegistrationId()), + any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient2); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } @@ -218,7 +218,7 @@ public class OAuth2AuthorizedClientArgumentResolverTests { @Test public void resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves() throws Exception { OAuth2AuthenticationToken authentication = mock(OAuth2AuthenticationToken.class); - when(authentication.getAuthorizedClientRegistrationId()).thenReturn("client1"); + given(authentication.getAuthorizedClientRegistrationId()).willReturn("client1"); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); SecurityContextHolder.setContext(securityContext); @@ -246,8 +246,8 @@ public class OAuth2AuthorizedClientArgumentResolverTests { @Test public void resolveArgumentWhenAuthorizedClientNotFoundForAuthorizationCodeClientThenThrowClientAuthorizationRequiredException() { - when(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class))) - .thenReturn(null); + given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class))) + .willReturn(null); MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class); assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, @@ -270,10 +270,10 @@ public class OAuth2AuthorizedClientArgumentResolverTests { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234") .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).build(); - when(clientCredentialsTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); - when(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class))) - .thenReturn(null); + given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class))) + .willReturn(null); MethodParameter methodParameter = this.getMethodParameter("clientCredentialsClient", OAuth2AuthorizedClient.class); @@ -318,10 +318,10 @@ public class OAuth2AuthorizedClientArgumentResolverTests { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234") .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).build(); - when(passwordTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(passwordTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); - when(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class))) - .thenReturn(null); + given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class))) + .willReturn(null); MethodParameter methodParameter = this.getMethodParameter("passwordClient", OAuth2AuthorizedClient.class); this.request.setParameter(OAuth2ParameterNames.USERNAME, "username"); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java index 589600730a..8007fad1bc 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java @@ -56,13 +56,13 @@ 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.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId; /** @@ -138,8 +138,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests { ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().tokenUri(this.serverUrl) .build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))) - .thenReturn(Mono.just(clientRegistration)); + given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))) + .willReturn(Mono.just(clientRegistration)); this.webClient.get().uri(this.serverUrl) .attributes(clientRegistrationId(clientRegistration.getRegistrationId())).retrieve() @@ -166,8 +166,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().tokenUri(this.serverUrl) .build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))) - .thenReturn(Mono.just(clientRegistration)); + given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))) + .willReturn(Mono.just(clientRegistration)); Instant issuedAt = Instant.now().minus(Duration.ofDays(1)); Instant expiresAt = issuedAt.plus(Duration.ofHours(1)); @@ -208,8 +208,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests { ClientRegistration clientRegistration1 = TestClientRegistrations.clientCredentials().registrationId("client-1") .tokenUri(this.serverUrl).build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration1.getRegistrationId()))) - .thenReturn(Mono.just(clientRegistration1)); + given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration1.getRegistrationId()))) + .willReturn(Mono.just(clientRegistration1)); // Client 2 this.server.enqueue(jsonResponse(accessTokenResponse)); @@ -217,8 +217,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests { ClientRegistration clientRegistration2 = TestClientRegistrations.clientCredentials().registrationId("client-2") .tokenUri(this.serverUrl).build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration2.getRegistrationId()))) - .thenReturn(Mono.just(clientRegistration2)); + given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration2.getRegistrationId()))) + .willReturn(Mono.just(clientRegistration2)); this.webClient.get().uri(this.serverUrl) .attributes(clientRegistrationId(clientRegistration1.getRegistrationId())).retrieve() @@ -255,8 +255,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests { ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().tokenUri(this.serverUrl) .build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))) - .thenReturn(Mono.just(clientRegistration)); + given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))) + .willReturn(Mono.just(clientRegistration)); OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("read", "write"); OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java index 110026c1f2..950f145c4e 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java @@ -100,12 +100,12 @@ import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.AssertionsForClassTypes.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.verifyZeroInteractions; -import static org.mockito.Mockito.when; import static org.springframework.http.HttpMethod.GET; import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId; import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient; @@ -172,8 +172,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.clientRegistrationRepository, this.authorizedClientRepository); this.authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); this.function = new ServerOAuth2AuthorizedClientExchangeFilterFunction(this.authorizedClientManager); - when(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).thenReturn(Mono.empty()); - when(this.exchange.getResponse().headers()).thenReturn(mock(ClientResponse.Headers.class)); + given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty()); + given(this.exchange.getResponse().headers()).willReturn(mock(ClientResponse.Headers.class)); } @Test @@ -246,8 +246,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { public void filterWhenClientCredentialsTokenExpiredThenGetNewToken() { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token") .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build(); - when(this.clientCredentialsTokenResponseClient.getTokenResponse(any())) - .thenReturn(Mono.just(accessTokenResponse)); + given(this.clientCredentialsTokenResponseClient.getTokenResponse(any())) + .willReturn(Mono.just(accessTokenResponse)); ClientRegistration registration = TestClientRegistrations.clientCredentials().build(); Instant issuedAt = Instant.now().minus(Duration.ofDays(1)); @@ -307,7 +307,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { public void filterWhenRefreshRequiredThenRefresh() { OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1") .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build(); - when(this.refreshTokenTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(response)); + given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(response)); Instant issuedAt = Instant.now().minus(Duration.ofDays(1)); Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1)); @@ -347,7 +347,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { public void filterWhenRefreshRequiredAndEmptyReactiveSecurityContextThenSaved() { OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1") .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build(); - when(this.refreshTokenTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(response)); + given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(response)); Instant issuedAt = Instant.now().minus(Duration.ofDays(1)); Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1)); @@ -419,8 +419,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); PublisherProbe publisherProbe = PublisherProbe.empty(); - when(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) - .thenReturn(publisherProbe.mono()); + given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) + .willReturn(publisherProbe.mono()); OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", @@ -428,7 +428,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) .attributes(oauth2AuthorizedClient(authorizedClient)).build(); - when(this.exchange.getResponse().rawStatusCode()).thenReturn(HttpStatus.UNAUTHORIZED.value()); + given(this.exchange.getResponse().rawStatusCode()).willReturn(HttpStatus.UNAUTHORIZED.value()); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -454,8 +454,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); PublisherProbe publisherProbe = PublisherProbe.empty(); - when(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) - .thenReturn(publisherProbe.mono()); + given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) + .willReturn(publisherProbe.mono()); OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", @@ -493,8 +493,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); PublisherProbe publisherProbe = PublisherProbe.empty(); - when(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) - .thenReturn(publisherProbe.mono()); + given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) + .willReturn(publisherProbe.mono()); OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", @@ -502,7 +502,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) .attributes(oauth2AuthorizedClient(authorizedClient)).build(); - when(this.exchange.getResponse().rawStatusCode()).thenReturn(HttpStatus.FORBIDDEN.value()); + given(this.exchange.getResponse().rawStatusCode()).willReturn(HttpStatus.FORBIDDEN.value()); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -528,8 +528,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); PublisherProbe publisherProbe = PublisherProbe.empty(); - when(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) - .thenReturn(publisherProbe.mono()); + given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) + .willReturn(publisherProbe.mono()); OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", @@ -567,8 +567,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); PublisherProbe publisherProbe = PublisherProbe.empty(); - when(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) - .thenReturn(publisherProbe.mono()); + given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) + .willReturn(publisherProbe.mono()); OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", @@ -580,9 +580,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { + "error_description=\"The request requires higher privileges than provided by the access token.\", " + "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\""; ClientResponse.Headers headers = mock(ClientResponse.Headers.class); - when(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE))) - .thenReturn(Collections.singletonList(wwwAuthenticateHeader)); - when(this.exchange.getResponse().headers()).thenReturn(headers); + given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE))) + .willReturn(Collections.singletonList(wwwAuthenticateHeader)); + given(this.exchange.getResponse().headers()).willReturn(headers); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -611,8 +611,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); PublisherProbe publisherProbe = PublisherProbe.empty(); - when(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) - .thenReturn(publisherProbe.mono()); + given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())) + .willReturn(publisherProbe.mono()); OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", @@ -649,7 +649,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) .attributes(oauth2AuthorizedClient(authorizedClient)).build(); - when(this.exchange.getResponse().rawStatusCode()).thenReturn(HttpStatus.BAD_REQUEST.value()); + given(this.exchange.getResponse().rawStatusCode()).willReturn(HttpStatus.BAD_REQUEST.value()); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -663,12 +663,12 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token") .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build(); - when(this.passwordTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); + given(this.passwordTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); - when(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))) - .thenReturn(Mono.just(registration)); - when(this.authorizedClientRepository.loadAuthorizedClient(eq(registration.getRegistrationId()), - eq(authentication), any())).thenReturn(Mono.empty()); + given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))) + .willReturn(Mono.just(registration)); + given(this.authorizedClientRepository.loadAuthorizedClient(eq(registration.getRegistrationId()), + eq(authentication), any())).willReturn(Mono.empty()); // Set custom contextAttributesMapper capable of mapping the form parameters this.authorizedClientManager.setContextAttributesMapper(authorizeRequest -> { @@ -713,8 +713,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - when(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) - .thenReturn(Mono.just(authorizedClient)); + given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) + .willReturn(Mono.just(authorizedClient)); ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) .attributes(clientRegistrationId(this.registration.getRegistrationId())).build(); @@ -736,8 +736,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - when(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) - .thenReturn(Mono.just(authorizedClient)); + given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) + .willReturn(Mono.just(authorizedClient)); ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -759,8 +759,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - when(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) - .thenReturn(Mono.just(authorizedClient)); + given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) + .willReturn(Mono.just(authorizedClient)); ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), @@ -804,8 +804,8 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - when(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) - .thenReturn(Mono.just(authorizedClient)); + given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) + .willReturn(Mono.just(authorizedClient)); ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) .attributes(clientRegistrationId(this.registration.getRegistrationId())).build(); @@ -828,12 +828,12 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token") .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build(); - when(this.clientCredentialsTokenResponseClient.getTokenResponse(any())) - .thenReturn(Mono.just(accessTokenResponse)); + given(this.clientCredentialsTokenResponseClient.getTokenResponse(any())) + .willReturn(Mono.just(accessTokenResponse)); ClientRegistration registration = TestClientRegistrations.clientCredentials().build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))) - .thenReturn(Mono.just(registration)); + given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))) + .willReturn(Mono.just(registration)); ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) .attributes(clientRegistrationId(registration.getRegistrationId())).build(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java index cd2fbb3438..7e8ca01a23 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java @@ -58,12 +58,12 @@ import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY; import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId; @@ -159,8 +159,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests { ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().tokenUri(this.serverUrl) .build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))) - .thenReturn(clientRegistration); + given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))) + .willReturn(clientRegistration); this.webClient.get().uri(this.serverUrl) .attributes(clientRegistrationId(clientRegistration.getRegistrationId())).retrieve() @@ -186,8 +186,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().tokenUri(this.serverUrl) .build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))) - .thenReturn(clientRegistration); + given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))) + .willReturn(clientRegistration); Instant issuedAt = Instant.now().minus(Duration.ofDays(1)); Instant expiresAt = issuedAt.plus(Duration.ofHours(1)); @@ -227,8 +227,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests { ClientRegistration clientRegistration1 = TestClientRegistrations.clientCredentials().registrationId("client-1") .tokenUri(this.serverUrl).build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration1.getRegistrationId()))) - .thenReturn(clientRegistration1); + given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration1.getRegistrationId()))) + .willReturn(clientRegistration1); // Client 2 this.server.enqueue(jsonResponse(accessTokenResponse)); @@ -236,8 +236,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests { ClientRegistration clientRegistration2 = TestClientRegistrations.clientCredentials().registrationId("client-2") .tokenUri(this.serverUrl).build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration2.getRegistrationId()))) - .thenReturn(clientRegistration2); + given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration2.getRegistrationId()))) + .willReturn(clientRegistration2); this.webClient.get().uri(this.serverUrl) .attributes(clientRegistrationId(clientRegistration1.getRegistrationId())).retrieve() diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java index 2728dce197..edc3d712b8 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java @@ -109,11 +109,11 @@ import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.AssertionsForClassTypes.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.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.http.HttpMethod.GET; import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId; import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY; @@ -322,7 +322,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { public void filterWhenRefreshRequiredThenRefresh() { OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1") .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build(); - when(this.refreshTokenTokenResponseClient.getTokenResponse(any())).thenReturn(response); + given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(response); Instant issuedAt = Instant.now().minus(Duration.ofDays(1)); Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1)); @@ -365,8 +365,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { .build(); RestOperations refreshTokenClient = mock(RestOperations.class); - when(refreshTokenClient.exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class))) - .thenReturn(new ResponseEntity(response, HttpStatus.OK)); + given(refreshTokenClient.exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class))) + .willReturn(new ResponseEntity(response, HttpStatus.OK)); DefaultRefreshTokenTokenResponseClient refreshTokenTokenResponseClient = new DefaultRefreshTokenTokenResponseClient(); refreshTokenTokenResponseClient.setRestOperations(refreshTokenClient); @@ -443,7 +443,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { this.registration = TestClientRegistrations.clientCredentials().build(); OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); - when(this.clientCredentialsTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); Instant issuedAt = Instant.now().minus(Duration.ofDays(1)); Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1)); @@ -478,11 +478,11 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { public void filterWhenPasswordClientNotAuthorizedThenGetNewToken() { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token") .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build(); - when(this.passwordTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); + given(this.passwordTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); ClientRegistration registration = TestClientRegistrations.password().build(); - when(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))) - .thenReturn(registration); + given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))) + .willReturn(registration); // Set custom contextAttributesMapper this.authorizedClientManager.setContextAttributesMapper(authorizeRequest -> { @@ -525,7 +525,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { public void filterWhenRefreshRequiredAndEmptyReactiveSecurityContextThenSaved() { OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1") .tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build(); - when(this.refreshTokenTokenResponseClient.getTokenResponse(any())).thenReturn(response); + given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(response); Instant issuedAt = Instant.now().minus(Duration.ofDays(1)); Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1)); @@ -616,9 +616,9 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken); - when(this.authorizedClientRepository.loadAuthorizedClient( + given(this.authorizedClientRepository.loadAuthorizedClient( eq(authentication.getAuthorizedClientRegistrationId()), eq(authentication), eq(servletRequest))) - .thenReturn(authorizedClient); + .willReturn(authorizedClient); // Default request attributes set final ClientRequest request1 = ClientRequest.create(GET, URI.create("https://example1.com")) @@ -667,8 +667,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(httpServletRequest(servletRequest)) .attributes(httpServletResponse(servletResponse)).build(); - when(this.exchange.getResponse().rawStatusCode()).thenReturn(httpStatus.value()); - when(this.exchange.getResponse().headers()).thenReturn(mock(ClientResponse.Headers.class)); + given(this.exchange.getResponse().rawStatusCode()).willReturn(httpStatus.value()); + given(this.exchange.getResponse().headers()).willReturn(mock(ClientResponse.Headers.class)); this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); this.function.filter(request, this.exchange).block(); @@ -703,9 +703,9 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { + "error_description=\"The request requires higher privileges than provided by the access token.\", " + "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\""; ClientResponse.Headers headers = mock(ClientResponse.Headers.class); - when(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE))) - .thenReturn(Collections.singletonList(wwwAuthenticateHeader)); - when(this.exchange.getResponse().headers()).thenReturn(headers); + given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE))) + .willReturn(Collections.singletonList(wwwAuthenticateHeader)); + given(this.exchange.getResponse().headers()).willReturn(headers); this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); this.function.filter(request, this.exchange).block(); @@ -818,8 +818,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(httpServletRequest(servletRequest)) .attributes(httpServletResponse(servletResponse)).build(); - when(this.exchange.getResponse().rawStatusCode()).thenReturn(HttpStatus.BAD_REQUEST.value()); - when(this.exchange.getResponse().headers()).thenReturn(mock(ClientResponse.Headers.class)); + given(this.exchange.getResponse().rawStatusCode()).willReturn(HttpStatus.BAD_REQUEST.value()); + given(this.exchange.getResponse().headers()).willReturn(mock(ClientResponse.Headers.class)); this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler); this.function.filter(request, this.exchange).block(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java index eb3f47b240..577aca3bb7 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java @@ -51,8 +51,8 @@ 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.when; /** * @author Rob Winch @@ -88,8 +88,8 @@ public class OAuth2AuthorizedClientArgumentResolverTests { this.clientRegistration = TestClientRegistrations.clientRegistration().build(); this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.authentication.getName(), TestOAuth2AccessTokens.noScopes()); - when(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any())) - .thenReturn(Mono.just(this.authorizedClient)); + given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any())) + .willReturn(Mono.just(this.authorizedClient)); } @Test @@ -141,8 +141,8 @@ public class OAuth2AuthorizedClientArgumentResolverTests { @Test public void resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves() { this.authentication = mock(OAuth2AuthenticationToken.class); - when(((OAuth2AuthenticationToken) this.authentication).getAuthorizedClientRegistrationId()) - .thenReturn("client1"); + given(((OAuth2AuthenticationToken) this.authentication).getAuthorizedClientRegistrationId()) + .willReturn("client1"); MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AuthorizedClient.class); resolveArgument(methodParameter); } @@ -164,9 +164,9 @@ public class OAuth2AuthorizedClientArgumentResolverTests { @Test public void resolveArgumentWhenOAuth2AuthorizedClientNotFoundThenThrowClientAuthorizationRequiredException() { - when(this.clientRegistrationRepository.findByRegistrationId(any())) - .thenReturn(Mono.just(this.clientRegistration)); - when(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any())).thenReturn(Mono.empty()); + given(this.clientRegistrationRepository.findByRegistrationId(any())) + .willReturn(Mono.just(this.clientRegistration)); + given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any())).willReturn(Mono.empty()); MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class); assertThatThrownBy(() -> resolveArgument(methodParameter)) diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests.java index 119eaa1f3e..18763ef55c 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests.java @@ -31,9 +31,9 @@ import org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAut 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.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -76,7 +76,7 @@ public class AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests { @Test public void loadAuthorizedClientWhenAuthenticatedPrincipalThenLoadFromService() { - when(this.authorizedClientService.loadAuthorizedClient(any(), any())).thenReturn(Mono.empty()); + given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty()); Authentication authentication = this.createAuthenticatedPrincipal(); this.authorizedClientRepository.loadAuthorizedClient(this.registrationId, authentication, this.exchange) .block(); @@ -85,8 +85,8 @@ public class AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests { @Test public void loadAuthorizedClientWhenAnonymousPrincipalThenLoadFromAnonymousRepository() { - when(this.anonymousAuthorizedClientRepository.loadAuthorizedClient(any(), any(), any())) - .thenReturn(Mono.empty()); + given(this.anonymousAuthorizedClientRepository.loadAuthorizedClient(any(), any(), any())) + .willReturn(Mono.empty()); Authentication authentication = this.createAnonymousPrincipal(); this.authorizedClientRepository.loadAuthorizedClient(this.registrationId, authentication, this.exchange) .block(); @@ -96,7 +96,7 @@ public class AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests { @Test public void saveAuthorizedClientWhenAuthenticatedPrincipalThenSaveToService() { - when(this.authorizedClientService.saveAuthorizedClient(any(), any())).thenReturn(Mono.empty()); + given(this.authorizedClientService.saveAuthorizedClient(any(), any())).willReturn(Mono.empty()); Authentication authentication = this.createAuthenticatedPrincipal(); OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class); this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authentication, this.exchange).block(); @@ -105,8 +105,8 @@ public class AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests { @Test public void saveAuthorizedClientWhenAnonymousPrincipalThenSaveToAnonymousRepository() { - when(this.anonymousAuthorizedClientRepository.saveAuthorizedClient(any(), any(), any())) - .thenReturn(Mono.empty()); + given(this.anonymousAuthorizedClientRepository.saveAuthorizedClient(any(), any(), any())) + .willReturn(Mono.empty()); Authentication authentication = this.createAnonymousPrincipal(); OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class); this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authentication, this.exchange).block(); @@ -116,7 +116,7 @@ public class AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests { @Test public void removeAuthorizedClientWhenAuthenticatedPrincipalThenRemoveFromService() { - when(this.authorizedClientService.removeAuthorizedClient(any(), any())).thenReturn(Mono.empty()); + given(this.authorizedClientService.removeAuthorizedClient(any(), any())).willReturn(Mono.empty()); Authentication authentication = this.createAuthenticatedPrincipal(); this.authorizedClientRepository.removeAuthorizedClient(this.registrationId, authentication, this.exchange) .block(); @@ -125,8 +125,8 @@ public class AuthenticatedPrincipalServerOAuth2AuthorizedClientRepositoryTests { @Test public void removeAuthorizedClientWhenAnonymousPrincipalThenRemoveFromAnonymousRepository() { - when(this.anonymousAuthorizedClientRepository.removeAuthorizedClient(any(), any(), any())) - .thenReturn(Mono.empty()); + given(this.anonymousAuthorizedClientRepository.removeAuthorizedClient(any(), any(), any())) + .willReturn(Mono.empty()); Authentication authentication = this.createAnonymousPrincipal(); this.authorizedClientRepository.removeAuthorizedClient(this.registrationId, authentication, this.exchange) .block(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolverTests.java index cd11c7910f..5307448290 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolverTests.java @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowableOfType; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -76,7 +76,7 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests { @Test public void resolveWhenClientRegistrationNotFoundMatchThenBadRequest() { - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(Mono.empty()); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty()); ResponseStatusException expected = catchThrowableOfType(() -> resolve("/oauth2/authorization/not-found-id"), ResponseStatusException.class); @@ -86,7 +86,7 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests { @Test public void resolveWhenClientRegistrationFoundThenWorks() { - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(Mono.just(this.registration)); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.registration)); OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/not-found-id"); @@ -97,7 +97,7 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests { @Test public void resolveWhenForwardedHeadersClientRegistrationFoundThenWorks() { - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(Mono.just(this.registration)); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.registration)); ServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/oauth2/authorization/id").header("X-Forwarded-Host", "evil.com")); @@ -110,8 +110,8 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests { @Test public void resolveWhenAuthorizationRequestWithValidPkceClientThenResolves() { - when(this.clientRegistrationRepository.findByRegistrationId(any())) - .thenReturn(Mono.just(TestClientRegistrations.clientRegistration() + given(this.clientRegistrationRepository.findByRegistrationId(any())) + .willReturn(Mono.just(TestClientRegistrations.clientRegistration() .clientAuthenticationMethod(ClientAuthenticationMethod.NONE).clientSecret(null).build())); OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/registration-id"); @@ -127,8 +127,8 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests { @Test public void resolveWhenAuthenticationRequestWithValidOidcClientThenResolves() { - when(this.clientRegistrationRepository.findByRegistrationId(any())) - .thenReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())); + given(this.clientRegistrationRepository.findByRegistrationId(any())) + .willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())); OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/registration-id"); @@ -142,8 +142,8 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests { // gh-7696 @Test public void resolveWhenAuthorizationRequestCustomizerRemovesNonceThenQueryExcludesNonce() { - when(this.clientRegistrationRepository.findByRegistrationId(any())) - .thenReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())); + given(this.clientRegistrationRepository.findByRegistrationId(any())) + .willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())); this.resolver.setAuthorizationRequestCustomizer( customizer -> customizer.additionalParameters(params -> params.remove(OidcParameterNames.NONCE)) @@ -161,8 +161,8 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests { @Test public void resolveWhenAuthorizationRequestCustomizerAddsParameterThenQueryIncludesParameter() { - when(this.clientRegistrationRepository.findByRegistrationId(any())) - .thenReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())); + given(this.clientRegistrationRepository.findByRegistrationId(any())) + .willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())); this.resolver.setAuthorizationRequestCustomizer(customizer -> customizer.authorizationRequestUri(uriBuilder -> { uriBuilder.queryParam("param1", "value1"); @@ -179,8 +179,8 @@ public class DefaultServerOAuth2AuthorizationRequestResolverTests { @Test public void resolveWhenAuthorizationRequestCustomizerOverridesParameterThenQueryIncludesParameter() { - when(this.clientRegistrationRepository.findByRegistrationId(any())) - .thenReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())); + given(this.clientRegistrationRepository.findByRegistrationId(any())) + .willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())); this.resolver.setAuthorizationRequestCustomizer(customizer -> customizer.parameters(params -> { params.put("appid", params.get("client_id")); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java index afaf4dd12f..1757e3778c 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java @@ -51,11 +51,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.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.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; /** @@ -130,19 +130,19 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests { @Test public void filterWhenMatchThenAuthorizedClientSaved() { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build(); - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(Mono.just(clientRegistration)); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration)); MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback"); OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration); - when(this.authorizationRequestRepository.loadAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); - when(this.authorizationRequestRepository.removeAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.loadAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); - when(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).thenReturn(Mono.empty()); - when(this.authenticationManager.authenticate(any())) - .thenReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated())); + given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty()); + given(this.authenticationManager.authenticate(any())) + .willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated())); MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest); MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse); @@ -159,10 +159,10 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests { @Test public void filterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed() { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build(); - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(Mono.just(clientRegistration)); - when(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).thenReturn(Mono.empty()); - when(this.authenticationManager.authenticate(any())) - .thenReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated())); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration)); + given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty()); + given(this.authenticationManager.authenticate(any())) + .willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated())); // 1) redirect_uri with query parameters Map parameters = new LinkedHashMap<>(); @@ -171,10 +171,10 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests { MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback", parameters); OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration); - when(this.authorizationRequestRepository.loadAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); - when(this.authorizationRequestRepository.removeAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.loadAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest); MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse); @@ -207,8 +207,8 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build(); OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration); - when(this.authorizationRequestRepository.loadAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.loadAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); // 1) Parameter value Map parametersNotMatch = new LinkedHashMap<>(parameters); @@ -245,18 +245,18 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests { @Test public void filterWhenAuthorizationSucceedsAndRequestCacheConfiguredThenRequestCacheUsed() { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build(); - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(Mono.just(clientRegistration)); - when(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).thenReturn(Mono.empty()); - when(this.authenticationManager.authenticate(any())) - .thenReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated())); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration)); + given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty()); + given(this.authenticationManager.authenticate(any())) + .willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated())); MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback"); OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration); - when(this.authorizationRequestRepository.loadAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); - when(this.authorizationRequestRepository.removeAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.loadAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest); MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse); @@ -264,8 +264,8 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests { Collections.emptyList()); ServerRequestCache requestCache = mock(ServerRequestCache.class); - when(requestCache.getRedirectUri(any(ServerWebExchange.class))) - .thenReturn(Mono.just(URI.create("/saved-request"))); + given(requestCache.getRedirectUri(any(ServerWebExchange.class))) + .willReturn(Mono.just(URI.create("/saved-request"))); this.filter.setRequestCache(requestCache); @@ -279,15 +279,15 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests { @Test public void filterWhenAuthenticationConverterThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build(); - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(Mono.empty()); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty()); MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback"); OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration); - when(this.authorizationRequestRepository.loadAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); - when(this.authorizationRequestRepository.removeAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.loadAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest); MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse); @@ -305,18 +305,18 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests { @Test public void filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() { ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build(); - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(Mono.just(clientRegistration)); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration)); MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback"); OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration); - when(this.authorizationRequestRepository.loadAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); - when(this.authorizationRequestRepository.removeAuthorizationRequest(any())) - .thenReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.loadAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); + given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) + .willReturn(Mono.just(oauth2AuthorizationRequest)); - when(this.authenticationManager.authenticate(any())) - .thenReturn(Mono.error(new OAuth2AuthorizationException(new OAuth2Error("authorization_error")))); + given(this.authenticationManager.authenticate(any())) + .willReturn(Mono.error(new OAuth2AuthorizationException(new OAuth2Error("authorization_error")))); MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest); MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java index c978fa1296..1675240178 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java @@ -39,9 +39,9 @@ import org.springframework.web.server.handler.FilteringWebHandler; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.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 @@ -73,9 +73,9 @@ public class OAuth2AuthorizationRequestRedirectWebFilterTests { Arrays.asList(this.filter)); this.client = WebTestClient.bindToWebHandler(webHandler).build(); - when(this.clientRepository.findByRegistrationId(this.registration.getRegistrationId())) - .thenReturn(Mono.just(this.registration)); - when(this.authzRequestRepository.saveAuthorizationRequest(any(), any())).thenReturn(Mono.empty()); + given(this.clientRepository.findByRegistrationId(this.registration.getRegistrationId())) + .willReturn(Mono.just(this.registration)); + given(this.authzRequestRepository.saveAuthorizationRequest(any(), any())).willReturn(Mono.empty()); } @Test @@ -135,7 +135,7 @@ public class OAuth2AuthorizationRequestRedirectWebFilterTests { @Test public void filterWhenExceptionThenSaveRequestSessionAttribute() { this.filter.setRequestCache(this.requestCache); - when(this.requestCache.saveRequest(any())).thenReturn(Mono.empty()); + given(this.requestCache.saveRequest(any())).willReturn(Mono.empty()); FilteringWebHandler webHandler = new FilteringWebHandler( e -> Mono.error(new ClientAuthorizationRequiredException(this.registration.getRegistrationId())), Arrays.asList(this.filter)); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java index 9b139c4a22..b08e068cfa 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java @@ -41,7 +41,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -84,7 +84,7 @@ public class ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests { @Test public void applyWhenAuthorizationRequestEmptyThenOAuth2AuthorizationException() { - when(this.authorizationRequestRepository.removeAuthorizationRequest(any())).thenReturn(Mono.empty()); + given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.empty()); assertThatThrownBy(() -> applyConverter()).isInstanceOf(OAuth2AuthorizationException.class); } @@ -92,8 +92,8 @@ public class ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests { @Test public void applyWhenAttributesMissingThenOAuth2AuthorizationException() { this.authorizationRequest.attributes(Map::clear); - when(this.authorizationRequestRepository.removeAuthorizationRequest(any())) - .thenReturn(Mono.just(this.authorizationRequest.build())); + given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) + .willReturn(Mono.just(this.authorizationRequest.build())); assertThatThrownBy(() -> applyConverter()).isInstanceOf(OAuth2AuthorizationException.class) .hasMessageContaining( @@ -102,9 +102,9 @@ public class ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests { @Test public void applyWhenClientRegistrationMissingThenOAuth2AuthorizationException() { - when(this.authorizationRequestRepository.removeAuthorizationRequest(any())) - .thenReturn(Mono.just(this.authorizationRequest.build())); - when(this.clientRegistrationRepository.findByRegistrationId(any())).thenReturn(Mono.empty()); + given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) + .willReturn(Mono.just(this.authorizationRequest.build())); + given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty()); assertThatThrownBy(() -> applyConverter()).isInstanceOf(OAuth2AuthorizationException.class) .hasMessageContaining( @@ -114,10 +114,10 @@ public class ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests { @Test public void applyWhenCodeParameterNotFoundThenErrorCode() { this.request.queryParam(OAuth2ParameterNames.ERROR, "error"); - when(this.authorizationRequestRepository.removeAuthorizationRequest(any())) - .thenReturn(Mono.just(this.authorizationRequest.build())); - when(this.clientRegistrationRepository.findByRegistrationId(any())) - .thenReturn(Mono.just(this.clientRegistration)); + given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) + .willReturn(Mono.just(this.authorizationRequest.build())); + given(this.clientRegistrationRepository.findByRegistrationId(any())) + .willReturn(Mono.just(this.clientRegistration)); assertThat(applyConverter().getAuthorizationExchange().getAuthorizationResponse().getError().getErrorCode()) .isEqualTo("error"); @@ -126,10 +126,10 @@ public class ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests { @Test public void applyWhenCodeParameterFoundThenCode() { this.request.queryParam(OAuth2ParameterNames.CODE, "code"); - when(this.authorizationRequestRepository.removeAuthorizationRequest(any())) - .thenReturn(Mono.just(this.authorizationRequest.build())); - when(this.clientRegistrationRepository.findByRegistrationId(any())) - .thenReturn(Mono.just(this.clientRegistration)); + given(this.authorizationRequestRepository.removeAuthorizationRequest(any())) + .willReturn(Mono.just(this.authorizationRequest.build())); + given(this.clientRegistrationRepository.findByRegistrationId(any())) + .willReturn(Mono.just(this.clientRegistration)); OAuth2AuthorizationCodeAuthenticationToken result = applyConverter(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionOAuth2ServerAuthorizationRequestRepositoryTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionOAuth2ServerAuthorizationRequestRepositoryTests.java index 9ca8a5302d..ddb447c74c 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionOAuth2ServerAuthorizationRequestRepositoryTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/WebSessionOAuth2ServerAuthorizationRequestRepositoryTests.java @@ -37,11 +37,11 @@ import org.springframework.web.server.session.WebSessionManager; 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.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -225,7 +225,7 @@ public class WebSessionOAuth2ServerAuthorizationRequestRepositoryTests { Map sessionAttrs = spy(new HashMap<>()); WebSession session = mock(WebSession.class); - when(session.getAttributes()).thenReturn(sessionAttrs); + given(session.getAttributes()).willReturn(sessionAttrs); WebSessionManager sessionManager = e -> Mono.just(session); this.exchange = new DefaultServerWebExchange(this.exchange.getRequest(), new MockServerHttpResponse(), diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilterTests.java index f151ed3285..64dfebf040 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilterTests.java @@ -44,8 +44,8 @@ import org.springframework.security.web.server.WebFilterExchange; import org.springframework.web.server.handler.DefaultWebFilterChain; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -75,7 +75,7 @@ public class OAuth2LoginAuthenticationWebFilterTests { this.authorizedClientRepository); this.webFilterExchange = new WebFilterExchange(MockServerWebExchange.from(MockServerHttpRequest.get("/")), new DefaultWebFilterChain(exchange -> exchange.getResponse().setComplete())); - when(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).thenReturn(Mono.empty()); + given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty()); } @Test diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DelegatingOAuth2TokenValidatorTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DelegatingOAuth2TokenValidatorTests.java index 621318f6a6..539a370999 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DelegatingOAuth2TokenValidatorTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DelegatingOAuth2TokenValidatorTests.java @@ -23,10 +23,10 @@ import org.junit.Test; 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.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for verifying {@link DelegatingOAuth2TokenValidator} @@ -50,8 +50,8 @@ public class DelegatingOAuth2TokenValidatorTests { OAuth2TokenValidator success = mock(OAuth2TokenValidator.class); OAuth2TokenValidator failure = mock(OAuth2TokenValidator.class); - when(success.validate(any(AbstractOAuth2Token.class))).thenReturn(OAuth2TokenValidatorResult.success()); - when(failure.validate(any(AbstractOAuth2Token.class))).thenReturn(OAuth2TokenValidatorResult.failure(DETAIL)); + given(success.validate(any(AbstractOAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success()); + given(failure.validate(any(AbstractOAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL)); DelegatingOAuth2TokenValidator tokenValidator = new DelegatingOAuth2TokenValidator<>( Arrays.asList(success, failure)); @@ -70,10 +70,10 @@ public class DelegatingOAuth2TokenValidatorTests { OAuth2Error otherDetail = new OAuth2Error("another-error"); - when(firstFailure.validate(any(AbstractOAuth2Token.class))) - .thenReturn(OAuth2TokenValidatorResult.failure(DETAIL)); - when(secondFailure.validate(any(AbstractOAuth2Token.class))) - .thenReturn(OAuth2TokenValidatorResult.failure(otherDetail)); + given(firstFailure.validate(any(AbstractOAuth2Token.class))) + .willReturn(OAuth2TokenValidatorResult.failure(DETAIL)); + given(secondFailure.validate(any(AbstractOAuth2Token.class))) + .willReturn(OAuth2TokenValidatorResult.failure(otherDetail)); DelegatingOAuth2TokenValidator tokenValidator = new DelegatingOAuth2TokenValidator<>( firstFailure, secondFailure); @@ -90,8 +90,8 @@ public class DelegatingOAuth2TokenValidatorTests { OAuth2TokenValidator firstSuccess = mock(OAuth2TokenValidator.class); OAuth2TokenValidator secondSuccess = mock(OAuth2TokenValidator.class); - when(firstSuccess.validate(any(AbstractOAuth2Token.class))).thenReturn(OAuth2TokenValidatorResult.success()); - when(secondSuccess.validate(any(AbstractOAuth2Token.class))).thenReturn(OAuth2TokenValidatorResult.success()); + given(firstSuccess.validate(any(AbstractOAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success()); + given(secondSuccess.validate(any(AbstractOAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success()); DelegatingOAuth2TokenValidator tokenValidator = new DelegatingOAuth2TokenValidator<>( Arrays.asList(firstSuccess, secondSuccess)); @@ -115,8 +115,8 @@ public class DelegatingOAuth2TokenValidatorTests { OAuth2TokenValidator firstSuccess = mock(OAuth2TokenValidator.class); OAuth2TokenValidator secondSuccess = mock(OAuth2TokenValidator.class); - when(firstSuccess.validate(any(AbstractOAuth2Token.class))).thenReturn(OAuth2TokenValidatorResult.success()); - when(secondSuccess.validate(any(AbstractOAuth2Token.class))).thenReturn(OAuth2TokenValidatorResult.success()); + given(firstSuccess.validate(any(AbstractOAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success()); + given(secondSuccess.validate(any(AbstractOAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success()); DelegatingOAuth2TokenValidator firstValidator = new DelegatingOAuth2TokenValidator<>( Arrays.asList(firstSuccess, secondSuccess)); diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverterTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverterTests.java index 85d88e928b..83141c1313 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverterTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverterTests.java @@ -38,8 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; 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 OAuth2AccessTokenResponseHttpMessageConverter}. @@ -146,7 +146,7 @@ public class OAuth2AccessTokenResponseHttpMessageConverterTests { @Test public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException() { Converter tokenResponseConverter = mock(Converter.class); - when(tokenResponseConverter.convert(any())).thenThrow(RuntimeException.class); + given(tokenResponseConverter.convert(any())).willThrow(RuntimeException.class); this.messageConverter.setTokenResponseConverter(tokenResponseConverter); String tokenResponse = "{}"; @@ -186,7 +186,7 @@ public class OAuth2AccessTokenResponseHttpMessageConverterTests { @Test public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException() { Converter tokenResponseParametersConverter = mock(Converter.class); - when(tokenResponseParametersConverter.convert(any())).thenThrow(RuntimeException.class); + given(tokenResponseParametersConverter.convert(any())).willThrow(RuntimeException.class); this.messageConverter.setTokenResponseParametersConverter(tokenResponseParametersConverter); OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234") diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2ErrorHttpMessageConverterTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2ErrorHttpMessageConverterTests.java index c2d4d952ad..6e916691dd 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2ErrorHttpMessageConverterTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/http/converter/OAuth2ErrorHttpMessageConverterTests.java @@ -29,8 +29,8 @@ import org.springframework.security.oauth2.core.OAuth2Error; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2ErrorHttpMessageConverter}. @@ -95,7 +95,7 @@ public class OAuth2ErrorHttpMessageConverterTests { @Test public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException() { Converter errorConverter = mock(Converter.class); - when(errorConverter.convert(any())).thenThrow(RuntimeException.class); + given(errorConverter.convert(any())).willThrow(RuntimeException.class); this.messageConverter.setErrorConverter(errorConverter); String errorResponse = "{}"; @@ -124,7 +124,7 @@ public class OAuth2ErrorHttpMessageConverterTests { @Test public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException() { Converter errorParametersConverter = mock(Converter.class); - when(errorParametersConverter.convert(any())).thenThrow(RuntimeException.class); + given(errorParametersConverter.convert(any())).willThrow(RuntimeException.class); this.messageConverter.setErrorParametersConverter(errorParametersConverter); OAuth2Error oauth2Error = new OAuth2Error("unauthorized_client", "The client is not authorized", diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverterTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverterTests.java index 49bf8f04ee..540f668e5e 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverterTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverterTests.java @@ -33,8 +33,8 @@ import org.springframework.core.convert.converter.Converter; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * Tests for {@link MappedJwtClaimSetConverter} @@ -47,7 +47,7 @@ public class MappedJwtClaimSetConverterTests { public void convertWhenUsingCustomExpiresAtConverterThenIssuedAtConverterStillConsultsIt() { Instant at = Instant.ofEpochMilli(1000000000000L); Converter expiresAtConverter = mock(Converter.class); - when(expiresAtConverter.convert(any())).thenReturn(at); + given(expiresAtConverter.convert(any())).willReturn(at); MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter .withDefaults(Collections.singletonMap(JwtClaimNames.EXP, expiresAtConverter)); @@ -115,7 +115,7 @@ public class MappedJwtClaimSetConverterTests { Converter claimConverter = mock(Converter.class); MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter .withDefaults(Collections.singletonMap(JwtClaimNames.SUB, claimConverter)); - when(claimConverter.convert(any(Object.class))).thenReturn("1234"); + given(claimConverter.convert(any(Object.class))).willReturn("1234"); Map source = new HashMap<>(); source.put(JwtClaimNames.JTI, 1); @@ -152,7 +152,7 @@ public class MappedJwtClaimSetConverterTests { Converter claimConverter = mock(Converter.class); MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter .withDefaults(Collections.singletonMap("custom-claim", claimConverter)); - when(claimConverter.convert(any())).thenReturn("custom-value"); + given(claimConverter.convert(any())).willReturn("custom-value"); Map source = new HashMap<>(); Map target = converter.convert(source); @@ -165,7 +165,7 @@ public class MappedJwtClaimSetConverterTests { Converter claimConverter = mock(Converter.class); MappedJwtClaimSetConverter converter = new MappedJwtClaimSetConverter( Collections.singletonMap(JwtClaimNames.SUB, claimConverter)); - when(claimConverter.convert(any(Object.class))).thenReturn("1234"); + given(claimConverter.convert(any(Object.class))).willReturn("1234"); Map source = new HashMap<>(); source.put(JwtClaimNames.JTI, new Object()); diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java index acf9a911ac..358f8bc99d 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java @@ -41,10 +41,10 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; import static org.assertj.core.api.AssertionsForClassTypes.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.spy; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link NimbusJwtDecoderJwkSupport}. @@ -180,7 +180,7 @@ public class NimbusJwtDecoderJwkSupportTests { OAuth2Error failure = new OAuth2Error("mock-error", "mock-description", "mock-uri"); OAuth2TokenValidator jwtValidator = mock(OAuth2TokenValidator.class); - when(jwtValidator.validate(any(Jwt.class))).thenReturn(OAuth2TokenValidatorResult.failure(failure)); + given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(failure)); decoder.setJwtValidator(jwtValidator); assertThatCode(() -> decoder.decode(SIGNED_JWT)).isInstanceOf(JwtValidationException.class) @@ -201,7 +201,7 @@ public class NimbusJwtDecoderJwkSupportTests { OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(firstFailure, secondFailure); OAuth2TokenValidator jwtValidator = mock(OAuth2TokenValidator.class); - when(jwtValidator.validate(any(Jwt.class))).thenReturn(result); + given(jwtValidator.validate(any(Jwt.class))).willReturn(result); decoder.setJwtValidator(jwtValidator); assertThatCode(() -> decoder.decode(SIGNED_JWT)).isInstanceOf(JwtValidationException.class) @@ -219,7 +219,7 @@ public class NimbusJwtDecoderJwkSupportTests { NimbusJwtDecoderJwkSupport decoder = new NimbusJwtDecoderJwkSupport(jwkSetUrl); Converter, Map> claimSetConverter = mock(Converter.class); - when(claimSetConverter.convert(any(Map.class))).thenReturn(Collections.singletonMap("custom", "value")); + given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value")); decoder.setClaimSetConverter(claimSetConverter); Jwt jwt = decoder.decode(SIGNED_JWT); @@ -235,8 +235,8 @@ public class NimbusJwtDecoderJwkSupportTests { private static RestOperations mockJwkSetResponse(String response) { RestOperations restOperations = mock(RestOperations.class); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))) - .thenReturn(new ResponseEntity<>(response, HttpStatus.OK)); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) + .willReturn(new ResponseEntity<>(response, HttpStatus.OK)); return restOperations; } diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java index 946c822d95..25a07fc930 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java @@ -80,11 +80,11 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; import static org.assertj.core.api.AssertionsForClassTypes.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.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withJwkSetUri; import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withPublicKey; import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withSecretKey; @@ -179,7 +179,7 @@ public class NimbusJwtDecoderTests { OAuth2Error failure = new OAuth2Error("mock-error", "mock-description", "mock-uri"); OAuth2TokenValidator jwtValidator = mock(OAuth2TokenValidator.class); - when(jwtValidator.validate(any(Jwt.class))).thenReturn(OAuth2TokenValidatorResult.failure(failure)); + given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(failure)); this.jwtDecoder.setJwtValidator(jwtValidator); assertThatCode(() -> this.jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtValidationException.class) @@ -193,7 +193,7 @@ public class NimbusJwtDecoderTests { OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(firstFailure, secondFailure); OAuth2TokenValidator jwtValidator = mock(OAuth2TokenValidator.class); - when(jwtValidator.validate(any(Jwt.class))).thenReturn(result); + given(jwtValidator.validate(any(Jwt.class))).willReturn(result); this.jwtDecoder.setJwtValidator(jwtValidator); assertThatCode(() -> this.jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtValidationException.class) @@ -210,7 +210,7 @@ public class NimbusJwtDecoderTests { OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri"); OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second"); OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2); - when(jwtValidator.validate(any(Jwt.class))).thenReturn(result); + given(jwtValidator.validate(any(Jwt.class))).willReturn(result); Assertions.assertThatCode(() -> this.jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtValidationException.class) .hasMessageContaining("mock-description"); @@ -219,7 +219,7 @@ public class NimbusJwtDecoderTests { @Test public void decodeWhenUsingSignedJwtThenReturnsClaimsGivenByClaimSetConverter() { Converter, Map> claimSetConverter = mock(Converter.class); - when(claimSetConverter.convert(any(Map.class))).thenReturn(Collections.singletonMap("custom", "value")); + given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value")); this.jwtDecoder.setClaimSetConverter(claimSetConverter); Jwt jwt = this.jwtDecoder.decode(SIGNED_JWT); @@ -233,7 +233,7 @@ public class NimbusJwtDecoderTests { Converter, Map> claimSetConverter = mock(Converter.class); this.jwtDecoder.setClaimSetConverter(claimSetConverter); - when(claimSetConverter.convert(any(Map.class))).thenThrow(new IllegalArgumentException("bad conversion")); + given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion")); assertThatCode(() -> this.jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(BadJwtException.class); } @@ -472,8 +472,8 @@ public class NimbusJwtDecoderTests { @Test public void decodeWhenJwkSetRequestedThenAcceptHeaderJsonAndJwkSetJson() { RestOperations restOperations = mock(RestOperations.class); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))) - .thenReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK)); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) + .willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK)); JWTProcessor processor = withJwkSetUri(JWK_SET_URI).restOperations(restOperations).processor(); NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(processor); jwtDecoder.decode(SIGNED_JWT); @@ -488,8 +488,8 @@ public class NimbusJwtDecoderTests { // given Cache cache = new ConcurrentMapCache("test-jwk-set-cache"); RestOperations restOperations = mock(RestOperations.class); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))) - .thenReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK)); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) + .willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK)); NimbusJwtDecoder jwtDecoder = withJwkSetUri(JWK_SET_URI).restOperations(restOperations).cache(cache).build(); // when jwtDecoder.decode(SIGNED_JWT); @@ -507,7 +507,7 @@ public class NimbusJwtDecoderTests { // given RestOperations restOperations = mock(RestOperations.class); Cache cache = mock(Cache.class); - when(cache.get(eq(JWK_SET_URI), any(Callable.class))).thenReturn(JWK_SET); + given(cache.get(eq(JWK_SET_URI), any(Callable.class))).willReturn(JWK_SET); NimbusJwtDecoder jwtDecoder = withJwkSetUri(JWK_SET_URI).cache(cache).restOperations(restOperations).build(); // when jwtDecoder.decode(SIGNED_JWT); @@ -522,8 +522,8 @@ public class NimbusJwtDecoderTests { // given Cache cache = new ConcurrentMapCache("test-jwk-set-cache"); RestOperations restOperations = mock(RestOperations.class); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))) - .thenThrow(new RestClientException("Cannot retrieve JWK Set")); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) + .willThrow(new RestClientException("Cannot retrieve JWK Set")); NimbusJwtDecoder jwtDecoder = withJwkSetUri(JWK_SET_URI).restOperations(restOperations).cache(cache).build(); // then assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtException.class) @@ -535,8 +535,8 @@ public class NimbusJwtDecoderTests { @Test public void withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws Exception { RestOperations restOperations = mock(RestOperations.class); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))) - .thenReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK)); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) + .willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK)); NimbusJwtDecoder jwtDecoder = withJwkSetUri(JWK_SET_URI).restOperations(restOperations) .jwtProcessorCustomizer( p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) @@ -580,8 +580,8 @@ public class NimbusJwtDecoderTests { private static JWTProcessor withSigning(String jwkResponse) { RestOperations restOperations = mock(RestOperations.class); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))) - .thenReturn(new ResponseEntity<>(jwkResponse, HttpStatus.OK)); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) + .willReturn(new ResponseEntity<>(jwkResponse, HttpStatus.OK)); return withJwkSetUri(JWK_SET_URI).restOperations(restOperations).processor(); } diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java index 28839446b8..99c4d04829 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java @@ -68,10 +68,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; 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.NimbusReactiveJwtDecoder.withJwkSetUri; import static org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder.withJwkSource; import static org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder.withPublicKey; @@ -214,7 +214,7 @@ public class NimbusReactiveJwtDecoderTests { OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri"); OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(error); - when(jwtValidator.validate(any(Jwt.class))).thenReturn(result); + given(jwtValidator.validate(any(Jwt.class))).willReturn(result); assertThatCode(() -> this.decoder.decode(this.messageReadToken).block()) .isInstanceOf(JwtValidationException.class).hasMessageContaining("mock-description"); @@ -229,7 +229,7 @@ public class NimbusReactiveJwtDecoderTests { OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri"); OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second"); OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2); - when(jwtValidator.validate(any(Jwt.class))).thenReturn(result); + given(jwtValidator.validate(any(Jwt.class))).willReturn(result); assertThatCode(() -> this.decoder.decode(this.messageReadToken).block()) .isInstanceOf(JwtValidationException.class).hasMessageContaining("mock-description"); @@ -240,7 +240,7 @@ public class NimbusReactiveJwtDecoderTests { Converter, Map> claimSetConverter = mock(Converter.class); this.decoder.setClaimSetConverter(claimSetConverter); - when(claimSetConverter.convert(any(Map.class))).thenReturn(Collections.singletonMap("custom", "value")); + given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value")); Jwt jwt = this.decoder.decode(this.messageReadToken).block(); assertThat(jwt.getClaims().size()).isEqualTo(1); @@ -254,7 +254,7 @@ public class NimbusReactiveJwtDecoderTests { Converter, Map> claimSetConverter = mock(Converter.class); this.decoder.setClaimSetConverter(claimSetConverter); - when(claimSetConverter.convert(any(Map.class))).thenThrow(new IllegalArgumentException("bad conversion")); + given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion")); assertThatCode(() -> this.decoder.decode(this.messageReadToken).block()).isInstanceOf(BadJwtException.class); } @@ -508,10 +508,10 @@ public class NimbusReactiveJwtDecoderTests { WebClient real = WebClient.builder().build(); WebClient.RequestHeadersUriSpec spec = spy(real.get()); WebClient webClient = spy(WebClient.class); - when(webClient.get()).thenReturn(spec); + given(webClient.get()).willReturn(spec); WebClient.ResponseSpec responseSpec = mock(WebClient.ResponseSpec.class); - when(responseSpec.bodyToMono(String.class)).thenReturn(Mono.just(response)); - when(spec.retrieve()).thenReturn(responseSpec); + given(responseSpec.bodyToMono(String.class)).willReturn(Mono.just(response)); + given(spec.retrieve()).willReturn(responseSpec); return webClient; } diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveRemoteJWKSourceTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveRemoteJWKSourceTests.java index e995feaef2..6a2960afee 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveRemoteJWKSourceTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveRemoteJWKSourceTests.java @@ -34,7 +34,7 @@ import org.mockito.junit.MockitoJUnitRunner; 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 @@ -81,7 +81,7 @@ public class ReactiveRemoteJWKSourceTests { @Test public void getWhenMultipleRequestThenCached() { - when(this.matcher.matches(any())).thenReturn(true); + given(this.matcher.matches(any())).willReturn(true); this.source.get(this.selector).block(); this.source.get(this.selector).block(); @@ -91,7 +91,7 @@ public class ReactiveRemoteJWKSourceTests { @Test public void getWhenMatchThenCreatesKeys() { - when(this.matcher.matches(any())).thenReturn(true); + given(this.matcher.matches(any())).willReturn(true); List keys = this.source.get(this.selector).block(); assertThat(keys).hasSize(2); @@ -110,8 +110,8 @@ public class ReactiveRemoteJWKSourceTests { @Test public void getWhenNoMatchAndNoKeyIdThenEmpty() { - when(this.matcher.matches(any())).thenReturn(false); - when(this.matcher.getKeyIDs()).thenReturn(Collections.emptySet()); + given(this.matcher.matches(any())).willReturn(false); + given(this.matcher.getKeyIDs()).willReturn(Collections.emptySet()); assertThat(this.source.get(this.selector).block()).isEmpty(); } @@ -119,8 +119,8 @@ public class ReactiveRemoteJWKSourceTests { @Test public void getWhenNoMatchAndKeyIdNotMatchThenRefreshAndFoundThenFound() { this.server.enqueue(new MockResponse().setBody(this.keys2)); - when(this.matcher.matches(any())).thenReturn(false, false, true); - when(this.matcher.getKeyIDs()).thenReturn(Collections.singleton("rotated")); + given(this.matcher.matches(any())).willReturn(false, false, true); + given(this.matcher.getKeyIDs()).willReturn(Collections.singleton("rotated")); List keys = this.source.get(this.selector).block(); @@ -131,8 +131,8 @@ public class ReactiveRemoteJWKSourceTests { @Test public void getWhenNoMatchAndKeyIdNotMatchThenRefreshAndNotFoundThenEmpty() { this.server.enqueue(new MockResponse().setBody(this.keys2)); - when(this.matcher.matches(any())).thenReturn(false, false, false); - when(this.matcher.getKeyIDs()).thenReturn(Collections.singleton("rotated")); + given(this.matcher.matches(any())).willReturn(false, false, false); + given(this.matcher.getKeyIDs()).willReturn(Collections.singleton("rotated")); List keys = this.source.get(this.selector).block(); @@ -141,8 +141,8 @@ public class ReactiveRemoteJWKSourceTests { @Test public void getWhenNoMatchAndKeyIdMatchThenEmpty() { - when(this.matcher.matches(any())).thenReturn(false); - when(this.matcher.getKeyIDs()).thenReturn(Collections.singleton("7ddf54d3032d1f0d48c3618892ca74c1ac30ad77")); + given(this.matcher.matches(any())).willReturn(false); + given(this.matcher.getKeyIDs()).willReturn(Collections.singleton("7ddf54d3032d1f0d48c3618892ca74c1ac30ad77")); assertThat(this.source.get(this.selector).block()).isEmpty(); } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java index 3fa0a85ff9..ca33f35c69 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java @@ -35,8 +35,8 @@ import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** @@ -67,8 +67,8 @@ public class JwtAuthenticationProviderTests { Jwt jwt = jwt().claim("name", "value").build(); - when(this.jwtDecoder.decode("token")).thenReturn(jwt); - when(this.jwtAuthenticationConverter.convert(jwt)).thenReturn(new JwtAuthenticationToken(jwt)); + given(this.jwtDecoder.decode("token")).willReturn(jwt); + given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(new JwtAuthenticationToken(jwt)); JwtAuthenticationToken authentication = (JwtAuthenticationToken) this.provider.authenticate(token); @@ -79,7 +79,7 @@ public class JwtAuthenticationProviderTests { public void authenticateWhenJwtDecodeFailsThenRespondsWithInvalidToken() { BearerTokenAuthenticationToken token = this.authentication(); - when(this.jwtDecoder.decode("token")).thenThrow(BadJwtException.class); + given(this.jwtDecoder.decode("token")).willThrow(BadJwtException.class); assertThatCode(() -> this.provider.authenticate(token)) .matches(failed -> failed instanceof OAuth2AuthenticationException) @@ -90,7 +90,7 @@ public class JwtAuthenticationProviderTests { public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGenericOne() { BearerTokenAuthenticationToken token = this.authentication(); - when(this.jwtDecoder.decode(token.getToken())).thenThrow(new BadJwtException("with \"invalid\" chars")); + given(this.jwtDecoder.decode(token.getToken())).willThrow(new BadJwtException("with \"invalid\" chars")); assertThatCode(() -> this.provider.authenticate(token)).isInstanceOf(OAuth2AuthenticationException.class) .hasFieldOrPropertyWithValue("error.description", "Invalid token"); @@ -101,7 +101,7 @@ public class JwtAuthenticationProviderTests { public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() { BearerTokenAuthenticationToken token = this.authentication(); - when(this.jwtDecoder.decode(token.getToken())).thenThrow(new JwtException("no jwk set")); + given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set")); assertThatCode(() -> this.provider.authenticate(token)).isInstanceOf(AuthenticationException.class) .isNotInstanceOf(OAuth2AuthenticationException.class); @@ -116,8 +116,8 @@ public class JwtAuthenticationProviderTests { Jwt jwt = jwt().build(); JwtAuthenticationToken authentication = new JwtAuthenticationToken(jwt); - when(this.jwtDecoder.decode(token.getToken())).thenReturn(jwt); - when(this.jwtAuthenticationConverter.convert(jwt)).thenReturn(authentication); + given(this.jwtDecoder.decode(token.getToken())).willReturn(jwt); + given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(authentication); assertThat(this.provider.authenticate(token)).isEqualTo(authentication).hasFieldOrPropertyWithValue("details", details); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java index 5764da170f..1289ad57b8 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java @@ -37,7 +37,7 @@ import org.springframework.security.oauth2.server.resource.BearerTokenAuthentica 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.Mockito.when; +import static org.mockito.BDDMockito.given; import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** @@ -77,7 +77,7 @@ public class JwtReactiveAuthenticationManagerTests { @Test public void authenticateWhenEmptyJwtThenEmpty() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); - when(this.jwtDecoder.decode(token.getToken())).thenReturn(Mono.empty()); + given(this.jwtDecoder.decode(token.getToken())).willReturn(Mono.empty()); assertThat(this.manager.authenticate(token).block()).isNull(); } @@ -85,7 +85,7 @@ public class JwtReactiveAuthenticationManagerTests { @Test public void authenticateWhenJwtExceptionThenOAuth2AuthenticationException() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); - when(this.jwtDecoder.decode(any())).thenReturn(Mono.error(new BadJwtException("Oops"))); + given(this.jwtDecoder.decode(any())).willReturn(Mono.error(new BadJwtException("Oops"))); assertThatCode(() -> this.manager.authenticate(token).block()) .isInstanceOf(OAuth2AuthenticationException.class); @@ -95,7 +95,7 @@ public class JwtReactiveAuthenticationManagerTests { @Test public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGenericOne() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); - when(this.jwtDecoder.decode(token.getToken())).thenThrow(new BadJwtException("with \"invalid\" chars")); + given(this.jwtDecoder.decode(token.getToken())).willThrow(new BadJwtException("with \"invalid\" chars")); assertThatCode(() -> this.manager.authenticate(token).block()).isInstanceOf(OAuth2AuthenticationException.class) .hasFieldOrPropertyWithValue("error.description", "Invalid token"); @@ -105,7 +105,7 @@ public class JwtReactiveAuthenticationManagerTests { @Test public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); - when(this.jwtDecoder.decode(token.getToken())).thenThrow(new JwtException("no jwk set")); + given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set")); assertThatCode(() -> this.manager.authenticate(token).block()).isInstanceOf(AuthenticationException.class) .isNotInstanceOf(OAuth2AuthenticationException.class); @@ -114,7 +114,7 @@ public class JwtReactiveAuthenticationManagerTests { @Test public void authenticateWhenNotJwtExceptionThenPropagates() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); - when(this.jwtDecoder.decode(any())).thenReturn(Mono.error(new RuntimeException("Oops"))); + given(this.jwtDecoder.decode(any())).willReturn(Mono.error(new RuntimeException("Oops"))); assertThatCode(() -> this.manager.authenticate(token).block()).isInstanceOf(RuntimeException.class); } @@ -122,7 +122,7 @@ public class JwtReactiveAuthenticationManagerTests { @Test public void authenticateWhenJwtThenSuccess() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); - when(this.jwtDecoder.decode(token.getToken())).thenReturn(Mono.just(this.jwt)); + given(this.jwtDecoder.decode(token.getToken())).willReturn(Mono.just(this.jwt)); Authentication authentication = this.manager.authenticate(token).block(); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java index 0609e5bba3..1f27b57b5e 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java @@ -35,8 +35,8 @@ import org.springframework.security.oauth2.server.resource.introspection.OpaqueT 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.Mockito.mock; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals.active; import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ACTIVE; import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.AUDIENCE; @@ -59,7 +59,7 @@ public class OpaqueTokenAuthenticationProviderTests { OAuth2AuthenticatedPrincipal principal = active( attributes -> attributes.put("extension_field", "twenty-seven")); OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class); - when(introspector.introspect(any())).thenReturn(principal); + given(introspector.introspect(any())).willReturn(principal); OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector); Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")); @@ -86,7 +86,7 @@ public class OpaqueTokenAuthenticationProviderTests { OAuth2AuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal( Collections.singletonMap("claim", "value"), null); OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class); - when(introspector.introspect(any())).thenReturn(principal); + given(introspector.introspect(any())).willReturn(principal); OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector); Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")); @@ -101,7 +101,7 @@ public class OpaqueTokenAuthenticationProviderTests { @Test public void authenticateWhenIntrospectionEndpointThrowsExceptionThenInvalidToken() { OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class); - when(introspector.introspect(any())).thenThrow(new OAuth2IntrospectionException("with \"invalid\" chars")); + given(introspector.introspect(any())).willThrow(new OAuth2IntrospectionException("with \"invalid\" chars")); OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector); assertThatCode(() -> provider.authenticate(new BearerTokenAuthenticationToken("token"))) diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java index c6d6297c72..8a498b3ec9 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java @@ -37,8 +37,8 @@ import org.springframework.security.oauth2.server.resource.introspection.Reactiv 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.Mockito.mock; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals.active; import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ACTIVE; import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.AUDIENCE; @@ -61,7 +61,7 @@ public class OpaqueTokenReactiveAuthenticationManagerTests { OAuth2AuthenticatedPrincipal authority = active( attributes -> attributes.put("extension_field", "twenty-seven")); ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class); - when(introspector.introspect(any())).thenReturn(Mono.just(authority)); + given(introspector.introspect(any())).willReturn(Mono.just(authority)); OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector); Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block(); @@ -88,7 +88,7 @@ public class OpaqueTokenReactiveAuthenticationManagerTests { OAuth2AuthenticatedPrincipal authority = new OAuth2IntrospectionAuthenticatedPrincipal( Collections.singletonMap("claim", "value"), null); ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class); - when(introspector.introspect(any())).thenReturn(Mono.just(authority)); + given(introspector.introspect(any())).willReturn(Mono.just(authority)); OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector); Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block(); @@ -103,8 +103,8 @@ public class OpaqueTokenReactiveAuthenticationManagerTests { @Test public void authenticateWhenIntrospectionEndpointThrowsExceptionThenInvalidToken() { ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class); - when(introspector.introspect(any())) - .thenReturn(Mono.error(new OAuth2IntrospectionException("with \"invalid\" chars"))); + given(introspector.introspect(any())) + .willReturn(Mono.error(new OAuth2IntrospectionException("with \"invalid\" chars"))); OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector); assertThatCode(() -> provider.authenticate(new BearerTokenAuthenticationToken("token")).block()) diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java index 5e33638382..7539acf13d 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java @@ -47,9 +47,9 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.AUDIENCE; import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.EXPIRES_AT; import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUER; @@ -145,7 +145,7 @@ public class NimbusOpaqueTokenIntrospectorTests { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))).thenReturn(INACTIVE); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INACTIVE); assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class) .extracting("message").isEqualTo("Provided token isn't active"); @@ -161,8 +161,8 @@ public class NimbusOpaqueTokenIntrospectorTests { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))) - .thenReturn(response(new JSONObject(introspectedValues).toJSONString())); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) + .willReturn(response(new JSONObject(introspectedValues).toJSONString())); OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token"); assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true) @@ -176,8 +176,8 @@ public class NimbusOpaqueTokenIntrospectorTests { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))) - .thenThrow(new IllegalStateException("server was unresponsive")); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) + .willThrow(new IllegalStateException("server was unresponsive")); assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class) .extracting("message").isEqualTo("server was unresponsive"); @@ -188,7 +188,7 @@ public class NimbusOpaqueTokenIntrospectorTests { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))).thenReturn(response("malformed")); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(response("malformed")); assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class); } @@ -198,7 +198,7 @@ public class NimbusOpaqueTokenIntrospectorTests { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))).thenReturn(INVALID); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INVALID); assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class); } @@ -208,7 +208,7 @@ public class NimbusOpaqueTokenIntrospectorTests { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))).thenReturn(MALFORMED_ISSUER); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_ISSUER); assertThatCode(() -> introspectionClient.introspect("token")).isInstanceOf(OAuth2IntrospectionException.class); } @@ -219,7 +219,7 @@ public class NimbusOpaqueTokenIntrospectorTests { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); - when(restOperations.exchange(any(RequestEntity.class), eq(String.class))).thenReturn(MALFORMED_SCOPE); + given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_SCOPE); OAuth2AuthenticatedPrincipal principal = introspectionClient.introspect("token"); assertThat(principal.getAuthorities()).isEmpty(); @@ -269,8 +269,8 @@ public class NimbusOpaqueTokenIntrospectorTests { Converter> requestEntityConverter = mock(Converter.class); RequestEntity requestEntity = mock(RequestEntity.class); String tokenToIntrospect = "some token"; - when(requestEntityConverter.convert(tokenToIntrospect)).thenReturn(requestEntity); - when(restOperations.exchange(requestEntity, String.class)).thenReturn(ACTIVE); + given(requestEntityConverter.convert(tokenToIntrospect)).willReturn(requestEntity); + given(restOperations.exchange(requestEntity, String.class)).willReturn(ACTIVE); NimbusOpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); introspectionClient.setRequestEntityConverter(requestEntityConverter); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java index 691d25454b..befa3bef92 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java @@ -42,9 +42,9 @@ import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; +import static org.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.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.AUDIENCE; import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.EXPIRES_AT; import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUER; @@ -216,15 +216,15 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests { WebClient real = WebClient.builder().build(); WebClient.RequestBodyUriSpec spec = spy(real.post()); WebClient webClient = spy(WebClient.class); - when(webClient.post()).thenReturn(spec); + given(webClient.post()).willReturn(spec); ClientResponse clientResponse = mock(ClientResponse.class); - when(clientResponse.rawStatusCode()).thenReturn(200); - when(clientResponse.statusCode()).thenReturn(HttpStatus.OK); - when(clientResponse.bodyToMono(String.class)).thenReturn(Mono.just(response)); + given(clientResponse.rawStatusCode()).willReturn(200); + given(clientResponse.statusCode()).willReturn(HttpStatus.OK); + given(clientResponse.bodyToMono(String.class)).willReturn(Mono.just(response)); ClientResponse.Headers headers = mock(ClientResponse.Headers.class); - when(headers.contentType()).thenReturn(Optional.of(MediaType.APPLICATION_JSON_UTF8)); - when(clientResponse.headers()).thenReturn(headers); - when(spec.exchange()).thenReturn(Mono.just(clientResponse)); + given(headers.contentType()).willReturn(Optional.of(MediaType.APPLICATION_JSON_UTF8)); + given(clientResponse.headers()).willReturn(headers); + given(spec.exchange()).willReturn(Mono.just(clientResponse)); return webClient; } @@ -232,8 +232,8 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests { WebClient real = WebClient.builder().build(); WebClient.RequestBodyUriSpec spec = spy(real.post()); WebClient webClient = spy(WebClient.class); - when(webClient.post()).thenReturn(spec); - when(spec.exchange()).thenThrow(t); + given(webClient.post()).willReturn(spec); + given(spec.exchange()).willThrow(t); return webClient; } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java index 0525260526..1427bde865 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilterTests.java @@ -43,9 +43,9 @@ import org.springframework.security.web.authentication.AuthenticationFailureHand 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.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; /** * Tests {@link BearerTokenAuthenticationFilterTests} @@ -85,7 +85,7 @@ public class BearerTokenAuthenticationFilterTests { @Test public void doFilterWhenBearerTokenPresentThenAuthenticates() throws ServletException, IOException { - when(this.bearerTokenResolver.resolve(this.request)).thenReturn("token"); + given(this.bearerTokenResolver.resolve(this.request)).willReturn("token"); BearerTokenAuthenticationFilter filter = addMocks( new BearerTokenAuthenticationFilter(this.authenticationManager)); @@ -104,8 +104,8 @@ public class BearerTokenAuthenticationFilterTests { BearerTokenAuthenticationFilter filter = addMocks( new BearerTokenAuthenticationFilter(this.authenticationManagerResolver)); - when(this.bearerTokenResolver.resolve(this.request)).thenReturn("token"); - when(this.authenticationManagerResolver.resolve(any())).thenReturn(this.authenticationManager); + given(this.bearerTokenResolver.resolve(this.request)).willReturn("token"); + given(this.authenticationManagerResolver.resolve(any())).willReturn(this.authenticationManager); filter.doFilter(this.request, this.response, this.filterChain); @@ -120,7 +120,7 @@ public class BearerTokenAuthenticationFilterTests { @Test public void doFilterWhenNoBearerTokenPresentThenDoesNotAuthenticate() throws ServletException, IOException { - when(this.bearerTokenResolver.resolve(this.request)).thenReturn(null); + given(this.bearerTokenResolver.resolve(this.request)).willReturn(null); dontAuthenticate(); } @@ -132,7 +132,7 @@ public class BearerTokenAuthenticationFilterTests { OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error); - when(this.bearerTokenResolver.resolve(this.request)).thenThrow(exception); + given(this.bearerTokenResolver.resolve(this.request)).willThrow(exception); dontAuthenticate(); @@ -147,8 +147,8 @@ public class BearerTokenAuthenticationFilterTests { OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error); - when(this.bearerTokenResolver.resolve(this.request)).thenReturn("token"); - when(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).thenThrow(exception); + given(this.bearerTokenResolver.resolve(this.request)).willReturn("token"); + given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).willThrow(exception); BearerTokenAuthenticationFilter filter = addMocks( new BearerTokenAuthenticationFilter(this.authenticationManager)); @@ -165,8 +165,8 @@ public class BearerTokenAuthenticationFilterTests { OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error); - when(this.bearerTokenResolver.resolve(this.request)).thenReturn("token"); - when(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).thenThrow(exception); + given(this.bearerTokenResolver.resolve(this.request)).willReturn("token"); + given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).willThrow(exception); BearerTokenAuthenticationFilter filter = addMocks( new BearerTokenAuthenticationFilter(this.authenticationManager)); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandlerTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandlerTests.java index 856028a968..272d7b9bbc 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandlerTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandlerTests.java @@ -34,8 +34,8 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class BearerTokenServerAccessDeniedHandlerTests { @@ -51,8 +51,8 @@ public class BearerTokenServerAccessDeniedHandlerTests { Authentication token = new TestingAuthenticationToken("user", "pass"); ServerWebExchange exchange = mock(ServerWebExchange.class); - when(exchange.getPrincipal()).thenReturn(Mono.just(token)); - when(exchange.getResponse()).thenReturn(new MockServerHttpResponse()); + given(exchange.getPrincipal()).willReturn(Mono.just(token)); + given(exchange.getResponse()).willReturn(new MockServerHttpResponse()); this.accessDeniedHandler.handle(exchange, null).block(); @@ -65,8 +65,8 @@ public class BearerTokenServerAccessDeniedHandlerTests { Authentication token = new TestingAuthenticationToken("user", "pass"); ServerWebExchange exchange = mock(ServerWebExchange.class); - when(exchange.getPrincipal()).thenReturn(Mono.just(token)); - when(exchange.getResponse()).thenReturn(new MockServerHttpResponse()); + given(exchange.getPrincipal()).willReturn(Mono.just(token)); + given(exchange.getResponse()).willReturn(new MockServerHttpResponse()); this.accessDeniedHandler.setRealmName("test"); this.accessDeniedHandler.handle(exchange, null).block(); @@ -81,8 +81,8 @@ public class BearerTokenServerAccessDeniedHandlerTests { Authentication token = new TestingOAuth2TokenAuthenticationToken(Collections.emptyMap()); ServerWebExchange exchange = mock(ServerWebExchange.class); - when(exchange.getPrincipal()).thenReturn(Mono.just(token)); - when(exchange.getResponse()).thenReturn(new MockServerHttpResponse()); + given(exchange.getPrincipal()).willReturn(Mono.just(token)); + given(exchange.getResponse()).willReturn(new MockServerHttpResponse()); this.accessDeniedHandler.handle(exchange, null).block(); diff --git a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java index aa7b8fa459..1bee6cb0cf 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java @@ -39,8 +39,8 @@ import org.springframework.mock.web.MockHttpServletRequest; 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; /** * @author Luke Taylor @@ -62,8 +62,8 @@ public class OpenID4JavaConsumerTests { AuthRequest authReq = mock(AuthRequest.class); DiscoveryInformation di = mock(DiscoveryInformation.class); - when(mgr.authenticate(any(DiscoveryInformation.class), any(), any())).thenReturn(authReq); - when(mgr.associate(any())).thenReturn(di); + given(mgr.authenticate(any(DiscoveryInformation.class), any(), any())).willReturn(authReq); + given(mgr.associate(any())).willReturn(di); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new MockAttributesFactory()); @@ -85,7 +85,7 @@ public class OpenID4JavaConsumerTests { public void discoveryExceptionRaisesOpenIDException() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); - when(mgr.discover(any())).thenThrow(new DiscoveryException("msg")); + given(mgr.discover(any())).willThrow(new DiscoveryException("msg")); consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); } @@ -94,8 +94,8 @@ public class OpenID4JavaConsumerTests { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); - when(mgr.authenticate(ArgumentMatchers.any(), any(), any())) - .thenThrow(new MessageException("msg"), new ConsumerException("msg")); + given(mgr.authenticate(ArgumentMatchers.any(), any(), any())) + .willThrow(new MessageException("msg"), new ConsumerException("msg")); try { consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); fail("OpenIDConsumerException was not thrown"); @@ -118,7 +118,7 @@ public class OpenID4JavaConsumerTests { VerificationResult vr = mock(VerificationResult.class); DiscoveryInformation di = mock(DiscoveryInformation.class); - when(mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))).thenReturn(vr); + given(mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))).willReturn(vr); MockHttpServletRequest request = new MockHttpServletRequest(); @@ -134,9 +134,8 @@ public class OpenID4JavaConsumerTests { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); - when(mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))) - .thenThrow(new MessageException("")).thenThrow(new AssociationException("")) - .thenThrow(new DiscoveryException("")); + given(mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))) + .willThrow(new MessageException(""), new AssociationException(""), new DiscoveryException("")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("x=5"); @@ -174,9 +173,9 @@ public class OpenID4JavaConsumerTests { Identifier id = (Identifier) () -> "id"; Message msg = mock(Message.class); - when(mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))).thenReturn(vr); - when(vr.getVerifiedId()).thenReturn(id); - when(vr.getAuthResponse()).thenReturn(msg); + given(mgr.verify(any(), any(ParameterList.class), any(DiscoveryInformation.class))).willReturn(vr); + given(vr.getVerifiedId()).willReturn(id); + given(vr.getAuthResponse()).willReturn(msg); MockHttpServletRequest request = new MockHttpServletRequest(); @@ -193,9 +192,9 @@ public class OpenID4JavaConsumerTests { OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(new NullAxFetchListFactory()); Message msg = mock(Message.class); FetchResponse fr = mock(FetchResponse.class); - when(msg.hasExtension(AxMessage.OPENID_NS_AX)).thenReturn(true); - when(msg.getExtension(AxMessage.OPENID_NS_AX)).thenReturn(fr); - when(fr.getAttributeValues("a")).thenReturn(Arrays.asList("x", "y")); + given(msg.hasExtension(AxMessage.OPENID_NS_AX)).willReturn(true); + given(msg.getExtension(AxMessage.OPENID_NS_AX)).willReturn(fr); + given(fr.getAttributeValues("a")).willReturn(Arrays.asList("x", "y")); List fetched = consumer.fetchAxAttributes(msg, this.attributes); @@ -208,9 +207,9 @@ public class OpenID4JavaConsumerTests { OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(new NullAxFetchListFactory()); Message msg = mock(Message.class); FetchResponse fr = mock(FetchResponse.class); - when(msg.hasExtension(AxMessage.OPENID_NS_AX)).thenReturn(true); - when(msg.getExtension(AxMessage.OPENID_NS_AX)).thenThrow(new MessageException("")); - when(fr.getAttributeValues("a")).thenReturn(Arrays.asList("x", "y")); + given(msg.hasExtension(AxMessage.OPENID_NS_AX)).willReturn(true); + given(msg.getExtension(AxMessage.OPENID_NS_AX)).willThrow(new MessageException("")); + given(fr.getAttributeValues("a")).willReturn(Arrays.asList("x", "y")); consumer.fetchAxAttributes(msg, this.attributes); } diff --git a/remoting/src/test/java/org/springframework/security/remoting/dns/JndiDnsResolverTests.java b/remoting/src/test/java/org/springframework/security/remoting/dns/JndiDnsResolverTests.java index 38659f0f57..470429ec38 100644 --- a/remoting/src/test/java/org/springframework/security/remoting/dns/JndiDnsResolverTests.java +++ b/remoting/src/test/java/org/springframework/security/remoting/dns/JndiDnsResolverTests.java @@ -28,8 +28,8 @@ import org.junit.Test; 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 Mike Wiesner @@ -49,14 +49,14 @@ public class JndiDnsResolverTests { this.context = mock(DirContext.class); this.dnsResolver = new JndiDnsResolver(); this.dnsResolver.setCtxFactory(this.contextFactory); - when(this.contextFactory.getCtx()).thenReturn(this.context); + given(this.contextFactory.getCtx()).willReturn(this.context); } @Test public void testResolveIpAddress() throws Exception { Attributes records = new BasicAttributes("A", "63.246.7.80"); - when(this.context.getAttributes("www.springsource.com", new String[] { "A" })).thenReturn(records); + given(this.context.getAttributes("www.springsource.com", new String[] { "A" })).willReturn(records); String ipAddress = this.dnsResolver.resolveIpAddress("www.springsource.com"); assertThat(ipAddress).isEqualTo("63.246.7.80"); @@ -64,8 +64,8 @@ public class JndiDnsResolverTests { @Test(expected = DnsEntryNotFoundException.class) public void testResolveIpAddressNotExisting() throws Exception { - when(this.context.getAttributes(any(String.class), any(String[].class))) - .thenThrow(new NameNotFoundException("not found")); + given(this.context.getAttributes(any(String.class), any(String[].class))) + .willThrow(new NameNotFoundException("not found")); this.dnsResolver.resolveIpAddress("notexisting.ansdansdugiuzgguzgioansdiandwq.foo"); } @@ -74,7 +74,7 @@ public class JndiDnsResolverTests { public void testResolveServiceEntry() throws Exception { BasicAttributes records = createSrvRecords(); - when(this.context.getAttributes("_ldap._tcp.springsource.com", new String[] { "SRV" })).thenReturn(records); + given(this.context.getAttributes("_ldap._tcp.springsource.com", new String[] { "SRV" })).willReturn(records); String hostname = this.dnsResolver.resolveServiceEntry("ldap", "springsource.com"); assertThat(hostname).isEqualTo("kdc.springsource.com"); @@ -82,8 +82,8 @@ public class JndiDnsResolverTests { @Test(expected = DnsEntryNotFoundException.class) public void testResolveServiceEntryNotExisting() throws Exception { - when(this.context.getAttributes(any(String.class), any(String[].class))) - .thenThrow(new NameNotFoundException("not found")); + given(this.context.getAttributes(any(String.class), any(String[].class))) + .willThrow(new NameNotFoundException("not found")); this.dnsResolver.resolveServiceEntry("wrong", "secpod.de"); } @@ -92,8 +92,8 @@ public class JndiDnsResolverTests { public void testResolveServiceIpAddress() throws Exception { BasicAttributes srvRecords = createSrvRecords(); BasicAttributes aRecords = new BasicAttributes("A", "63.246.7.80"); - when(this.context.getAttributes("_ldap._tcp.springsource.com", new String[] { "SRV" })).thenReturn(srvRecords); - when(this.context.getAttributes("kdc.springsource.com", new String[] { "A" })).thenReturn(aRecords); + given(this.context.getAttributes("_ldap._tcp.springsource.com", new String[] { "SRV" })).willReturn(srvRecords); + given(this.context.getAttributes("kdc.springsource.com", new String[] { "A" })).willReturn(aRecords); String ipAddress = this.dnsResolver.resolveServiceIpAddress("ldap", "springsource.com"); assertThat(ipAddress).isEqualTo("63.246.7.80"); @@ -101,8 +101,8 @@ public class JndiDnsResolverTests { @Test(expected = DnsLookupException.class) public void testUnknowError() throws Exception { - when(this.context.getAttributes(any(String.class), any(String[].class))) - .thenThrow(new NamingException("error")); + given(this.context.getAttributes(any(String.class), any(String[].class))) + .willThrow(new NamingException("error")); this.dnsResolver.resolveIpAddress(""); } diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java index f360bf1b2e..061d590faf 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/authentication/AuthenticationPayloadInterceptorTests.java @@ -55,9 +55,9 @@ import org.springframework.util.MimeTypeUtils; 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.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -84,7 +84,7 @@ public class AuthenticationPayloadInterceptorTests { AuthenticationPayloadInterceptor interceptor = new AuthenticationPayloadInterceptor(this.authenticationManager); PayloadExchange exchange = createExchange(); TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("user", "password"); - when(this.authenticationManager.authenticate(any())).thenReturn(Mono.just(expectedAuthentication)); + given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(expectedAuthentication)); AuthenticationPayloadInterceptorChain authenticationPayloadChain = new AuthenticationPayloadInterceptorChain(); interceptor.intercept(exchange, authenticationPayloadChain).block(); @@ -103,11 +103,11 @@ public class AuthenticationPayloadInterceptorTests { PayloadExchange exchange = createExchange(); TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("user", "password"); - when(this.authenticationManager.authenticate(any())).thenReturn(Mono.just(expectedAuthentication)); + given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(expectedAuthentication)); PublisherProbe voidResult = PublisherProbe.empty(); PayloadInterceptorChain chain = mock(PayloadInterceptorChain.class); - when(chain.next(any())).thenReturn(voidResult.mono()); + given(chain.next(any())).willReturn(voidResult.mono()); StepVerifier.create(interceptor.intercept(exchange, chain)) .then(() -> assertThat(voidResult.subscribeCount()).isEqualTo(1)).verifyComplete(); diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptorTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptorTests.java index 99f7de80f1..36f98b2189 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptorTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptorTests.java @@ -34,7 +34,7 @@ import org.springframework.security.rsocket.api.PayloadExchange; import org.springframework.security.rsocket.api.PayloadInterceptorChain; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; import static org.springframework.security.authorization.AuthenticatedReactiveAuthorizationManager.authenticated; import static org.springframework.security.authorization.AuthorityReactiveAuthorizationManager.hasRole; @@ -59,7 +59,7 @@ public class AuthorizationPayloadInterceptorTests { @Test public void interceptWhenAuthenticationEmptyAndSubscribedThenException() { - when(this.chain.next(any())).thenReturn(this.chainResult.mono()); + given(this.chain.next(any())).willReturn(this.chainResult.mono()); AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(authenticated()); @@ -70,8 +70,8 @@ public class AuthorizationPayloadInterceptorTests { @Test public void interceptWhenAuthenticationNotSubscribedAndEmptyThenCompletes() { - when(this.chain.next(any())).thenReturn(this.chainResult.mono()); - when(this.authorizationManager.verify(any(), any())).thenReturn(this.managerResult.mono()); + given(this.chain.next(any())).willReturn(this.chainResult.mono()); + given(this.authorizationManager.verify(any(), any())).willReturn(this.managerResult.mono()); AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(this.authorizationManager); @@ -81,7 +81,7 @@ public class AuthorizationPayloadInterceptorTests { @Test public void interceptWhenNotAuthorizedThenException() { - when(this.chain.next(any())).thenReturn(this.chainResult.mono()); + given(this.chain.next(any())).willReturn(this.chainResult.mono()); AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(hasRole("USER")); Context userContext = ReactiveSecurityContextHolder @@ -95,7 +95,7 @@ public class AuthorizationPayloadInterceptorTests { @Test public void interceptWhenAuthorizedThenContinues() { - when(this.chain.next(any())).thenReturn(this.chainResult.mono()); + given(this.chain.next(any())).willReturn(this.chainResult.mono()); AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(authenticated()); Context userContext = ReactiveSecurityContextHolder diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/authorization/PayloadExchangeMatcherReactiveAuthorizationManagerTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/authorization/PayloadExchangeMatcherReactiveAuthorizationManagerTests.java index 709ddfbf37..835a50c02b 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/authorization/PayloadExchangeMatcherReactiveAuthorizationManagerTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/authorization/PayloadExchangeMatcherReactiveAuthorizationManagerTests.java @@ -32,7 +32,7 @@ import org.springframework.security.rsocket.util.matcher.PayloadExchangeMatchers 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 @@ -52,7 +52,7 @@ public class PayloadExchangeMatcherReactiveAuthorizationManagerTests { @Test public void checkWhenGrantedThenGranted() { AuthorizationDecision expected = new AuthorizationDecision(true); - when(this.authz.check(any(), any())).thenReturn(Mono.just(expected)); + given(this.authz.check(any(), any())).willReturn(Mono.just(expected)); PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager .builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz)) .build(); @@ -63,7 +63,7 @@ public class PayloadExchangeMatcherReactiveAuthorizationManagerTests { @Test public void checkWhenDeniedThenDenied() { AuthorizationDecision expected = new AuthorizationDecision(false); - when(this.authz.check(any(), any())).thenReturn(Mono.just(expected)); + given(this.authz.check(any(), any())).willReturn(Mono.just(expected)); PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager .builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz)) .build(); @@ -74,7 +74,7 @@ public class PayloadExchangeMatcherReactiveAuthorizationManagerTests { @Test public void checkWhenFirstMatchThenSecondUsed() { AuthorizationDecision expected = new AuthorizationDecision(true); - when(this.authz.check(any(), any())).thenReturn(Mono.just(expected)); + given(this.authz.check(any(), any())).willReturn(Mono.just(expected)); PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager .builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz)) .add(new PayloadExchangeMatcherEntry<>(e -> PayloadExchangeMatcher.MatchResult.notMatch(), this.authz2)) @@ -86,7 +86,7 @@ public class PayloadExchangeMatcherReactiveAuthorizationManagerTests { @Test public void checkWhenSecondMatchThenSecondUsed() { AuthorizationDecision expected = new AuthorizationDecision(true); - when(this.authz2.check(any(), any())).thenReturn(Mono.just(expected)); + given(this.authz2.check(any(), any())).willReturn(Mono.just(expected)); PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager .builder() .add(new PayloadExchangeMatcherEntry<>(e -> PayloadExchangeMatcher.MatchResult.notMatch(), this.authz)) diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocketTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocketTests.java index 95ae4f08f7..f5aa79ab3b 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocketTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadInterceptorRSocketTests.java @@ -54,9 +54,9 @@ 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.ArgumentMatchers.eq; +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 @@ -117,8 +117,8 @@ public class PayloadInterceptorRSocketTests { @Test public void fireAndForgetWhenInterceptorCompletesThenDelegateSubscribed() { - when(this.interceptor.intercept(any(), any())).thenAnswer(withChainNext()); - when(this.delegate.fireAndForget(any())).thenReturn(this.voidResult.mono()); + given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext()); + given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono()); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); @@ -133,7 +133,7 @@ public class PayloadInterceptorRSocketTests { @Test public void fireAndForgetWhenInterceptorErrorsThenDelegateNotSubscribed() { RuntimeException expected = new RuntimeException("Oops"); - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.error(expected)); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected)); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); @@ -149,8 +149,8 @@ public class PayloadInterceptorRSocketTests { @Test public void fireAndForgetWhenSecurityContextThenDelegateContext() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password"); - when(this.interceptor.intercept(any(), any())).thenAnswer(withAuthenticated(authentication)); - when(this.delegate.fireAndForget(any())).thenReturn(Mono.empty()); + given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication)); + given(this.delegate.fireAndForget(any())).willReturn(Mono.empty()); RSocket assertAuthentication = new RSocketProxy(this.delegate) { @Override @@ -170,8 +170,8 @@ public class PayloadInterceptorRSocketTests { @Test public void requestResponseWhenInterceptorCompletesThenDelegateSubscribed() { - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.empty()); - when(this.delegate.requestResponse(any())).thenReturn(this.payloadResult.mono()); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty()); + given(this.delegate.requestResponse(any())).willReturn(this.payloadResult.mono()); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); @@ -188,7 +188,7 @@ public class PayloadInterceptorRSocketTests { @Test public void requestResponseWhenInterceptorErrorsThenDelegateNotInvoked() { RuntimeException expected = new RuntimeException("Oops"); - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.error(expected)); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected)); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); @@ -203,8 +203,8 @@ public class PayloadInterceptorRSocketTests { @Test public void requestResponseWhenSecurityContextThenDelegateContext() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password"); - when(this.interceptor.intercept(any(), any())).thenAnswer(withAuthenticated(authentication)); - when(this.delegate.requestResponse(any())).thenReturn(this.payloadResult.mono()); + given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication)); + given(this.delegate.requestResponse(any())).willReturn(this.payloadResult.mono()); RSocket assertAuthentication = new RSocketProxy(this.delegate) { @Override @@ -226,8 +226,8 @@ public class PayloadInterceptorRSocketTests { @Test public void requestStreamWhenInterceptorCompletesThenDelegateSubscribed() { - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.empty()); - when(this.delegate.requestStream(any())).thenReturn(this.payloadResult.flux()); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty()); + given(this.delegate.requestStream(any())).willReturn(this.payloadResult.flux()); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); @@ -242,7 +242,7 @@ public class PayloadInterceptorRSocketTests { @Test public void requestStreamWhenInterceptorErrorsThenDelegateNotSubscribed() { RuntimeException expected = new RuntimeException("Oops"); - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.error(expected)); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected)); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); @@ -258,8 +258,8 @@ public class PayloadInterceptorRSocketTests { @Test public void requestStreamWhenSecurityContextThenDelegateContext() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password"); - when(this.interceptor.intercept(any(), any())).thenAnswer(withAuthenticated(authentication)); - when(this.delegate.requestStream(any())).thenReturn(this.payloadResult.flux()); + given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication)); + given(this.delegate.requestStream(any())).willReturn(this.payloadResult.flux()); RSocket assertAuthentication = new RSocketProxy(this.delegate) { @Override @@ -280,8 +280,8 @@ public class PayloadInterceptorRSocketTests { @Test public void requestChannelWhenInterceptorCompletesThenDelegateSubscribed() { - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.empty()); - when(this.delegate.requestChannel(any())).thenReturn(this.payloadResult.flux()); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty()); + given(this.delegate.requestChannel(any())).willReturn(this.payloadResult.flux()); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); @@ -298,7 +298,7 @@ public class PayloadInterceptorRSocketTests { @Test public void requestChannelWhenInterceptorErrorsThenDelegateNotSubscribed() { RuntimeException expected = new RuntimeException("Oops"); - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.error(expected)); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected)); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); @@ -315,8 +315,8 @@ public class PayloadInterceptorRSocketTests { public void requestChannelWhenSecurityContextThenDelegateContext() { Mono payload = Mono.just(this.payload); TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password"); - when(this.interceptor.intercept(any(), any())).thenAnswer(withAuthenticated(authentication)); - when(this.delegate.requestChannel(any())).thenReturn(this.payloadResult.flux()); + given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication)); + given(this.delegate.requestChannel(any())).willReturn(this.payloadResult.flux()); RSocket assertAuthentication = new RSocketProxy(this.delegate) { @Override @@ -337,8 +337,8 @@ public class PayloadInterceptorRSocketTests { @Test public void metadataPushWhenInterceptorCompletesThenDelegateSubscribed() { - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.empty()); - when(this.delegate.metadataPush(any())).thenReturn(this.voidResult.mono()); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty()); + given(this.delegate.metadataPush(any())).willReturn(this.voidResult.mono()); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); @@ -353,7 +353,7 @@ public class PayloadInterceptorRSocketTests { @Test public void metadataPushWhenInterceptorErrorsThenDelegateNotSubscribed() { RuntimeException expected = new RuntimeException("Oops"); - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.error(expected)); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected)); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType); @@ -368,8 +368,8 @@ public class PayloadInterceptorRSocketTests { @Test public void metadataPushWhenSecurityContextThenDelegateContext() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password"); - when(this.interceptor.intercept(any(), any())).thenAnswer(withAuthenticated(authentication)); - when(this.delegate.metadataPush(any())).thenReturn(this.voidResult.mono()); + given(this.interceptor.intercept(any(), any())).willAnswer(withAuthenticated(authentication)); + given(this.delegate.metadataPush(any())).willReturn(this.voidResult.mono()); RSocket assertAuthentication = new RSocketProxy(this.delegate) { @Override @@ -392,9 +392,9 @@ public class PayloadInterceptorRSocketTests { @Test public void fireAndForgetWhenInterceptorsCompleteThenDelegateInvoked() { - when(this.interceptor.intercept(any(), any())).thenAnswer(withChainNext()); - when(this.interceptor2.intercept(any(), any())).thenAnswer(withChainNext()); - when(this.delegate.fireAndForget(any())).thenReturn(this.voidResult.mono()); + given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext()); + given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext()); + given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono()); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType); @@ -408,9 +408,9 @@ public class PayloadInterceptorRSocketTests { @Test public void fireAndForgetWhenInterceptorsMutatesPayloadThenDelegateInvoked() { - when(this.interceptor.intercept(any(), any())).thenAnswer(withChainNext()); - when(this.interceptor2.intercept(any(), any())).thenAnswer(withChainNext()); - when(this.delegate.fireAndForget(any())).thenReturn(this.voidResult.mono()); + given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext()); + given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext()); + given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono()); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType); @@ -427,7 +427,7 @@ public class PayloadInterceptorRSocketTests { @Test public void fireAndForgetWhenInterceptor1ErrorsThenInterceptor2AndDelegateNotInvoked() { RuntimeException expected = new RuntimeException("Oops"); - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.error(expected)); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected)); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType); @@ -443,8 +443,8 @@ public class PayloadInterceptorRSocketTests { @Test public void fireAndForgetWhenInterceptor2ErrorsThenInterceptor2AndDelegateNotInvoked() { RuntimeException expected = new RuntimeException("Oops"); - when(this.interceptor.intercept(any(), any())).thenAnswer(withChainNext()); - when(this.interceptor2.intercept(any(), any())).thenReturn(Mono.error(expected)); + given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext()); + given(this.interceptor2.intercept(any(), any())).willReturn(Mono.error(expected)); PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType); diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorInterceptorTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorInterceptorTests.java index 3212bd1ae8..a20686ba3e 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorInterceptorTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorInterceptorTests.java @@ -38,9 +38,9 @@ import org.springframework.security.rsocket.api.PayloadInterceptor; 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; /** * @author Rob Winch @@ -75,7 +75,7 @@ public class PayloadSocketAcceptorInterceptorTests { @Test public void applyWhenDefaultMetadataMimeTypeThenDefaulted() { - when(this.setupPayload.dataMimeType()).thenReturn(MediaType.APPLICATION_JSON_VALUE); + given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE); PayloadExchange exchange = captureExchange(); @@ -87,7 +87,7 @@ public class PayloadSocketAcceptorInterceptorTests { @Test public void acceptWhenDefaultMetadataMimeTypeOverrideThenDefaulted() { this.acceptorInterceptor.setDefaultMetadataMimeType(MediaType.APPLICATION_JSON); - when(this.setupPayload.dataMimeType()).thenReturn(MediaType.APPLICATION_JSON_VALUE); + given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE); PayloadExchange exchange = captureExchange(); @@ -107,15 +107,15 @@ public class PayloadSocketAcceptorInterceptorTests { } private PayloadExchange captureExchange() { - when(this.socketAcceptor.accept(any(), any())).thenReturn(Mono.just(this.rSocket)); - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.empty()); + given(this.socketAcceptor.accept(any(), any())).willReturn(Mono.just(this.rSocket)); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty()); SocketAcceptor wrappedAcceptor = this.acceptorInterceptor.apply(this.socketAcceptor); RSocket result = wrappedAcceptor.accept(this.setupPayload, this.rSocket).block(); assertThat(result).isInstanceOf(PayloadInterceptorRSocket.class); - when(this.rSocket.fireAndForget(any())).thenReturn(Mono.empty()); + given(this.rSocket.fireAndForget(any())).willReturn(Mono.empty()); result.fireAndForget(this.payload).block(); diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorTests.java index 0c695fef6d..0f61bf4853 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/core/PayloadSocketAcceptorTests.java @@ -45,9 +45,9 @@ import org.springframework.security.rsocket.api.PayloadInterceptor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.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; /** * @author Rob Winch @@ -106,7 +106,7 @@ public class PayloadSocketAcceptorTests { @Test public void acceptWhenDefaultMetadataMimeTypeThenDefaulted() { - when(this.setupPayload.dataMimeType()).thenReturn(MediaType.APPLICATION_JSON_VALUE); + given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE); PayloadExchange exchange = captureExchange(); @@ -118,7 +118,7 @@ public class PayloadSocketAcceptorTests { @Test public void acceptWhenDefaultMetadataMimeTypeOverrideThenDefaulted() { this.acceptor.setDefaultMetadataMimeType(MediaType.APPLICATION_JSON); - when(this.setupPayload.dataMimeType()).thenReturn(MediaType.APPLICATION_JSON_VALUE); + given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE); PayloadExchange exchange = captureExchange(); @@ -139,8 +139,8 @@ public class PayloadSocketAcceptorTests { @Test public void acceptWhenExplicitMimeTypeThenThenOverrideDefault() { - when(this.setupPayload.metadataMimeType()).thenReturn(MediaType.TEXT_PLAIN_VALUE); - when(this.setupPayload.dataMimeType()).thenReturn(MediaType.APPLICATION_JSON_VALUE); + given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE); + given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE); PayloadExchange exchange = captureExchange(); @@ -151,8 +151,8 @@ public class PayloadSocketAcceptorTests { @Test // gh-8654 public void acceptWhenDelegateAcceptRequiresReactiveSecurityContext() { - when(this.setupPayload.metadataMimeType()).thenReturn(MediaType.TEXT_PLAIN_VALUE); - when(this.setupPayload.dataMimeType()).thenReturn(MediaType.APPLICATION_JSON_VALUE); + given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE); + given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE); SecurityContext expectedSecurityContext = new SecurityContextImpl( new TestingAuthenticationToken("user", "password", "ROLE_USER")); CaptureSecurityContextSocketAcceptor captureSecurityContext = new CaptureSecurityContextSocketAcceptor( @@ -171,14 +171,14 @@ public class PayloadSocketAcceptorTests { } private PayloadExchange captureExchange() { - when(this.delegate.accept(any(), any())).thenReturn(Mono.just(this.rSocket)); - when(this.interceptor.intercept(any(), any())).thenReturn(Mono.empty()); + given(this.delegate.accept(any(), any())).willReturn(Mono.just(this.rSocket)); + given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty()); RSocket result = this.acceptor.accept(this.setupPayload, this.rSocket).block(); assertThat(result).isInstanceOf(PayloadInterceptorRSocket.class); - when(this.rSocket.fireAndForget(any())).thenReturn(Mono.empty()); + given(this.rSocket.fireAndForget(any())).willReturn(Mono.empty()); result.fireAndForget(this.payload).block(); diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/util/matcher/RoutePayloadExchangeMatcherTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/util/matcher/RoutePayloadExchangeMatcherTests.java index 6ecd661eb0..747e6e2c8a 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/util/matcher/RoutePayloadExchangeMatcherTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/util/matcher/RoutePayloadExchangeMatcherTests.java @@ -38,7 +38,7 @@ import org.springframework.util.RouteMatcher; 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 @@ -77,7 +77,7 @@ public class RoutePayloadExchangeMatcherTests { @Test public void matchesWhenNoRouteThenNotMatch() { - when(this.metadataExtractor.extract(any(), any())).thenReturn(Collections.emptyMap()); + given(this.metadataExtractor.extract(any(), any())).willReturn(Collections.emptyMap()); PayloadExchangeMatcher.MatchResult result = this.matcher.matches(this.exchange).block(); assertThat(result.isMatch()).isFalse(); } @@ -85,8 +85,8 @@ public class RoutePayloadExchangeMatcherTests { @Test public void matchesWhenNotMatchThenNotMatch() { String route = "route"; - when(this.metadataExtractor.extract(any(), any())) - .thenReturn(Collections.singletonMap(MetadataExtractor.ROUTE_KEY, route)); + given(this.metadataExtractor.extract(any(), any())) + .willReturn(Collections.singletonMap(MetadataExtractor.ROUTE_KEY, route)); PayloadExchangeMatcher.MatchResult result = this.matcher.matches(this.exchange).block(); assertThat(result.isMatch()).isFalse(); } @@ -94,10 +94,10 @@ public class RoutePayloadExchangeMatcherTests { @Test public void matchesWhenMatchAndNoVariablesThenMatch() { String route = "route"; - when(this.metadataExtractor.extract(any(), any())) - .thenReturn(Collections.singletonMap(MetadataExtractor.ROUTE_KEY, route)); - when(this.routeMatcher.parseRoute(any())).thenReturn(this.route); - when(this.routeMatcher.matchAndExtract(any(), any())).thenReturn(Collections.emptyMap()); + given(this.metadataExtractor.extract(any(), any())) + .willReturn(Collections.singletonMap(MetadataExtractor.ROUTE_KEY, route)); + given(this.routeMatcher.parseRoute(any())).willReturn(this.route); + given(this.routeMatcher.matchAndExtract(any(), any())).willReturn(Collections.emptyMap()); PayloadExchangeMatcher.MatchResult result = this.matcher.matches(this.exchange).block(); assertThat(result.isMatch()).isTrue(); } @@ -106,10 +106,10 @@ public class RoutePayloadExchangeMatcherTests { public void matchesWhenMatchAndVariablesThenMatchAndVariables() { String route = "route"; Map variables = Collections.singletonMap("a", "b"); - when(this.metadataExtractor.extract(any(), any())) - .thenReturn(Collections.singletonMap(MetadataExtractor.ROUTE_KEY, route)); - when(this.routeMatcher.parseRoute(any())).thenReturn(this.route); - when(this.routeMatcher.matchAndExtract(any(), any())).thenReturn(variables); + given(this.metadataExtractor.extract(any(), any())) + .willReturn(Collections.singletonMap(MetadataExtractor.ROUTE_KEY, route)); + given(this.routeMatcher.parseRoute(any())).willReturn(this.route); + given(this.routeMatcher.matchAndExtract(any(), any())).willReturn(variables); PayloadExchangeMatcher.MatchResult result = this.matcher.matches(this.exchange).block(); assertThat(result.isMatch()).isTrue(); assertThat(result.getVariables()).containsAllEntriesOf(variables); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.java index 9480471a73..3927cd2c6b 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.java @@ -28,6 +28,8 @@ import java.util.function.Consumer; import java.util.function.Function; import org.springframework.security.saml2.core.Saml2X509Credential; +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.AssertingPartyDetails; +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.ProviderDetails; import org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter; import org.springframework.util.Assert; diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java index c9356536a7..b6081da1c3 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java @@ -69,10 +69,10 @@ import static java.util.Collections.singleton; 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.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getBuilderFactory; import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getMarshallerFactory; import static org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS; @@ -260,7 +260,7 @@ public class OpenSamlAuthenticationProviderTests { Element attributeElement = element("value"); Marshaller marshaller = mock(Marshaller.class); - when(marshaller.marshall(any(XMLObject.class))).thenReturn(attributeElement); + given(marshaller.marshall(any(XMLObject.class))).willReturn(attributeElement); try { XMLObjectProviderRegistrySupport.getMarshallerFactory() @@ -375,9 +375,9 @@ public class OpenSamlAuthenticationProviderTests { response.getAssertions().add(assertion); signed(response, assertingPartySigningCredential(), ASSERTING_PARTY_ENTITY_ID); Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); - when(validator.getServicedCondition()).thenReturn(OneTimeUse.DEFAULT_ELEMENT_NAME); - when(validator.validate(any(Condition.class), any(Assertion.class), any(ValidationContext.class))) - .thenReturn(ValidationResult.VALID); + given(validator.getServicedCondition()).willReturn(OneTimeUse.DEFAULT_ELEMENT_NAME); + given(validator.validate(any(Condition.class), any(Assertion.class), any(ValidationContext.class))) + .willReturn(ValidationResult.VALID); provider.authenticate(token); verify(validator).validate(any(Condition.class), any(Assertion.class), any(ValidationContext.class)); } @@ -388,7 +388,7 @@ public class OpenSamlAuthenticationProviderTests { parameters.put(SC_VALID_RECIPIENTS, singleton(DESTINATION)); parameters.put(SIGNATURE_REQUIRED, false); ValidationContext context = mock(ValidationContext.class); - when(context.getStaticParameters()).thenReturn(parameters); + given(context.getStaticParameters()).willReturn(parameters); OpenSamlAuthenticationProvider provider = new OpenSamlAuthenticationProvider(); provider.setValidationContextConverter(tuple -> context); Response response = response(); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java index a3962b07ee..1ec40b8fd2 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java @@ -39,9 +39,9 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.hamcrest.CoreMatchers.containsString; +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.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getParserPool; import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getUnmarshallerFactory; import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.relyingPartySigningCredential; @@ -170,7 +170,7 @@ public class OpenSamlAuthenticationRequestFactoryTests { public void createPostAuthenticationRequestWhenAuthnRequestConsumerThenUses() { Function> authnRequestConsumerResolver = mock( Function.class); - when(authnRequestConsumerResolver.apply(this.context)).thenReturn(authnRequest -> { + given(authnRequestConsumerResolver.apply(this.context)).willReturn(authnRequest -> { }); this.factory.setAuthnRequestConsumerResolver(authnRequestConsumerResolver); @@ -182,7 +182,7 @@ public class OpenSamlAuthenticationRequestFactoryTests { public void createRedirectAuthenticationRequestWhenAuthnRequestConsumerThenUses() { Function> authnRequestConsumerResolver = mock( Function.class); - when(authnRequestConsumerResolver.apply(this.context)).thenReturn(authnRequest -> { + given(authnRequestConsumerResolver.apply(this.context)).willReturn(authnRequest -> { }); this.factory.setAuthnRequestConsumerResolver(authnRequestConsumerResolver); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java index 2127ca11a4..25d7f416aa 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java @@ -31,8 +31,8 @@ import org.springframework.security.saml2.provider.service.registration.RelyingP import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class Saml2WebSsoAuthenticationFilterTests { @@ -81,7 +81,7 @@ public class Saml2WebSsoAuthenticationFilterTests { @Test public void attemptAuthenticationWhenRegistrationIdDoesNotExistThenThrowsException() { - when(this.repository.findByRegistrationId("non-existent-id")).thenReturn(null); + given(this.repository.findByRegistrationId("non-existent-id")).willReturn(null); this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/some/other/path/{registrationId}"); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java index 6526829196..69368eec00 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java @@ -38,10 +38,10 @@ import org.springframework.web.util.UriUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.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.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.assertingPartyPrivateCredential; import static org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationRequestContexts.authenticationRequestContext; import static org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding.POST; @@ -83,14 +83,14 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { @Test public void doFilterWhenNoRelayStateThenRedirectDoesNotContainParameter() throws ServletException, IOException { - when(this.repository.findByRegistrationId("registration-id")).thenReturn(this.rpBuilder.build()); + given(this.repository.findByRegistrationId("registration-id")).willReturn(this.rpBuilder.build()); this.filter.doFilterInternal(this.request, this.response, this.filterChain); assertThat(this.response.getHeader("Location")).doesNotContain("RelayState=").startsWith(IDP_SSO_URL); } @Test public void doFilterWhenRelayStateThenRedirectDoesContainParameter() throws ServletException, IOException { - when(this.repository.findByRegistrationId("registration-id")).thenReturn(this.rpBuilder.build()); + given(this.repository.findByRegistrationId("registration-id")).willReturn(this.rpBuilder.build()); this.request.setParameter("RelayState", "my-relay-state"); this.filter.doFilterInternal(this.request, this.response, this.filterChain); assertThat(this.response.getHeader("Location")).contains("RelayState=my-relay-state").startsWith(IDP_SSO_URL); @@ -98,7 +98,7 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { @Test public void doFilterWhenRelayStateThatRequiresEncodingThenRedirectDoesContainsEncodedParameter() throws Exception { - when(this.repository.findByRegistrationId("registration-id")).thenReturn(this.rpBuilder.build()); + given(this.repository.findByRegistrationId("registration-id")).willReturn(this.rpBuilder.build()); final String relayStateValue = "https://my-relay-state.example.com?with=param&other=param"; final String relayStateEncoded = UriUtils.encode(relayStateValue, StandardCharsets.ISO_8859_1); this.request.setParameter("RelayState", relayStateValue); @@ -109,7 +109,7 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { @Test public void doFilterWhenSimpleSignatureSpecifiedThenSignatureParametersAreInTheRedirectURL() throws Exception { - when(this.repository.findByRegistrationId("registration-id")).thenReturn(this.rpBuilder.build()); + given(this.repository.findByRegistrationId("registration-id")).willReturn(this.rpBuilder.build()); final String relayStateValue = "https://my-relay-state.example.com?with=param&other=param"; final String relayStateEncoded = UriUtils.encode(relayStateValue, StandardCharsets.ISO_8859_1); this.request.setParameter("RelayState", relayStateValue); @@ -120,8 +120,8 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { @Test public void doFilterWhenSignatureIsDisabledThenSignatureParametersAreNotInTheRedirectURL() throws Exception { - when(this.repository.findByRegistrationId("registration-id")) - .thenReturn(this.rpBuilder.providerDetails(c -> c.signAuthNRequest(false)).build()); + given(this.repository.findByRegistrationId("registration-id")) + .willReturn(this.rpBuilder.providerDetails(c -> c.signAuthNRequest(false)).build()); final String relayStateValue = "https://my-relay-state.example.com?with=param&other=param"; final String relayStateEncoded = UriUtils.encode(relayStateValue, StandardCharsets.ISO_8859_1); this.request.setParameter("RelayState", relayStateValue); @@ -132,8 +132,8 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { @Test public void doFilterWhenPostFormDataIsPresent() throws Exception { - when(this.repository.findByRegistrationId("registration-id")) - .thenReturn(this.rpBuilder.providerDetails(c -> c.binding(POST)).build()); + given(this.repository.findByRegistrationId("registration-id")) + .willReturn(this.rpBuilder.providerDetails(c -> c.binding(POST)).build()); final String relayStateValue = "https://my-relay-state.example.com?with=param&other=param&javascript{alert('1');}"; final String relayStateEncoded = HtmlUtils.htmlEscape(relayStateValue); this.request.setParameter("RelayState", relayStateValue); @@ -149,11 +149,11 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { public void doFilterWhenSetAuthenticationRequestFactoryThenUses() throws Exception { RelyingPartyRegistration relyingParty = this.rpBuilder.providerDetails(c -> c.binding(POST)).build(); Saml2PostAuthenticationRequest authenticationRequest = mock(Saml2PostAuthenticationRequest.class); - when(authenticationRequest.getAuthenticationRequestUri()).thenReturn("uri"); - when(authenticationRequest.getRelayState()).thenReturn("relay"); - when(authenticationRequest.getSamlRequest()).thenReturn("saml"); - when(this.repository.findByRegistrationId("registration-id")).thenReturn(relyingParty); - when(this.factory.createPostAuthenticationRequest(any())).thenReturn(authenticationRequest); + given(authenticationRequest.getAuthenticationRequestUri()).willReturn("uri"); + given(authenticationRequest.getRelayState()).willReturn("relay"); + given(authenticationRequest.getSamlRequest()).willReturn("saml"); + given(this.repository.findByRegistrationId("registration-id")).willReturn(relyingParty); + given(this.factory.createPostAuthenticationRequest(any())).willReturn(authenticationRequest); Saml2WebSsoAuthenticationRequestFilter filter = new Saml2WebSsoAuthenticationRequestFilter(this.repository); filter.setAuthenticationRequestFactory(this.factory); @@ -168,12 +168,12 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { public void doFilterWhenCustomAuthenticationRequestFactoryThenUses() throws Exception { RelyingPartyRegistration relyingParty = this.rpBuilder.providerDetails(c -> c.binding(POST)).build(); Saml2PostAuthenticationRequest authenticationRequest = mock(Saml2PostAuthenticationRequest.class); - when(authenticationRequest.getAuthenticationRequestUri()).thenReturn("uri"); - when(authenticationRequest.getRelayState()).thenReturn("relay"); - when(authenticationRequest.getSamlRequest()).thenReturn("saml"); - when(this.resolver.resolve(this.request)) - .thenReturn(authenticationRequestContext().relyingPartyRegistration(relyingParty).build()); - when(this.factory.createPostAuthenticationRequest(any())).thenReturn(authenticationRequest); + given(authenticationRequest.getAuthenticationRequestUri()).willReturn("uri"); + given(authenticationRequest.getRelayState()).willReturn("relay"); + given(authenticationRequest.getSamlRequest()).willReturn("saml"); + given(this.resolver.resolve(this.request)) + .willReturn(authenticationRequestContext().relyingPartyRegistration(relyingParty).build()); + given(this.factory.createPostAuthenticationRequest(any())).willReturn(authenticationRequest); Saml2WebSsoAuthenticationRequestFilter filter = new Saml2WebSsoAuthenticationRequestFilter(this.resolver, this.factory); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java index 1de923bed4..a653845697 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java @@ -39,7 +39,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; 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.Mockito.when; +import static org.mockito.BDDMockito.given; import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.relyingPartyRegistration; @RunWith(MockitoJUnitRunner.class) @@ -54,8 +54,8 @@ public class Saml2AuthenticationTokenConverterTests { public void convertWhenSamlResponseThenToken() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); - when(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))) - .thenReturn(this.relyingPartyRegistration); + given(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))) + .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("SAMLResponse", Saml2Utils.samlEncode("response".getBytes(UTF_8))); Saml2AuthenticationToken token = converter.convert(request); @@ -68,8 +68,8 @@ public class Saml2AuthenticationTokenConverterTests { public void convertWhenNoSamlResponseThenNull() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); - when(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))) - .thenReturn(this.relyingPartyRegistration); + given(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))) + .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); assertThat(converter.convert(request)).isNull(); } @@ -78,7 +78,7 @@ public class Saml2AuthenticationTokenConverterTests { public void convertWhenNoRelyingPartyRegistrationThenNull() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); - when(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))).thenReturn(null); + given(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))).willReturn(null); MockHttpServletRequest request = new MockHttpServletRequest(); assertThat(converter.convert(request)).isNull(); } @@ -87,8 +87,8 @@ public class Saml2AuthenticationTokenConverterTests { public void convertWhenGetRequestThenInflates() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); - when(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))) - .thenReturn(this.relyingPartyRegistration); + given(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))) + .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("GET"); byte[] deflated = Saml2Utils.samlDeflate("response"); @@ -109,8 +109,8 @@ public class Saml2AuthenticationTokenConverterTests { public void convertWhenUsingSamlUtilsBase64ThenXmlIsValid() throws Exception { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); - when(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))) - .thenReturn(this.relyingPartyRegistration); + given(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))) + .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("SAMLResponse", getSsoCircleEncodedXml()); Saml2AuthenticationToken token = converter.convert(request); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java index 6d1b0455e9..3e4fe4d575 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java @@ -30,10 +30,10 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.security.saml2.core.TestSaml2X509Credentials.relyingPartyVerifyingCredential; import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.noCredentials; @@ -94,7 +94,7 @@ public class Saml2MetadataFilterTests { public void doFilterWhenNoRelyingPartyRegistrationThenUnauthorized() throws Exception { // given this.request.setPathInfo("/saml2/service-provider-metadata/invalidRegistration"); - when(this.repository.findByRegistrationId("invalidRegistration")).thenReturn(null); + given(this.repository.findByRegistrationId("invalidRegistration")).willReturn(null); // when this.filter.doFilter(this.request, this.response, this.chain); @@ -114,7 +114,7 @@ public class Saml2MetadataFilterTests { .build(); String generatedMetadata = "test"; - when(this.resolver.resolve(validRegistration)).thenReturn(generatedMetadata); + given(this.resolver.resolve(validRegistration)).willReturn(generatedMetadata); this.filter = new Saml2MetadataFilter(request -> validRegistration, this.resolver); diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTagTests.java index 5d009dde41..ca81cb9b85 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTagTests.java @@ -40,9 +40,9 @@ import org.springframework.web.context.WebApplicationContext; 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; /** * @author Rob Winch @@ -89,8 +89,8 @@ public class AbstractAuthorizeTagTests { WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class); this.tag.setUrl(uri); WebApplicationContext wac = mock(WebApplicationContext.class); - when(wac.getBeansOfType(WebInvocationPrivilegeEvaluator.class)) - .thenReturn(Collections.singletonMap("wipe", expected)); + given(wac.getBeansOfType(WebInvocationPrivilegeEvaluator.class)) + .willReturn(Collections.singletonMap("wipe", expected)); this.servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac); this.tag.authorizeUsingUrlCheck(); @@ -105,8 +105,8 @@ public class AbstractAuthorizeTagTests { DefaultWebSecurityExpressionHandler expected = new DefaultWebSecurityExpressionHandler(); this.tag.setAccess("permitAll"); WebApplicationContext wac = mock(WebApplicationContext.class); - when(wac.getBeansOfType(SecurityExpressionHandler.class)) - .thenReturn(Collections.singletonMap("wipe", expected)); + given(wac.getBeansOfType(SecurityExpressionHandler.class)) + .willReturn(Collections.singletonMap("wipe", expected)); this.servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac); assertThat(this.tag.authorize()).isTrue(); diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AccessControlListTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AccessControlListTagTests.java index 05f54a0ae8..67d6718f2e 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AccessControlListTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AccessControlListTagTests.java @@ -36,10 +36,10 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.context.WebApplicationContext; 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.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; /** * @author Luke Taylor @@ -68,7 +68,7 @@ public class AccessControlListTagTests { Map beanMap = new HashMap(); beanMap.put("pe", this.pe); - when(ctx.getBeansOfType(PermissionEvaluator.class)).thenReturn(beanMap); + given(ctx.getBeansOfType(PermissionEvaluator.class)).willReturn(beanMap); MockServletContext servletCtx = new MockServletContext(); servletCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx); @@ -84,7 +84,7 @@ public class AccessControlListTagTests { @Test public void bodyIsEvaluatedIfAclGrantsAccess() throws Exception { Object domainObject = new Object(); - when(this.pe.hasPermission(this.bob, domainObject, "READ")).thenReturn(true); + given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(true); this.tag.setDomainObject(domainObject); this.tag.setHasPermission("READ"); @@ -105,7 +105,7 @@ public class AccessControlListTagTests { servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac); Object domainObject = new Object(); - when(this.pe.hasPermission(this.bob, domainObject, "READ")).thenReturn(true); + given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(true); this.tag.setDomainObject(domainObject); this.tag.setHasPermission("READ"); @@ -121,8 +121,8 @@ public class AccessControlListTagTests { @Test public void multiHasPermissionsAreSplit() throws Exception { Object domainObject = new Object(); - when(this.pe.hasPermission(this.bob, domainObject, "READ")).thenReturn(true); - when(this.pe.hasPermission(this.bob, domainObject, "WRITE")).thenReturn(true); + given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(true); + given(this.pe.hasPermission(this.bob, domainObject, "WRITE")).willReturn(true); this.tag.setDomainObject(domainObject); this.tag.setHasPermission("READ,WRITE"); @@ -141,8 +141,8 @@ public class AccessControlListTagTests { @Test public void hasPermissionsBitMaskSupported() throws Exception { Object domainObject = new Object(); - when(this.pe.hasPermission(this.bob, domainObject, 1)).thenReturn(true); - when(this.pe.hasPermission(this.bob, domainObject, 2)).thenReturn(true); + given(this.pe.hasPermission(this.bob, domainObject, 1)).willReturn(true); + given(this.pe.hasPermission(this.bob, domainObject, 2)).willReturn(true); this.tag.setDomainObject(domainObject); this.tag.setHasPermission("1,2"); @@ -160,8 +160,8 @@ public class AccessControlListTagTests { @Test public void hasPermissionsMixedBitMaskSupported() throws Exception { Object domainObject = new Object(); - when(this.pe.hasPermission(this.bob, domainObject, 1)).thenReturn(true); - when(this.pe.hasPermission(this.bob, domainObject, "WRITE")).thenReturn(true); + given(this.pe.hasPermission(this.bob, domainObject, 1)).willReturn(true); + given(this.pe.hasPermission(this.bob, domainObject, "WRITE")).willReturn(true); this.tag.setDomainObject(domainObject); this.tag.setHasPermission("1,WRITE"); @@ -179,7 +179,7 @@ public class AccessControlListTagTests { @Test public void bodyIsSkippedIfAclDeniesAccess() throws Exception { Object domainObject = new Object(); - when(this.pe.hasPermission(this.bob, domainObject, "READ")).thenReturn(false); + given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(false); this.tag.setDomainObject(domainObject); this.tag.setHasPermission("READ"); diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java index c89a4f6975..7f7f54ee36 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java @@ -43,7 +43,7 @@ import org.springframework.web.context.support.StaticWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Francois Beausoleil @@ -91,7 +91,7 @@ public class AuthorizeTagTests { Object domain = new Object(); this.request.setAttribute("domain", domain); this.authorizeTag.setAccess("hasPermission(#domain,'read') or hasPermission(#domain,'write')"); - when(this.permissionEvaluator.hasPermission(eq(this.currentUser), eq(domain), anyString())).thenReturn(true); + given(this.permissionEvaluator.hasPermission(eq(this.currentUser), eq(domain), anyString())).willReturn(true); assertThat(this.authorizeTag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE); } diff --git a/test/src/test/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactoryTests.java b/test/src/test/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactoryTests.java index 1edb96de79..790b1498ec 100644 --- a/test/src/test/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactoryTests.java +++ b/test/src/test/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactoryTests.java @@ -22,7 +22,7 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; 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 WithMockUserSecurityContextFactoryTests { @@ -44,10 +44,10 @@ public class WithMockUserSecurityContextFactoryTests { @Test public void valueDefaultsUsername() { - when(this.withUser.value()).thenReturn("valueUser"); - when(this.withUser.password()).thenReturn("password"); - when(this.withUser.roles()).thenReturn(new String[] { "USER" }); - when(this.withUser.authorities()).thenReturn(new String[] {}); + given(this.withUser.value()).willReturn("valueUser"); + given(this.withUser.password()).willReturn("password"); + given(this.withUser.roles()).willReturn(new String[] { "USER" }); + given(this.withUser.authorities()).willReturn(new String[] {}); assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getName()) .isEqualTo(this.withUser.value()); @@ -55,10 +55,10 @@ public class WithMockUserSecurityContextFactoryTests { @Test public void usernamePrioritizedOverValue() { - when(this.withUser.username()).thenReturn("customUser"); - when(this.withUser.password()).thenReturn("password"); - when(this.withUser.roles()).thenReturn(new String[] { "USER" }); - when(this.withUser.authorities()).thenReturn(new String[] {}); + given(this.withUser.username()).willReturn("customUser"); + given(this.withUser.password()).willReturn("password"); + given(this.withUser.roles()).willReturn(new String[] { "USER" }); + given(this.withUser.authorities()).willReturn(new String[] {}); assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getName()) .isEqualTo(this.withUser.username()); @@ -66,10 +66,10 @@ public class WithMockUserSecurityContextFactoryTests { @Test public void rolesWorks() { - when(this.withUser.value()).thenReturn("valueUser"); - when(this.withUser.password()).thenReturn("password"); - when(this.withUser.roles()).thenReturn(new String[] { "USER", "CUSTOM" }); - when(this.withUser.authorities()).thenReturn(new String[] {}); + given(this.withUser.value()).willReturn("valueUser"); + given(this.withUser.password()).willReturn("password"); + given(this.withUser.roles()).willReturn(new String[] { "USER", "CUSTOM" }); + given(this.withUser.authorities()).willReturn(new String[] {}); assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getAuthorities()) .extracting("authority").containsOnly("ROLE_USER", "ROLE_CUSTOM"); @@ -77,10 +77,10 @@ public class WithMockUserSecurityContextFactoryTests { @Test public void authoritiesWorks() { - when(this.withUser.value()).thenReturn("valueUser"); - when(this.withUser.password()).thenReturn("password"); - when(this.withUser.roles()).thenReturn(new String[] { "USER" }); - when(this.withUser.authorities()).thenReturn(new String[] { "USER", "CUSTOM" }); + given(this.withUser.value()).willReturn("valueUser"); + given(this.withUser.password()).willReturn("password"); + given(this.withUser.roles()).willReturn(new String[] { "USER" }); + given(this.withUser.authorities()).willReturn(new String[] { "USER", "CUSTOM" }); assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getAuthorities()) .extracting("authority").containsOnly("USER", "CUSTOM"); @@ -88,18 +88,18 @@ public class WithMockUserSecurityContextFactoryTests { @Test(expected = IllegalStateException.class) public void authoritiesAndRolesInvalid() { - when(this.withUser.value()).thenReturn("valueUser"); - when(this.withUser.roles()).thenReturn(new String[] { "CUSTOM" }); - when(this.withUser.authorities()).thenReturn(new String[] { "USER", "CUSTOM" }); + given(this.withUser.value()).willReturn("valueUser"); + given(this.withUser.roles()).willReturn(new String[] { "CUSTOM" }); + given(this.withUser.authorities()).willReturn(new String[] { "USER", "CUSTOM" }); this.factory.createSecurityContext(this.withUser); } @Test(expected = IllegalArgumentException.class) public void rolesWithRolePrefixFails() { - when(this.withUser.value()).thenReturn("valueUser"); - when(this.withUser.roles()).thenReturn(new String[] { "ROLE_FAIL" }); - when(this.withUser.authorities()).thenReturn(new String[] {}); + given(this.withUser.value()).willReturn("valueUser"); + given(this.withUser.roles()).willReturn(new String[] { "ROLE_FAIL" }); + given(this.withUser.authorities()).willReturn(new String[] {}); this.factory.createSecurityContext(this.withUser); } diff --git a/test/src/test/java/org/springframework/security/test/context/support/WithSecurityContextTestExcecutionListenerTests.java b/test/src/test/java/org/springframework/security/test/context/support/WithSecurityContextTestExcecutionListenerTests.java index dec5e7b65e..3bacb905d9 100644 --- a/test/src/test/java/org/springframework/security/test/context/support/WithSecurityContextTestExcecutionListenerTests.java +++ b/test/src/test/java/org/springframework/security/test/context/support/WithSecurityContextTestExcecutionListenerTests.java @@ -45,8 +45,8 @@ import org.springframework.test.context.support.AbstractTestExecutionListener; import org.springframework.util.ReflectionUtils; 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; @RunWith(MockitoJUnitRunner.class) public class WithSecurityContextTestExcecutionListenerTests { @@ -76,8 +76,8 @@ public class WithSecurityContextTestExcecutionListenerTests { @SuppressWarnings({ "rawtypes", "unchecked" }) public void beforeTestMethodNullSecurityContextNoError() throws Exception { Class testClass = FakeTest.class; - when(this.testContext.getTestClass()).thenReturn(testClass); - when(this.testContext.getTestMethod()).thenReturn(ReflectionUtils.findMethod(testClass, "testNoAnnotation")); + given(this.testContext.getTestClass()).willReturn(testClass); + given(this.testContext.getTestMethod()).willReturn(ReflectionUtils.findMethod(testClass, "testNoAnnotation")); this.listener.beforeTestMethod(this.testContext); } @@ -86,8 +86,8 @@ public class WithSecurityContextTestExcecutionListenerTests { @SuppressWarnings({ "rawtypes", "unchecked" }) public void beforeTestMethodNoApplicationContext() throws Exception { Class testClass = FakeTest.class; - when(this.testContext.getApplicationContext()).thenThrow(new IllegalStateException()); - when(this.testContext.getTestMethod()).thenReturn(ReflectionUtils.findMethod(testClass, "testWithMockUser")); + given(this.testContext.getApplicationContext()).willThrow(new IllegalStateException()); + given(this.testContext.getTestMethod()).willReturn(ReflectionUtils.findMethod(testClass, "testWithMockUser")); this.listener.beforeTestMethod(this.testContext); @@ -128,8 +128,8 @@ public class WithSecurityContextTestExcecutionListenerTests { Method method = ReflectionUtils.findMethod(WithSecurityContextTestExcecutionListenerTests.class, "handlesGenericAnnotationTestMethod"); TestContext testContext = mock(TestContext.class); - when(testContext.getTestMethod()).thenReturn(method); - when(testContext.getApplicationContext()).thenThrow(new IllegalStateException("")); + given(testContext.getTestMethod()).willReturn(method); + given(testContext.getApplicationContext()).willThrow(new IllegalStateException("")); this.listener.beforeTestMethod(testContext); diff --git a/test/src/test/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListenerTests.java b/test/src/test/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListenerTests.java index 3fd1c645c6..10bc6fd566 100644 --- a/test/src/test/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListenerTests.java +++ b/test/src/test/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListenerTests.java @@ -44,9 +44,9 @@ import org.springframework.test.context.junit4.rules.SpringMethodRule; 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.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -78,8 +78,8 @@ public class WithSecurityContextTestExecutionListenerTests { @Test public void beforeTestMethodWhenWithMockUserTestExecutionDefaultThenSecurityContextSet() throws Exception { Method testMethod = TheTest.class.getMethod("withMockUserDefault"); - when(this.testContext.getApplicationContext()).thenReturn(this.applicationContext); - when(this.testContext.getTestMethod()).thenReturn(testMethod); + given(this.testContext.getApplicationContext()).willReturn(this.applicationContext); + given(this.testContext.getTestMethod()).willReturn(testMethod); this.listener.beforeTestMethod(this.testContext); @@ -91,8 +91,8 @@ public class WithSecurityContextTestExecutionListenerTests { @Test public void beforeTestMethodWhenWithMockUserTestMethodThenSecurityContextSet() throws Exception { Method testMethod = TheTest.class.getMethod("withMockUserTestMethod"); - when(this.testContext.getApplicationContext()).thenReturn(this.applicationContext); - when(this.testContext.getTestMethod()).thenReturn(testMethod); + given(this.testContext.getApplicationContext()).willReturn(this.applicationContext); + given(this.testContext.getTestMethod()).willReturn(testMethod); this.listener.beforeTestMethod(this.testContext); @@ -104,8 +104,8 @@ public class WithSecurityContextTestExecutionListenerTests { @Test public void beforeTestMethodWhenWithMockUserTestExecutionThenTestContextSet() throws Exception { Method testMethod = TheTest.class.getMethod("withMockUserTestExecution"); - when(this.testContext.getApplicationContext()).thenReturn(this.applicationContext); - when(this.testContext.getTestMethod()).thenReturn(testMethod); + given(this.testContext.getApplicationContext()).willReturn(this.applicationContext); + given(this.testContext.getTestMethod()).willReturn(testMethod); this.listener.beforeTestMethod(this.testContext); @@ -118,8 +118,8 @@ public class WithSecurityContextTestExecutionListenerTests { @SuppressWarnings("unchecked") public void beforeTestMethodWhenWithMockUserTestExecutionThenTestContextSupplierOk() throws Exception { Method testMethod = TheTest.class.getMethod("withMockUserTestExecution"); - when(this.testContext.getApplicationContext()).thenReturn(this.applicationContext); - when(this.testContext.getTestMethod()).thenReturn(testMethod); + given(this.testContext.getApplicationContext()).willReturn(this.applicationContext); + given(this.testContext.getTestMethod()).willReturn(testMethod); this.listener.beforeTestMethod(this.testContext); @@ -133,9 +133,9 @@ public class WithSecurityContextTestExecutionListenerTests { // gh-6591 public void beforeTestMethodWhenTestExecutionThenDelayFactoryCreate() throws Exception { Method testMethod = TheTest.class.getMethod("withUserDetails"); - when(this.testContext.getApplicationContext()).thenReturn(this.applicationContext); + given(this.testContext.getApplicationContext()).willReturn(this.applicationContext); // do not set a UserDetailsService Bean so it would fail if looked up - when(this.testContext.getTestMethod()).thenReturn(testMethod); + given(this.testContext.getTestMethod()).willReturn(testMethod); this.listener.beforeTestMethod(this.testContext); // bean lookup of UserDetailsService would fail if it has already been looked up @@ -153,8 +153,8 @@ public class WithSecurityContextTestExecutionListenerTests { SecurityContextImpl securityContext = new SecurityContextImpl(); securityContext.setAuthentication(new TestingAuthenticationToken("user", "passsword", "ROLE_USER")); Supplier supplier = () -> securityContext; - when(this.testContext.removeAttribute(WithSecurityContextTestExecutionListener.SECURITY_CONTEXT_ATTR_NAME)) - .thenReturn(supplier); + given(this.testContext.removeAttribute(WithSecurityContextTestExecutionListener.SECURITY_CONTEXT_ATTR_NAME)) + .willReturn(supplier); this.listener.beforeTestExecution(this.testContext); diff --git a/test/src/test/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactoryTests.java b/test/src/test/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactoryTests.java index 873ce590e2..ce3c9f7d90 100644 --- a/test/src/test/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactoryTests.java +++ b/test/src/test/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactoryTests.java @@ -32,8 +32,8 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; 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; @RunWith(MockitoJUnitRunner.class) public class WithUserDetailsSecurityContextFactoryTests { @@ -68,17 +68,17 @@ public class WithUserDetailsSecurityContextFactoryTests { @Test(expected = IllegalArgumentException.class) public void createSecurityContextEmptyValue() { - when(this.withUserDetails.value()).thenReturn(""); + given(this.withUserDetails.value()).willReturn(""); this.factory.createSecurityContext(this.withUserDetails); } @Test public void createSecurityContextWithExistingUser() { String username = "user"; - when(this.beans.getBean(ReactiveUserDetailsService.class)).thenThrow(new NoSuchBeanDefinitionException("")); - when(this.beans.getBean(UserDetailsService.class)).thenReturn(this.userDetailsService); - when(this.withUserDetails.value()).thenReturn(username); - when(this.userDetailsService.loadUserByUsername(username)).thenReturn(this.userDetails); + given(this.beans.getBean(ReactiveUserDetailsService.class)).willThrow(new NoSuchBeanDefinitionException("")); + given(this.beans.getBean(UserDetailsService.class)).willReturn(this.userDetailsService); + given(this.withUserDetails.value()).willReturn(username); + given(this.userDetailsService.loadUserByUsername(username)).willReturn(this.userDetails); SecurityContext context = this.factory.createSecurityContext(this.withUserDetails); assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class); @@ -91,12 +91,12 @@ public class WithUserDetailsSecurityContextFactoryTests { public void createSecurityContextWithUserDetailsServiceName() { String beanName = "secondUserDetailsServiceBean"; String username = "user"; - when(this.beans.getBean(beanName, ReactiveUserDetailsService.class)).thenThrow( + given(this.beans.getBean(beanName, ReactiveUserDetailsService.class)).willThrow( new BeanNotOfRequiredTypeException("", ReactiveUserDetailsService.class, UserDetailsService.class)); - when(this.withUserDetails.value()).thenReturn(username); - when(this.withUserDetails.userDetailsServiceBeanName()).thenReturn(beanName); - when(this.userDetailsService.loadUserByUsername(username)).thenReturn(this.userDetails); - when(this.beans.getBean(beanName, UserDetailsService.class)).thenReturn(this.userDetailsService); + given(this.withUserDetails.value()).willReturn(username); + given(this.withUserDetails.userDetailsServiceBeanName()).willReturn(beanName); + given(this.userDetailsService.loadUserByUsername(username)).willReturn(this.userDetails); + given(this.beans.getBean(beanName, UserDetailsService.class)).willReturn(this.userDetailsService); SecurityContext context = this.factory.createSecurityContext(this.withUserDetails); assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class); @@ -107,9 +107,9 @@ public class WithUserDetailsSecurityContextFactoryTests { @Test public void createSecurityContextWithReactiveUserDetailsService() { String username = "user"; - when(this.withUserDetails.value()).thenReturn(username); - when(this.beans.getBean(ReactiveUserDetailsService.class)).thenReturn(this.reactiveUserDetailsService); - when(this.reactiveUserDetailsService.findByUsername(username)).thenReturn(Mono.just(this.userDetails)); + given(this.withUserDetails.value()).willReturn(username); + given(this.beans.getBean(ReactiveUserDetailsService.class)).willReturn(this.reactiveUserDetailsService); + given(this.reactiveUserDetailsService.findByUsername(username)).willReturn(Mono.just(this.userDetails)); SecurityContext context = this.factory.createSecurityContext(this.withUserDetails); assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class); @@ -121,11 +121,11 @@ public class WithUserDetailsSecurityContextFactoryTests { public void createSecurityContextWithReactiveUserDetailsServiceAndBeanName() { String beanName = "secondUserDetailsServiceBean"; String username = "user"; - when(this.withUserDetails.value()).thenReturn(username); - when(this.withUserDetails.userDetailsServiceBeanName()).thenReturn(beanName); - when(this.beans.getBean(beanName, ReactiveUserDetailsService.class)) - .thenReturn(this.reactiveUserDetailsService); - when(this.reactiveUserDetailsService.findByUsername(username)).thenReturn(Mono.just(this.userDetails)); + given(this.withUserDetails.value()).willReturn(username); + given(this.withUserDetails.userDetailsServiceBeanName()).willReturn(beanName); + given(this.beans.getBean(beanName, ReactiveUserDetailsService.class)) + .willReturn(this.reactiveUserDetailsService); + given(this.reactiveUserDetailsService.findByUsername(username)).willReturn(Mono.just(this.userDetails)); SecurityContext context = this.factory.createSecurityContext(this.withUserDetails); assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class); diff --git a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java index 242f0a4327..0183ef8aaa 100644 --- a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java +++ b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java @@ -45,8 +45,8 @@ 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.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockOAuth2Client; @@ -154,8 +154,8 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock assertThat(client.getClientRegistration().getClientId()).isEqualTo("test-client"); client = new OAuth2AuthorizedClient(clientRegistration().build(), "sub", noScopes()); - when(this.authorizedClientRepository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class), - any(ServerWebExchange.class))).thenReturn(Mono.just(client)); + given(this.authorizedClientRepository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class), + any(ServerWebExchange.class))).willReturn(Mono.just(client)); this.client.get().uri("/client").exchange().expectStatus().isOk(); client = this.controller.authorizedClient; assertThat(client).isNotNull(); diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java index 4814f4b0f8..814f1340ad 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java @@ -49,9 +49,9 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.assertj.core.api.Assertions.assertThatCode; 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.oauth2.client.registration.TestClientRegistrations.clientRegistration; import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oauth2Client; @@ -143,8 +143,8 @@ public class SecurityMockMvcRequestPostProcessorsOAuth2ClientTests { OAuth2AuthorizedClient client = new OAuth2AuthorizedClient(clientRegistration().build(), "sub", noScopes()); OAuth2AuthorizedClientRepository repository = this.context.getBean(OAuth2AuthorizedClientRepository.class); - when(repository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class), - any(HttpServletRequest.class))).thenReturn(client); + given(repository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class), + any(HttpServletRequest.class))).willReturn(client); this.mvc.perform(get("/client-id")).andExpect(content().string("client-id")); verify(repository).loadAuthorizedClient(eq("registration-id"), any(Authentication.class), any(HttpServletRequest.class)); diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurerTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurerTests.java index 1e0ce9e7ad..a64e06ecb7 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurerTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurerTests.java @@ -32,8 +32,8 @@ import org.springframework.web.context.WebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class SecurityMockMvcConfigurerTests { @@ -55,7 +55,7 @@ public class SecurityMockMvcConfigurerTests { @Before public void setup() { - when(this.context.getServletContext()).thenReturn(this.servletContext); + given(this.context.getServletContext()).willReturn(this.servletContext); } @Test @@ -107,8 +107,8 @@ public class SecurityMockMvcConfigurerTests { } private void returnFilterBean() { - when(this.context.containsBean(anyString())).thenReturn(true); - when(this.context.getBean(anyString(), eq(Filter.class))).thenReturn(this.beanFilter); + given(this.context.containsBean(anyString())).willReturn(true); + given(this.context.getBean(anyString(), eq(Filter.class))).willReturn(this.beanFilter); } } diff --git a/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java b/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java index 2c11daeee9..2017452c98 100644 --- a/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java +++ b/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java @@ -45,11 +45,11 @@ 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.doAnswer; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willAnswer; 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 @@ -73,13 +73,13 @@ public class FilterChainProxyTests { public void setup() throws Exception { this.matcher = mock(RequestMatcher.class); this.filter = mock(Filter.class); - doAnswer((Answer) inv -> { + willAnswer((Answer) inv -> { Object[] args = inv.getArguments(); FilterChain fc = (FilterChain) args[2]; HttpServletRequestWrapper extraWrapper = new HttpServletRequestWrapper((HttpServletRequest) args[0]); fc.doFilter(extraWrapper, (HttpServletResponse) args[1]); return null; - }).when(this.filter).doFilter(any(), any(), any()); + }).given(this.filter).doFilter(any(), any(), any()); this.fcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, Arrays.asList(this.filter))); this.fcp.setFilterChainValidator(mock(FilterChainProxy.FilterChainValidator.class)); this.request = new MockHttpServletRequest("GET", ""); @@ -101,7 +101,7 @@ public class FilterChainProxyTests { @Test public void securityFilterChainIsNotInvokedIfMatchFails() throws Exception { - when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(false); + given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(false); this.fcp.doFilter(this.request, this.response, this.chain); assertThat(this.fcp.getFilterChains()).hasSize(1); assertThat(this.fcp.getFilterChains().get(0).getFilters().get(0)).isSameAs(this.filter); @@ -113,7 +113,7 @@ public class FilterChainProxyTests { @Test public void originalChainIsInvokedAfterSecurityChainIfMatchSucceeds() throws Exception { - when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true); + given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true); this.fcp.doFilter(this.request, this.response, this.chain); verify(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), @@ -126,7 +126,7 @@ public class FilterChainProxyTests { List noFilters = Collections.emptyList(); this.fcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, noFilters)); - when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true); + given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true); this.fcp.doFilter(this.request, this.response, this.chain); verify(this.chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); @@ -134,7 +134,7 @@ public class FilterChainProxyTests { @Test public void requestIsWrappedForMatchingAndFilteringWhenMatchIsFound() throws Exception { - when(this.matcher.matches(any())).thenReturn(true); + given(this.matcher.matches(any())).willReturn(true); this.fcp.doFilter(this.request, this.response, this.chain); verify(this.matcher).matches(any(FirewalledRequest.class)); verify(this.filter).doFilter(any(FirewalledRequest.class), any(HttpServletResponse.class), @@ -144,7 +144,7 @@ public class FilterChainProxyTests { @Test public void requestIsWrappedForMatchingAndFilteringWhenMatchIsNotFound() throws Exception { - when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(false); + given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(false); this.fcp.doFilter(this.request, this.response, this.chain); verify(this.matcher).matches(any(FirewalledRequest.class)); verifyZeroInteractions(this.filter); @@ -155,11 +155,11 @@ public class FilterChainProxyTests { public void wrapperIsResetWhenNoMatchingFilters() throws Exception { HttpFirewall fw = mock(HttpFirewall.class); FirewalledRequest fwr = mock(FirewalledRequest.class); - when(fwr.getRequestURI()).thenReturn("/"); - when(fwr.getContextPath()).thenReturn(""); + given(fwr.getRequestURI()).willReturn("/"); + given(fwr.getContextPath()).willReturn(""); this.fcp.setFirewall(fw); - when(fw.getFirewalledRequest(this.request)).thenReturn(fwr); - when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(false); + given(fw.getFirewalledRequest(this.request)).willReturn(fwr); + given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(false); this.fcp.doFilter(this.request, this.response, this.chain); verify(fwr).reset(); } @@ -172,16 +172,16 @@ public class FilterChainProxyTests { firstFcp.setFirewall(fw); this.fcp.setFirewall(fw); FirewalledRequest firstFwr = mock(FirewalledRequest.class, "firstFwr"); - when(firstFwr.getRequestURI()).thenReturn("/"); - when(firstFwr.getContextPath()).thenReturn(""); + given(firstFwr.getRequestURI()).willReturn("/"); + given(firstFwr.getContextPath()).willReturn(""); FirewalledRequest fwr = mock(FirewalledRequest.class, "fwr"); - when(fwr.getRequestURI()).thenReturn("/"); - when(fwr.getContextPath()).thenReturn(""); - when(fw.getFirewalledRequest(this.request)).thenReturn(firstFwr); - when(fw.getFirewalledRequest(firstFwr)).thenReturn(fwr); - when(fwr.getRequest()).thenReturn(firstFwr); - when(firstFwr.getRequest()).thenReturn(this.request); - when(this.matcher.matches(any())).thenReturn(true); + given(fwr.getRequestURI()).willReturn("/"); + given(fwr.getContextPath()).willReturn(""); + given(fw.getFirewalledRequest(this.request)).willReturn(firstFwr); + given(fw.getFirewalledRequest(firstFwr)).willReturn(fwr); + given(fwr.getRequest()).willReturn(firstFwr); + given(firstFwr.getRequest()).willReturn(this.request); + given(this.matcher.matches(any())).willReturn(true); firstFcp.doFilter(this.request, this.response, this.chain); verify(firstFwr).reset(); verify(fwr).reset(); @@ -189,12 +189,12 @@ public class FilterChainProxyTests { @Test public void doFilterClearsSecurityContextHolder() throws Exception { - when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true); - doAnswer((Answer) inv -> { + given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true); + willAnswer((Answer) inv -> { SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("username", "password")); return null; - }).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), + }).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class)); this.fcp.doFilter(this.request, this.response, this.chain); @@ -204,12 +204,12 @@ public class FilterChainProxyTests { @Test public void doFilterClearsSecurityContextHolderWithException() throws Exception { - when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true); - doAnswer((Answer) inv -> { + given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true); + willAnswer((Answer) inv -> { SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("username", "password")); throw new ServletException("oops"); - }).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), + }).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class)); try { @@ -226,20 +226,20 @@ public class FilterChainProxyTests { @Test public void doFilterClearsSecurityContextHolderOnceOnForwards() throws Exception { final FilterChain innerChain = mock(FilterChain.class); - when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true); - doAnswer((Answer) inv -> { + given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true); + willAnswer((Answer) inv -> { TestingAuthenticationToken expected = new TestingAuthenticationToken("username", "password"); SecurityContextHolder.getContext().setAuthentication(expected); - doAnswer((Answer) inv1 -> { + willAnswer((Answer) inv1 -> { innerChain.doFilter(this.request, this.response); return null; - }).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), + }).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class)); this.fcp.doFilter(this.request, this.response, innerChain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expected); return null; - }).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), + }).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class)); this.fcp.doFilter(this.request, this.response, this.chain); @@ -260,7 +260,7 @@ public class FilterChainProxyTests { this.fcp.setFirewall(fw); this.fcp.setRequestRejectedHandler(rjh); RequestRejectedException requestRejectedException = new RequestRejectedException("Contains illegal chars"); - when(fw.getFirewalledRequest(this.request)).thenThrow(requestRejectedException); + given(fw.getFirewalledRequest(this.request)).willThrow(requestRejectedException); this.fcp.doFilter(this.request, this.response, this.chain); verify(rjh).handle(eq(this.request), eq(this.response), eq((requestRejectedException))); } diff --git a/web/src/test/java/org/springframework/security/web/access/DefaultWebInvocationPrivilegeEvaluatorTests.java b/web/src/test/java/org/springframework/security/web/access/DefaultWebInvocationPrivilegeEvaluatorTests.java index f5e98a599f..438ece3d85 100644 --- a/web/src/test/java/org/springframework/security/web/access/DefaultWebInvocationPrivilegeEvaluatorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/DefaultWebInvocationPrivilegeEvaluatorTests.java @@ -34,9 +34,9 @@ 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.anyObject; -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 @@ -71,14 +71,14 @@ public class DefaultWebInvocationPrivilegeEvaluatorTests { @Test public void permitsAccessIfNoMatchingAttributesAndPublicInvocationsAllowed() { DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor); - when(this.ods.getAttributes(anyObject())).thenReturn(null); + given(this.ods.getAttributes(anyObject())).willReturn(null); assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class))).isTrue(); } @Test public void deniesAccessIfNoMatchingAttributesAndPublicInvocationsNotAllowed() { DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor); - when(this.ods.getAttributes(anyObject())).thenReturn(null); + given(this.ods.getAttributes(anyObject())).willReturn(null); this.interceptor.setRejectPublicInvocations(true); assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class))).isFalse(); } @@ -102,7 +102,8 @@ public class DefaultWebInvocationPrivilegeEvaluatorTests { Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX"); DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor); - doThrow(new AccessDeniedException("")).when(this.adm).decide(any(Authentication.class), anyObject(), anyList()); + willThrow(new AccessDeniedException("")).given(this.adm).decide(any(Authentication.class), anyObject(), + anyList()); assertThat(wipe.isAllowed("/foo/index.jsp", token)).isFalse(); } diff --git a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java index 884035c0e6..4976f8a3e3 100644 --- a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java @@ -49,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doThrow; +import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; @@ -92,7 +92,7 @@ public class ExceptionTranslationFilterTests { // Setup the FilterChain to thrown an access denied exception FilterChain fc = mock(FilterChain.class); - doThrow(new AccessDeniedException("")).when(fc).doFilter(any(HttpServletRequest.class), + willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Setup SecurityContextHolder, as filter needs to check if user is @@ -124,7 +124,7 @@ public class ExceptionTranslationFilterTests { // Setup the FilterChain to thrown an access denied exception FilterChain fc = mock(FilterChain.class); - doThrow(new AccessDeniedException("")).when(fc).doFilter(any(HttpServletRequest.class), + willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Setup SecurityContextHolder, as filter needs to check if user is remembered @@ -149,7 +149,7 @@ public class ExceptionTranslationFilterTests { // Setup the FilterChain to thrown an access denied exception FilterChain fc = mock(FilterChain.class); - doThrow(new AccessDeniedException("")).when(fc).doFilter(any(HttpServletRequest.class), + willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Setup SecurityContextHolder, as filter needs to check if user is @@ -179,7 +179,7 @@ public class ExceptionTranslationFilterTests { // Setup the FilterChain to thrown an access denied exception FilterChain fc = mock(FilterChain.class); - doThrow(new AccessDeniedException("")).when(fc).doFilter(any(HttpServletRequest.class), + willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Setup SecurityContextHolder, as filter needs to check if user is @@ -213,7 +213,7 @@ public class ExceptionTranslationFilterTests { // Setup the FilterChain to thrown an authentication failure exception FilterChain fc = mock(FilterChain.class); - doThrow(new BadCredentialsException("")).when(fc).doFilter(any(HttpServletRequest.class), + willThrow(new BadCredentialsException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Test @@ -239,7 +239,7 @@ public class ExceptionTranslationFilterTests { // Setup the FilterChain to thrown an authentication failure exception FilterChain fc = mock(FilterChain.class); - doThrow(new BadCredentialsException("")).when(fc).doFilter(any(HttpServletRequest.class), + willThrow(new BadCredentialsException("")).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); // Test @@ -286,7 +286,7 @@ public class ExceptionTranslationFilterTests { for (Exception e : exceptions) { FilterChain fc = mock(FilterChain.class); - doThrow(e).when(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); + willThrow(e).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); try { filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc); fail("Should have thrown Exception"); diff --git a/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandlerTests.java b/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandlerTests.java index add9ce044f..f5e160c855 100644 --- a/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/access/RequestMatcherDelegatingAccessDeniedHandlerTests.java @@ -26,10 +26,10 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.web.util.matcher.RequestMatcher; +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 Josh Cummings @@ -55,7 +55,7 @@ public class RequestMatcherDelegatingAccessDeniedHandlerTests { public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() throws Exception { AccessDeniedHandler handler = mock(AccessDeniedHandler.class); RequestMatcher matcher = mock(RequestMatcher.class); - when(matcher.matches(this.request)).thenReturn(false); + given(matcher.matches(this.request)).willReturn(false); this.deniedHandlers.put(matcher, handler); this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler); @@ -71,7 +71,7 @@ public class RequestMatcherDelegatingAccessDeniedHandlerTests { RequestMatcher firstMatcher = mock(RequestMatcher.class); AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class); RequestMatcher secondMatcher = mock(RequestMatcher.class); - when(firstMatcher.matches(this.request)).thenReturn(true); + given(firstMatcher.matches(this.request)).willReturn(true); this.deniedHandlers.put(firstMatcher, firstHandler); this.deniedHandlers.put(secondMatcher, secondHandler); this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler); @@ -90,8 +90,8 @@ public class RequestMatcherDelegatingAccessDeniedHandlerTests { RequestMatcher firstMatcher = mock(RequestMatcher.class); AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class); RequestMatcher secondMatcher = mock(RequestMatcher.class); - when(firstMatcher.matches(this.request)).thenReturn(false); - when(secondMatcher.matches(this.request)).thenReturn(true); + given(firstMatcher.matches(this.request)).willReturn(false); + given(secondMatcher.matches(this.request)).willReturn(true); this.deniedHandlers.put(firstMatcher, firstHandler); this.deniedHandlers.put(secondMatcher, secondHandler); this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler); diff --git a/web/src/test/java/org/springframework/security/web/access/expression/DelegatingEvaluationContextTests.java b/web/src/test/java/org/springframework/security/web/access/expression/DelegatingEvaluationContextTests.java index abbc789a97..bb9a8e6734 100644 --- a/web/src/test/java/org/springframework/security/web/access/expression/DelegatingEvaluationContextTests.java +++ b/web/src/test/java/org/springframework/security/web/access/expression/DelegatingEvaluationContextTests.java @@ -36,9 +36,9 @@ import org.springframework.expression.TypeLocator; import org.springframework.expression.TypedValue; 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 @@ -55,7 +55,7 @@ public class DelegatingEvaluationContextTests { @Test public void getRootObject() { TypedValue expected = mock(TypedValue.class); - when(this.delegate.getRootObject()).thenReturn(expected); + given(this.delegate.getRootObject()).willReturn(expected); assertThat(this.context.getRootObject()).isEqualTo(expected); } @@ -63,7 +63,7 @@ public class DelegatingEvaluationContextTests { @Test public void getConstructorResolvers() { List expected = new ArrayList<>(); - when(this.delegate.getConstructorResolvers()).thenReturn(expected); + given(this.delegate.getConstructorResolvers()).willReturn(expected); assertThat(this.context.getConstructorResolvers()).isEqualTo(expected); } @@ -71,7 +71,7 @@ public class DelegatingEvaluationContextTests { @Test public void getMethodResolvers() { List expected = new ArrayList<>(); - when(this.delegate.getMethodResolvers()).thenReturn(expected); + given(this.delegate.getMethodResolvers()).willReturn(expected); assertThat(this.context.getMethodResolvers()).isEqualTo(expected); } @@ -79,7 +79,7 @@ public class DelegatingEvaluationContextTests { @Test public void getPropertyAccessors() { List expected = new ArrayList<>(); - when(this.delegate.getPropertyAccessors()).thenReturn(expected); + given(this.delegate.getPropertyAccessors()).willReturn(expected); assertThat(this.context.getPropertyAccessors()).isEqualTo(expected); } @@ -88,7 +88,7 @@ public class DelegatingEvaluationContextTests { public void getTypeLocator() { TypeLocator expected = mock(TypeLocator.class); - when(this.delegate.getTypeLocator()).thenReturn(expected); + given(this.delegate.getTypeLocator()).willReturn(expected); assertThat(this.context.getTypeLocator()).isEqualTo(expected); } @@ -96,7 +96,7 @@ public class DelegatingEvaluationContextTests { @Test public void getTypeConverter() { TypeConverter expected = mock(TypeConverter.class); - when(this.delegate.getTypeConverter()).thenReturn(expected); + given(this.delegate.getTypeConverter()).willReturn(expected); assertThat(this.context.getTypeConverter()).isEqualTo(expected); } @@ -104,7 +104,7 @@ public class DelegatingEvaluationContextTests { @Test public void getTypeComparator() { TypeComparator expected = mock(TypeComparator.class); - when(this.delegate.getTypeComparator()).thenReturn(expected); + given(this.delegate.getTypeComparator()).willReturn(expected); assertThat(this.context.getTypeComparator()).isEqualTo(expected); } @@ -112,7 +112,7 @@ public class DelegatingEvaluationContextTests { @Test public void getOperatorOverloader() { OperatorOverloader expected = mock(OperatorOverloader.class); - when(this.delegate.getOperatorOverloader()).thenReturn(expected); + given(this.delegate.getOperatorOverloader()).willReturn(expected); assertThat(this.context.getOperatorOverloader()).isEqualTo(expected); } @@ -120,7 +120,7 @@ public class DelegatingEvaluationContextTests { @Test public void getBeanResolver() { BeanResolver expected = mock(BeanResolver.class); - when(this.delegate.getBeanResolver()).thenReturn(expected); + given(this.delegate.getBeanResolver()).willReturn(expected); assertThat(this.context.getBeanResolver()).isEqualTo(expected); } @@ -139,7 +139,7 @@ public class DelegatingEvaluationContextTests { public void lookupVariable() { String name = "name"; String expected = "expected"; - when(this.delegate.lookupVariable(name)).thenReturn(expected); + given(this.delegate.lookupVariable(name)).willReturn(expected); assertThat(this.context.lookupVariable(name)).isEqualTo(expected); } diff --git a/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java b/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java index 608053c1d7..4e709ba6c7 100644 --- a/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/expression/WebExpressionVoterTests.java @@ -35,8 +35,8 @@ import org.springframework.security.web.FilterInvocation; 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 Luke Taylor @@ -70,15 +70,15 @@ public class WebExpressionVoterTests { WebExpressionVoter voter = new WebExpressionVoter(); Expression ex = mock(Expression.class); EvaluationContextPostProcessor postProcessor = mock(EvaluationContextPostProcessor.class); - when(postProcessor.postProcess(any(EvaluationContext.class), any(FilterInvocation.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); + given(postProcessor.postProcess(any(EvaluationContext.class), any(FilterInvocation.class))) + .willAnswer(invocation -> invocation.getArgument(0)); WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex, postProcessor); EvaluationContext ctx = mock(EvaluationContext.class); SecurityExpressionHandler eh = mock(SecurityExpressionHandler.class); FilterInvocation fi = new FilterInvocation("/path", "GET"); voter.setExpressionHandler(eh); - when(eh.createEvaluationContext(this.user, fi)).thenReturn(ctx); - when(ex.getValue(ctx, Boolean.class)).thenReturn(Boolean.TRUE).thenReturn(Boolean.FALSE); + given(eh.createEvaluationContext(this.user, fi)).willReturn(ctx); + given(ex.getValue(ctx, Boolean.class)).willReturn(Boolean.TRUE, Boolean.FALSE); ArrayList attributes = new ArrayList(); attributes.addAll(SecurityConfig.createList("A", "B", "C")); attributes.add(weca); diff --git a/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java b/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java index d56a4de170..37199a0c8f 100644 --- a/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java @@ -46,12 +46,12 @@ import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; 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 FilterSecurityInterceptor}. @@ -97,13 +97,13 @@ public class FilterSecurityInterceptorTests { @Test(expected = IllegalArgumentException.class) public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass() throws Exception { - when(this.adm.supports(FilterInvocation.class)).thenReturn(true); + given(this.adm.supports(FilterInvocation.class)).willReturn(true); this.interceptor.afterPropertiesSet(); } @Test(expected = IllegalArgumentException.class) public void testEnsuresRunAsManagerSupportsFilterInvocationClass() throws Exception { - when(this.adm.supports(FilterInvocation.class)).thenReturn(false); + given(this.adm.supports(FilterInvocation.class)).willReturn(false); this.interceptor.afterPropertiesSet(); } @@ -120,7 +120,7 @@ public class FilterSecurityInterceptorTests { FilterInvocation fi = createinvocation(); - when(this.ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK")); + given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); this.interceptor.invoke(fi); @@ -136,9 +136,9 @@ public class FilterSecurityInterceptorTests { FilterInvocation fi = createinvocation(); FilterChain chain = fi.getChain(); - doThrow(new RuntimeException()).when(chain).doFilter(any(HttpServletRequest.class), + willThrow(new RuntimeException()).given(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); - when(this.ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK")); + given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); AfterInvocationManager aim = mock(AfterInvocationManager.class); this.interceptor.setAfterInvocationManager(aim); @@ -163,16 +163,16 @@ public class FilterSecurityInterceptorTests { ctx.setAuthentication(token); RunAsManager runAsManager = mock(RunAsManager.class); - when(runAsManager.buildRunAs(eq(token), any(), anyCollection())) - .thenReturn(new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), token.getClass())); + given(runAsManager.buildRunAs(eq(token), any(), anyCollection())) + .willReturn(new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), token.getClass())); this.interceptor.setRunAsManager(runAsManager); FilterInvocation fi = createinvocation(); FilterChain chain = fi.getChain(); - doThrow(new RuntimeException()).when(chain).doFilter(any(HttpServletRequest.class), + willThrow(new RuntimeException()).given(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); - when(this.ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK")); + given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); AfterInvocationManager aim = mock(AfterInvocationManager.class); this.interceptor.setAfterInvocationManager(aim); diff --git a/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java index 53e60f8f62..50d37da710 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java @@ -44,10 +44,10 @@ import org.springframework.security.web.util.matcher.RequestMatcher; 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.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * @author Sergey Bespalov @@ -76,7 +76,7 @@ public class AuthenticationFilterTests { @Before public void setup() { - when(this.authenticationManagerResolver.resolve(any())).thenReturn(this.authenticationManager); + given(this.authenticationManagerResolver.resolve(any())).willReturn(this.authenticationManager); } @After @@ -117,8 +117,8 @@ public class AuthenticationFilterTests { @Test public void filterWhenDefaultsAndAuthenticationSuccessThenContinues() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE"); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(authentication); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter); @@ -136,8 +136,8 @@ public class AuthenticationFilterTests { public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationSuccessThenContinues() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE"); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(authentication); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); @@ -155,8 +155,8 @@ public class AuthenticationFilterTests { @Test public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE"); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())).thenThrow(new BadCredentialsException("failed")); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed")); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter); @@ -174,8 +174,8 @@ public class AuthenticationFilterTests { public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE"); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())).thenThrow(new BadCredentialsException("failed")); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed")); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); @@ -191,7 +191,7 @@ public class AuthenticationFilterTests { @Test public void filterWhenConvertEmptyThenOk() throws Exception { - when(this.authenticationConverter.convert(any())).thenReturn(null); + given(this.authenticationConverter.convert(any())).willReturn(null); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); @@ -207,8 +207,8 @@ public class AuthenticationFilterTests { @Test public void filterWhenConvertAndAuthenticationSuccessThenSuccess() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER"); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(authentication); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); @@ -227,8 +227,8 @@ public class AuthenticationFilterTests { @Test(expected = ServletException.class) public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER"); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())).thenReturn(null); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(null); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); @@ -250,7 +250,7 @@ public class AuthenticationFilterTests { @Test public void filterWhenNotMatchAndConvertAndAuthenticationSuccessThenContinues() throws Exception { - when(this.requestMatcher.matches(any())).thenReturn(false); + given(this.requestMatcher.matches(any())).willReturn(false); AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter); @@ -269,8 +269,8 @@ public class AuthenticationFilterTests { @Test public void filterWhenSuccessfulAuthenticationThenSessionIdChanges() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER"); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(authentication); MockHttpSession session = new MockHttpSession(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); diff --git a/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTests.java index 767f6ce5ac..9cb163cdc9 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTests.java @@ -26,10 +26,10 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.util.matcher.RequestMatcher; +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; /** * Test class for {@link DelegatingAuthenticationEntryPoint} @@ -60,7 +60,7 @@ public class DelegatingAuthenticationEntryPointTests { public void testDefaultEntryPoint() throws Exception { AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class); RequestMatcher firstRM = mock(RequestMatcher.class); - when(firstRM.matches(this.request)).thenReturn(false); + given(firstRM.matches(this.request)).willReturn(false); this.entryPoints.put(firstRM, firstAEP); this.daep.commence(this.request, null, null); @@ -75,7 +75,7 @@ public class DelegatingAuthenticationEntryPointTests { RequestMatcher firstRM = mock(RequestMatcher.class); AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class); RequestMatcher secondRM = mock(RequestMatcher.class); - when(firstRM.matches(this.request)).thenReturn(true); + given(firstRM.matches(this.request)).willReturn(true); this.entryPoints.put(firstRM, firstAEP); this.entryPoints.put(secondRM, secondAEP); @@ -93,8 +93,8 @@ public class DelegatingAuthenticationEntryPointTests { RequestMatcher firstRM = mock(RequestMatcher.class); AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class); RequestMatcher secondRM = mock(RequestMatcher.class); - when(firstRM.matches(this.request)).thenReturn(false); - when(secondRM.matches(this.request)).thenReturn(true); + given(firstRM.matches(this.request)).willReturn(false); + given(secondRM.matches(this.request)).willReturn(true); this.entryPoints.put(firstRM, firstAEP); this.entryPoints.put(secondRM, secondAEP); diff --git a/web/src/test/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandlerTests.java index d836bc701b..af5c0e2a9a 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandlerTests.java @@ -25,9 +25,9 @@ import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SavedRequest; 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.verify; -import static org.mockito.Mockito.when; public class SavedRequestAwareAuthenticationSuccessHandlerTests { @@ -55,8 +55,8 @@ public class SavedRequestAwareAuthenticationSuccessHandlerTests { SavedRequest savedRequest = mock(SavedRequest.class); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - when(savedRequest.getRedirectUrl()).thenReturn(redirectUrl); - when(requestCache.getRequest(request, response)).thenReturn(savedRequest); + given(savedRequest.getRedirectUrl()).willReturn(redirectUrl); + given(requestCache.getRequest(request, response)).willReturn(savedRequest); SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler(); handler.setRequestCache(requestCache); diff --git a/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java index f1417f9121..5c00f97145 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java @@ -29,8 +29,8 @@ import org.springframework.security.core.AuthenticationException; 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 {@link UsernamePasswordAuthenticationFilter}. @@ -122,7 +122,7 @@ public class UsernamePasswordAuthenticationFilterTests { request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod"); UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(); AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException("")); + given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); filter.setAuthenticationManager(am); try { @@ -152,8 +152,8 @@ public class UsernamePasswordAuthenticationFilterTests { private AuthenticationManager createAuthenticationManager() { AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(any(Authentication.class))) - .thenAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); + given(am.authenticate(any(Authentication.class))) + .willAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); return am; } diff --git a/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java index bfacd8d55f..5db6228a6d 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java @@ -31,7 +31,7 @@ import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doThrow; +import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -91,7 +91,7 @@ public class CompositeLogoutHandlerTests { LogoutHandler firstLogoutHandler = mock(LogoutHandler.class); LogoutHandler secondLogoutHandler = mock(LogoutHandler.class); - doThrow(new IllegalArgumentException()).when(firstLogoutHandler).logout(any(HttpServletRequest.class), + willThrow(new IllegalArgumentException()).given(firstLogoutHandler).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); List logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler); diff --git a/web/src/test/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandlerTests.java index 66ef5e52ef..ff92fb9536 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/DelegatingLogoutSuccessHandlerTests.java @@ -29,9 +29,9 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.util.matcher.RequestMatcher; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * DelegatingLogoutSuccessHandlerTests Tests @@ -79,7 +79,7 @@ public class DelegatingLogoutSuccessHandlerTests { @Test public void onLogoutSuccessFirstMatches() throws Exception { this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler); - when(this.matcher.matches(this.request)).thenReturn(true); + given(this.matcher.matches(this.request)).willReturn(true); this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication); @@ -90,7 +90,7 @@ public class DelegatingLogoutSuccessHandlerTests { @Test public void onLogoutSuccessSecondMatches() throws Exception { this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler); - when(this.matcher2.matches(this.request)).thenReturn(true); + given(this.matcher2.matches(this.request)).willReturn(true); this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication); diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java index 8a028ba49b..2a39eea38a 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java @@ -43,10 +43,10 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 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.verify; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -81,7 +81,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests { @Test public void filterChainProceedsOnFailedAuthenticationByDefault() throws Exception { AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException("")); + given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); this.filter.setAuthenticationManager(am); this.filter.afterPropertiesSet(); this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class)); @@ -93,7 +93,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests { public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse() throws Exception { AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException("")); + given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); this.filter.setContinueFilterChainOnUnsuccessfulAuthentication(false); this.filter.setAuthenticationManager(am); this.filter.afterPropertiesSet(); @@ -238,8 +238,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests { filter.setAuthenticationFailureHandler(new ForwardAuthenticationFailureHandler("/forwardUrl")); filter.setCheckForPrincipalChanges(true); AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(any(PreAuthenticatedAuthenticationToken.class))) - .thenThrow(new PreAuthenticatedCredentialsNotFoundException("invalid")); + given(am.authenticate(any(PreAuthenticatedAuthenticationToken.class))) + .willThrow(new PreAuthenticatedCredentialsNotFoundException("invalid")); filter.setAuthenticationManager(am); filter.afterPropertiesSet(); @@ -418,11 +418,11 @@ public class AbstractPreAuthenticatedProcessingFilterTests { AuthenticationManager am = mock(AuthenticationManager.class); if (!grantAccess) { - when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException("")); + given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); } else { - when(am.authenticate(any(Authentication.class))) - .thenAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); + given(am.authenticate(any(Authentication.class))) + .willAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); } filter.setAuthenticationManager(am); diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilterTests.java index 73bdc2b076..5f1ef577d4 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilterTests.java @@ -29,8 +29,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.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * @author Milan Sevcik @@ -149,8 +149,8 @@ public class RequestAttributeAuthenticationFilterTests { */ private AuthenticationManager createAuthenticationManager() { AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(any(Authentication.class))) - .thenAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); + given(am.authenticate(any(Authentication.class))) + .willAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); return am; } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java index 11b36ed7bf..41d857c928 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java @@ -31,8 +31,8 @@ import org.springframework.security.web.authentication.preauth.RequestHeaderAuth 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 Luke Taylor @@ -150,8 +150,8 @@ public class RequestHeaderAuthenticationFilterTests { */ private AuthenticationManager createAuthenticationManager() { AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(any(Authentication.class))) - .thenAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); + given(am.authenticate(any(Authentication.class))) + .willAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); return am; } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java index e4c818d23c..d5edb037d5 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java @@ -30,8 +30,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.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * @author Luke Taylor @@ -47,14 +47,14 @@ public class WebSpherePreAuthenticatedProcessingFilterTests { public void principalsAndCredentialsAreExtractedCorrectly() throws Exception { new WebSpherePreAuthenticatedProcessingFilter(); WASUsernameAndGroupsExtractor helper = mock(WASUsernameAndGroupsExtractor.class); - when(helper.getCurrentUserName()).thenReturn("jerry"); + given(helper.getCurrentUserName()).willReturn("jerry"); WebSpherePreAuthenticatedProcessingFilter filter = new WebSpherePreAuthenticatedProcessingFilter(helper); assertThat(filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest())).isEqualTo("jerry"); assertThat(filter.getPreAuthenticatedCredentials(new MockHttpServletRequest())).isEqualTo("N/A"); AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(any(Authentication.class))) - .thenAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); + given(am.authenticate(any(Authentication.class))) + .willAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); filter.setAuthenticationManager(am); WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource( diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java index 0f2b2c693b..0835c51e80 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImplTests.java @@ -41,10 +41,10 @@ import static org.assertj.core.api.Assertions.assertThat; 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.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; /** * @author Luke Taylor @@ -133,7 +133,7 @@ public class JdbcTokenRepositoryImplTests { // SEC-1964 @Test public void retrievingTokenWithNoSeriesReturnsNull() { - when(this.logger.isDebugEnabled()).thenReturn(true); + given(this.logger.isDebugEnabled()).willReturn(true); assertThat(this.repo.getTokenForSeries("missingSeries")).isNull(); diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java index e5892cf3c6..595a5c8353 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/RememberMeAuthenticationFilterTests.java @@ -39,10 +39,10 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationSu 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; /** * Tests {@link RememberMeAuthenticationFilter}. @@ -98,7 +98,7 @@ public class RememberMeAuthenticationFilterTests { @Test public void testOperationWhenNoAuthenticationInContextHolder() throws Exception { AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(this.remembered)).thenReturn(this.remembered); + given(am.authenticate(this.remembered)).willReturn(this.remembered); RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered)); @@ -118,7 +118,7 @@ public class RememberMeAuthenticationFilterTests { public void onUnsuccessfulLoginIsCalledWhenProviderRejectsAuth() throws Exception { final Authentication failedAuth = new TestingAuthenticationToken("failed", ""); AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException("")); + given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered)) { @@ -144,7 +144,7 @@ public class RememberMeAuthenticationFilterTests { @Test public void authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet() throws Exception { AuthenticationManager am = mock(AuthenticationManager.class); - when(am.authenticate(this.remembered)).thenReturn(this.remembered); + given(am.authenticate(this.remembered)).willReturn(this.remembered); RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered)); filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target")); diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java index 526b9a0cbe..0f4608bee7 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java @@ -38,8 +38,8 @@ import org.springframework.util.StringUtils; 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; 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; import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.TWO_WEEKS_S; @@ -67,15 +67,15 @@ public class TokenBasedRememberMeServicesTests { } void udsWillReturnUser() { - when(this.uds.loadUserByUsername(any(String.class))).thenReturn(this.user); + given(this.uds.loadUserByUsername(any(String.class))).willReturn(this.user); } void udsWillThrowNotFound() { - when(this.uds.loadUserByUsername(any(String.class))).thenThrow(new UsernameNotFoundException("")); + given(this.uds.loadUserByUsername(any(String.class))).willThrow(new UsernameNotFoundException("")); } void udsWillReturnNull() { - when(this.uds.loadUserByUsername(any(String.class))).thenReturn(null); + given(this.uds.loadUserByUsername(any(String.class))).willReturn(null); } private long determineExpiryTimeFromBased64EncodedToken(String validToken) { diff --git a/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java b/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java index c840dd570b..087c6bc578 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java @@ -30,7 +30,7 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.doThrow; +import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -83,8 +83,8 @@ public class CompositeSessionAuthenticationStrategyTests { @Test public void delegateShortCircuits() { - doThrow(new SessionAuthenticationException("oops")).when(this.strategy1).onAuthentication(this.authentication, - this.request, this.response); + willThrow(new SessionAuthenticationException("oops")).given(this.strategy1) + .onAuthentication(this.authentication, this.request, this.response); CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy( Arrays.asList(this.strategy1, this.strategy2)); diff --git a/web/src/test/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlAuthenticationStrategyTests.java b/web/src/test/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlAuthenticationStrategyTests.java index 9bcfc4b7dd..0f10d0e19c 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlAuthenticationStrategyTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/session/ConcurrentSessionControlAuthenticationStrategyTests.java @@ -38,7 +38,7 @@ import org.springframework.security.core.session.SessionRegistry; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -78,8 +78,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests { @Test public void noRegisteredSession() { - when(this.sessionRegistry.getAllSessions(any(), anyBoolean())) - .thenReturn(Collections.emptyList()); + given(this.sessionRegistry.getAllSessions(any(), anyBoolean())) + .willReturn(Collections.emptyList()); this.strategy.setMaximumSessions(1); this.strategy.setExceptionIfMaximumExceeded(true); @@ -92,8 +92,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests { public void maxSessionsSameSessionId() { MockHttpSession session = new MockHttpSession(new MockServletContext(), this.sessionInformation.getSessionId()); this.request.setSession(session); - when(this.sessionRegistry.getAllSessions(any(), anyBoolean())) - .thenReturn(Collections.singletonList(this.sessionInformation)); + given(this.sessionRegistry.getAllSessions(any(), anyBoolean())) + .willReturn(Collections.singletonList(this.sessionInformation)); this.strategy.setMaximumSessions(1); this.strategy.setExceptionIfMaximumExceeded(true); @@ -104,8 +104,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests { @Test(expected = SessionAuthenticationException.class) public void maxSessionsWithException() { - when(this.sessionRegistry.getAllSessions(any(), anyBoolean())) - .thenReturn(Collections.singletonList(this.sessionInformation)); + given(this.sessionRegistry.getAllSessions(any(), anyBoolean())) + .willReturn(Collections.singletonList(this.sessionInformation)); this.strategy.setMaximumSessions(1); this.strategy.setExceptionIfMaximumExceeded(true); @@ -114,8 +114,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests { @Test public void maxSessionsExpireExistingUser() { - when(this.sessionRegistry.getAllSessions(any(), anyBoolean())) - .thenReturn(Collections.singletonList(this.sessionInformation)); + given(this.sessionRegistry.getAllSessions(any(), anyBoolean())) + .willReturn(Collections.singletonList(this.sessionInformation)); this.strategy.setMaximumSessions(1); this.strategy.onAuthentication(this.authentication, this.request, this.response); @@ -127,8 +127,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests { public void maxSessionsExpireLeastRecentExistingUser() { SessionInformation moreRecentSessionInfo = new SessionInformation(this.authentication.getPrincipal(), "unique", new Date(1374766999999L)); - when(this.sessionRegistry.getAllSessions(any(), anyBoolean())) - .thenReturn(Arrays.asList(moreRecentSessionInfo, this.sessionInformation)); + given(this.sessionRegistry.getAllSessions(any(), anyBoolean())) + .willReturn(Arrays.asList(moreRecentSessionInfo, this.sessionInformation)); this.strategy.setMaximumSessions(2); this.strategy.onAuthentication(this.authentication, this.request, this.response); @@ -142,7 +142,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests { new Date(1374766134214L)); SessionInformation secondOldestSessionInfo = new SessionInformation(this.authentication.getPrincipal(), "unique2", new Date(1374766134215L)); - when(this.sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn( + given(this.sessionRegistry.getAllSessions(any(), anyBoolean())).willReturn( Arrays.asList(oldestSessionInfo, secondOldestSessionInfo, this.sessionInformation)); this.strategy.setMaximumSessions(2); diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java index 9367eac111..39a7ac7655 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationFilterTests.java @@ -44,10 +44,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.AdditionalMatchers.not; 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 {@link BasicAuthenticationFilter}. @@ -69,8 +69,8 @@ public class BasicAuthenticationFilterTests { AuthorityUtils.createAuthorityList("ROLE_1")); this.manager = mock(AuthenticationManager.class); - when(this.manager.authenticate(rodRequest)).thenReturn(rod); - when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException("")); + given(this.manager.authenticate(rodRequest)).willReturn(rod); + given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException("")); this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint()); } @@ -312,8 +312,8 @@ public class BasicAuthenticationFilterTests { AuthorityUtils.createAuthorityList("ROLE_1")); this.manager = mock(AuthenticationManager.class); - when(this.manager.authenticate(rodRequest)).thenReturn(rod); - when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException("")); + given(this.manager.authenticate(rodRequest)).willReturn(rod); + given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException("")); this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint()); @@ -347,8 +347,8 @@ public class BasicAuthenticationFilterTests { AuthorityUtils.createAuthorityList("ROLE_1")); this.manager = mock(AuthenticationManager.class); - when(this.manager.authenticate(rodRequest)).thenReturn(rod); - when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException("")); + given(this.manager.authenticate(rodRequest)).willReturn(rod); + given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException("")); this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint()); this.filter.setCredentialsCharset("ISO-8859-1"); @@ -383,8 +383,8 @@ public class BasicAuthenticationFilterTests { AuthorityUtils.createAuthorityList("ROLE_1")); this.manager = mock(AuthenticationManager.class); - when(this.manager.authenticate(rodRequest)).thenReturn(rod); - when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException("")); + given(this.manager.authenticate(rodRequest)).willReturn(rod); + given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException("")); this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint()); this.filter.setCredentialsCharset("ISO-8859-1"); diff --git a/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java b/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java index 57c42e4f6b..e6bd2892d6 100644 --- a/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/concurrent/ConcurrentSessionFilterTests.java @@ -44,10 +44,10 @@ import static org.assertj.core.api.Assertions.assertThat; 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.verify; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * Tests {@link ConcurrentSessionFilter}. @@ -179,7 +179,7 @@ public class ConcurrentSessionFilterTests { SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000)); information.expireNow(); - when(registry.getSessionInformation(anyString())).thenReturn(information); + given(registry.getSessionInformation(anyString())).willReturn(information); String expiredUrl = "/expired"; ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl); @@ -224,7 +224,7 @@ public class ConcurrentSessionFilterTests { SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000)); information.expireNow(); - when(registry.getSessionInformation(anyString())).thenReturn(information); + given(registry.getSessionInformation(anyString())).willReturn(information); String expiredUrl = "/expired"; ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl); @@ -247,7 +247,7 @@ public class ConcurrentSessionFilterTests { SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000)); information.expireNow(); - when(registry.getSessionInformation(anyString())).thenReturn(information); + given(registry.getSessionInformation(anyString())).willReturn(information); final String expiredUrl = "/expired"; ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl + "will-be-overrridden") { @@ -276,7 +276,7 @@ public class ConcurrentSessionFilterTests { SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000)); information.expireNow(); - when(registry.getSessionInformation(anyString())).thenReturn(information); + given(registry.getSessionInformation(anyString())).willReturn(information); ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry); @@ -298,7 +298,7 @@ public class ConcurrentSessionFilterTests { SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000)); information.expireNow(); - when(registry.getSessionInformation(anyString())).thenReturn(information); + given(registry.getSessionInformation(anyString())).willReturn(information); ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry); filter.setLogoutHandlers(new LogoutHandler[] { handler }); diff --git a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java index 8bd39186b2..b4c15c2db7 100644 --- a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java @@ -34,10 +34,10 @@ import org.springframework.security.core.context.SecurityContextImpl; 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.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.when; public class SecurityContextPersistenceFilterTests { @@ -68,7 +68,7 @@ public class SecurityContextPersistenceFilterTests { final MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(); SecurityContextHolder.getContext().setAuthentication(this.testToken); - doThrow(new IOException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); + willThrow(new IOException()).given(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); try { filter.doFilter(request, response, chain); fail("IOException should have been thrown"); @@ -91,7 +91,7 @@ public class SecurityContextPersistenceFilterTests { final SecurityContextRepository repo = mock(SecurityContextRepository.class); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo); - when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore); + given(repo.loadContext(any(HttpRequestResponseHolder.class))).willReturn(scBefore); final FilterChain chain = (request1, response1) -> { assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth); diff --git a/web/src/test/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilterTests.java b/web/src/test/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilterTests.java index ca1b3b84d6..2242f64dd1 100644 --- a/web/src/test/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/context/request/async/WebAsyncManagerIntegrationFilterTests.java @@ -39,7 +39,7 @@ import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -79,7 +79,7 @@ public class WebAsyncManagerIntegrationFilterTests { this.asyncManager = WebAsyncUtils.getAsyncManager(this.request); this.asyncManager.setAsyncWebRequest(this.asyncWebRequest); this.asyncManager.setTaskExecutor(executor); - when(this.request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).thenReturn(this.asyncManager); + given(this.request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).willReturn(this.asyncManager); this.filter = new WebAsyncManagerIntegrationFilter(); } diff --git a/web/src/test/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategyTests.java b/web/src/test/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategyTests.java index 56d3606318..3ea7571f82 100644 --- a/web/src/test/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategyTests.java +++ b/web/src/test/java/org/springframework/security/web/csrf/CsrfAuthenticationStrategyTests.java @@ -31,9 +31,9 @@ import org.springframework.security.authentication.TestingAuthenticationToken; 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.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -72,8 +72,8 @@ public class CsrfAuthenticationStrategyTests { @Test public void logoutRemovesCsrfTokenAndSavesNew() { - when(this.csrfTokenRepository.loadToken(this.request)).thenReturn(this.existingToken); - when(this.csrfTokenRepository.generateToken(this.request)).thenReturn(this.generatedToken); + given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken); + given(this.csrfTokenRepository.generateToken(this.request)).willReturn(this.generatedToken); this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request, this.response); @@ -93,8 +93,8 @@ public class CsrfAuthenticationStrategyTests { public void delaySavingCsrf() { this.strategy = new CsrfAuthenticationStrategy(new LazyCsrfTokenRepository(this.csrfTokenRepository)); - when(this.csrfTokenRepository.loadToken(this.request)).thenReturn(this.existingToken); - when(this.csrfTokenRepository.generateToken(this.request)).thenReturn(this.generatedToken); + given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken); + given(this.csrfTokenRepository.generateToken(this.request)).willReturn(this.generatedToken); this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request, this.response); diff --git a/web/src/test/java/org/springframework/security/web/csrf/CsrfFilterTests.java b/web/src/test/java/org/springframework/security/web/csrf/CsrfFilterTests.java index 412a63f81e..df217454e2 100644 --- a/web/src/test/java/org/springframework/security/web/csrf/CsrfFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/csrf/CsrfFilterTests.java @@ -40,13 +40,13 @@ import org.springframework.security.web.util.matcher.RequestMatcher; 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.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -103,8 +103,8 @@ public class CsrfFilterTests { @Test public void doFilterDoesNotSaveCsrfTokenUntilAccessed() throws ServletException, IOException { this.filter = createCsrfFilter(new LazyCsrfTokenRepository(this.tokenRepository)); - when(this.requestMatcher.matches(this.request)).thenReturn(false); - when(this.tokenRepository.generateToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(false); + given(this.tokenRepository.generateToken(this.request)).willReturn(this.token); this.filter.doFilter(this.request, this.response, this.filterChain); CsrfToken attrToken = (CsrfToken) this.request.getAttribute(this.token.getParameterName()); @@ -124,8 +124,8 @@ public class CsrfFilterTests { @Test public void doFilterAccessDeniedNoTokenPresent() throws ServletException, IOException { - when(this.requestMatcher.matches(this.request)).thenReturn(true); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(true); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -138,8 +138,8 @@ public class CsrfFilterTests { @Test public void doFilterAccessDeniedIncorrectTokenPresent() throws ServletException, IOException { - when(this.requestMatcher.matches(this.request)).thenReturn(true); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(true); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.request.setParameter(this.token.getParameterName(), this.token.getToken() + " INVALID"); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -153,8 +153,8 @@ public class CsrfFilterTests { @Test public void doFilterAccessDeniedIncorrectTokenPresentHeader() throws ServletException, IOException { - when(this.requestMatcher.matches(this.request)).thenReturn(true); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(true); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.request.addHeader(this.token.getHeaderName(), this.token.getToken() + " INVALID"); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -169,8 +169,8 @@ public class CsrfFilterTests { @Test public void doFilterAccessDeniedIncorrectTokenPresentHeaderPreferredOverParameter() throws ServletException, IOException { - when(this.requestMatcher.matches(this.request)).thenReturn(true); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(true); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.request.setParameter(this.token.getParameterName(), this.token.getToken()); this.request.addHeader(this.token.getHeaderName(), this.token.getToken() + " INVALID"); @@ -185,8 +185,8 @@ public class CsrfFilterTests { @Test public void doFilterNotCsrfRequestExistingToken() throws ServletException, IOException { - when(this.requestMatcher.matches(this.request)).thenReturn(false); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(false); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -199,8 +199,8 @@ public class CsrfFilterTests { @Test public void doFilterNotCsrfRequestGenerateToken() throws ServletException, IOException { - when(this.requestMatcher.matches(this.request)).thenReturn(false); - when(this.tokenRepository.generateToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(false); + given(this.tokenRepository.generateToken(this.request)).willReturn(this.token); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -213,8 +213,8 @@ public class CsrfFilterTests { @Test public void doFilterIsCsrfRequestExistingTokenHeader() throws ServletException, IOException { - when(this.requestMatcher.matches(this.request)).thenReturn(true); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(true); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.request.addHeader(this.token.getHeaderName(), this.token.getToken()); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -229,8 +229,8 @@ public class CsrfFilterTests { @Test public void doFilterIsCsrfRequestExistingTokenHeaderPreferredOverInvalidParam() throws ServletException, IOException { - when(this.requestMatcher.matches(this.request)).thenReturn(true); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(true); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.request.setParameter(this.token.getParameterName(), this.token.getToken() + " INVALID"); this.request.addHeader(this.token.getHeaderName(), this.token.getToken()); @@ -245,8 +245,8 @@ public class CsrfFilterTests { @Test public void doFilterIsCsrfRequestExistingToken() throws ServletException, IOException { - when(this.requestMatcher.matches(this.request)).thenReturn(true); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(true); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.request.setParameter(this.token.getParameterName(), this.token.getToken()); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -262,8 +262,8 @@ public class CsrfFilterTests { @Test public void doFilterIsCsrfRequestGenerateToken() throws ServletException, IOException { - when(this.requestMatcher.matches(this.request)).thenReturn(true); - when(this.tokenRepository.generateToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(true); + given(this.tokenRepository.generateToken(this.request)).willReturn(this.token); this.request.setParameter(this.token.getParameterName(), this.token.getToken()); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -286,7 +286,7 @@ public class CsrfFilterTests { for (String method : Arrays.asList("GET", "TRACE", "OPTIONS", "HEAD")) { resetRequestResponse(); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.request.setMethod(method); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -309,7 +309,7 @@ public class CsrfFilterTests { for (String method : Arrays.asList("get", "TrAcE", "oPTIOnS", "hEaD")) { resetRequestResponse(); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.request.setMethod(method); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -327,7 +327,7 @@ public class CsrfFilterTests { for (String method : Arrays.asList("POST", "PUT", "PATCH", "DELETE", "INVALID")) { resetRequestResponse(); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.request.setMethod(method); this.filter.doFilter(this.request, this.response, this.filterChain); @@ -342,8 +342,8 @@ public class CsrfFilterTests { public void doFilterDefaultAccessDenied() throws ServletException, IOException { this.filter = new CsrfFilter(this.tokenRepository); this.filter.setRequireCsrfProtectionMatcher(this.requestMatcher); - when(this.requestMatcher.matches(this.request)).thenReturn(true); - when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token); + given(this.requestMatcher.matches(this.request)).willReturn(true); + given(this.tokenRepository.loadToken(this.request)).willReturn(this.token); this.filter.doFilter(this.request, this.response, this.filterChain); diff --git a/web/src/test/java/org/springframework/security/web/csrf/LazyCsrfTokenRepositoryTests.java b/web/src/test/java/org/springframework/security/web/csrf/LazyCsrfTokenRepositoryTests.java index ffbb94f2a5..36bc4b0284 100644 --- a/web/src/test/java/org/springframework/security/web/csrf/LazyCsrfTokenRepositoryTests.java +++ b/web/src/test/java/org/springframework/security/web/csrf/LazyCsrfTokenRepositoryTests.java @@ -27,10 +27,10 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; 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.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -55,8 +55,8 @@ public class LazyCsrfTokenRepositoryTests { @Before public void setup() { this.token = new DefaultCsrfToken("header", "param", "token"); - when(this.delegate.generateToken(this.request)).thenReturn(this.token); - when(this.request.getAttribute(HttpServletResponse.class.getName())).thenReturn(this.response); + given(this.delegate.generateToken(this.request)).willReturn(this.token); + given(this.request.getAttribute(HttpServletResponse.class.getName())).willReturn(this.response); } @Test(expected = IllegalArgumentException.class) @@ -94,7 +94,7 @@ public class LazyCsrfTokenRepositoryTests { @Test public void loadTokenDelegates() { - when(this.delegate.loadToken(this.request)).thenReturn(this.token); + given(this.delegate.loadToken(this.request)).willReturn(this.token); CsrfToken loadToken = this.repository.loadToken(this.request); assertThat(loadToken).isSameAs(this.token); diff --git a/web/src/test/java/org/springframework/security/web/debug/DebugFilterTests.java b/web/src/test/java/org/springframework/security/web/debug/DebugFilterTests.java index 2d0cf0248e..c9d76279df 100644 --- a/web/src/test/java/org/springframework/security/web/debug/DebugFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/debug/DebugFilterTests.java @@ -39,9 +39,9 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -78,8 +78,8 @@ public class DebugFilterTests { @Before public void setUp() { - when(this.request.getHeaderNames()).thenReturn(Collections.enumeration(Collections.emptyList())); - when(this.request.getServletPath()).thenReturn("/login"); + given(this.request.getHeaderNames()).willReturn(Collections.enumeration(Collections.emptyList())); + given(this.request.getServletPath()).willReturn("/login"); this.filter = new DebugFilter(this.fcp); ReflectionTestUtils.setField(this.filter, "logger", this.logger); this.requestAttr = DebugFilter.ALREADY_FILTERED_ATTR_NAME; @@ -99,7 +99,7 @@ public class DebugFilterTests { // SEC-1901 @Test public void doFilterProcessesForwardedRequests() throws Exception { - when(this.request.getAttribute(this.requestAttr)).thenReturn(Boolean.TRUE); + given(this.request.getAttribute(this.requestAttr)).willReturn(Boolean.TRUE); HttpServletRequest request = new DebugRequestWrapper(this.request); this.filter.doFilter(request, this.response, this.filterChain); @@ -111,7 +111,7 @@ public class DebugFilterTests { @Test public void doFilterDoesNotWrapWithDebugRequestWrapperAgain() throws Exception { - when(this.request.getAttribute(this.requestAttr)).thenReturn(Boolean.TRUE); + given(this.request.getAttribute(this.requestAttr)).willReturn(Boolean.TRUE); HttpServletRequest fireWalledRequest = new HttpServletRequestWrapper(new DebugRequestWrapper(this.request)); this.filter.doFilter(fireWalledRequest, this.response, this.filterChain); diff --git a/web/src/test/java/org/springframework/security/web/firewall/RequestWrapperTests.java b/web/src/test/java/org/springframework/security/web/firewall/RequestWrapperTests.java index b4e92e8c64..378122d10e 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/RequestWrapperTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/RequestWrapperTests.java @@ -28,11 +28,11 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; 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.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; /** * @author Luke Taylor @@ -93,9 +93,9 @@ public class RequestWrapperTests { HttpServletRequest mockRequest = mock(HttpServletRequest.class); HttpServletResponse mockResponse = mock(HttpServletResponse.class); RequestDispatcher mockDispatcher = mock(RequestDispatcher.class); - when(mockRequest.getServletPath()).thenReturn(""); - when(mockRequest.getPathInfo()).thenReturn(denormalizedPath); - when(mockRequest.getRequestDispatcher(forwardPath)).thenReturn(mockDispatcher); + given(mockRequest.getServletPath()).willReturn(""); + given(mockRequest.getPathInfo()).willReturn(denormalizedPath); + given(mockRequest.getRequestDispatcher(forwardPath)).willReturn(mockDispatcher); RequestWrapper wrapper = new RequestWrapper(mockRequest); RequestDispatcher dispatcher = wrapper.getRequestDispatcher(forwardPath); @@ -116,7 +116,7 @@ public class RequestWrapperTests { String path = "/forward/path"; HttpServletRequest request = mock(HttpServletRequest.class); RequestDispatcher dispatcher = mock(RequestDispatcher.class); - when(request.getRequestDispatcher(path)).thenReturn(dispatcher); + given(request.getRequestDispatcher(path)).willReturn(dispatcher); RequestWrapper wrapper = new RequestWrapper(request); wrapper.reset(); assertThat(wrapper.getRequestDispatcher(path)).isSameAs(dispatcher); diff --git a/web/src/test/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriterTests.java b/web/src/test/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriterTests.java index f80b2cafef..2c5469247d 100644 --- a/web/src/test/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriterTests.java +++ b/web/src/test/java/org/springframework/security/web/header/writers/DelegatingRequestMatcherHeaderWriterTests.java @@ -26,9 +26,9 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.web.header.HeaderWriter; import org.springframework.security.web.util.matcher.RequestMatcher; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -68,7 +68,7 @@ public class DelegatingRequestMatcherHeaderWriterTests { @Test public void writeHeadersOnMatch() { - when(this.matcher.matches(this.request)).thenReturn(true); + given(this.matcher.matches(this.request)).willReturn(true); this.headerWriter.writeHeaders(this.request, this.response); @@ -77,7 +77,7 @@ public class DelegatingRequestMatcherHeaderWriterTests { @Test public void writeHeadersOnNoMatch() { - when(this.matcher.matches(this.request)).thenReturn(false); + given(this.matcher.matches(this.request)).willReturn(false); this.headerWriter.writeHeaders(this.request, this.response); diff --git a/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/FrameOptionsHeaderWriterTests.java b/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/FrameOptionsHeaderWriterTests.java index 52fc10499f..e3a2af46df 100644 --- a/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/FrameOptionsHeaderWriterTests.java +++ b/web/src/test/java/org/springframework/security/web/header/writers/frameoptions/FrameOptionsHeaderWriterTests.java @@ -26,7 +26,7 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter.XFrameOptionsMode; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -77,7 +77,7 @@ public class FrameOptionsHeaderWriterTests { @Test public void writeHeadersAllowFrom() { String allowFromValue = "https://example.com/"; - when(this.strategy.getAllowFromValue(this.request)).thenReturn(allowFromValue); + given(this.strategy.getAllowFromValue(this.request)).willReturn(allowFromValue); this.writer = new XFrameOptionsHeaderWriter(this.strategy); this.writer.writeHeaders(this.request, this.response); diff --git a/web/src/test/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolverTests.java b/web/src/test/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolverTests.java index ec368956ee..6bfabe3794 100644 --- a/web/src/test/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolverTests.java +++ b/web/src/test/java/org/springframework/security/web/reactive/result/method/annotation/AuthenticationPrincipalArgumentResolverTests.java @@ -43,7 +43,7 @@ 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.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -93,7 +93,7 @@ public class AuthenticationPrincipalArgumentResolverTests { @Test public void resolveArgumentWhenIsAuthenticationThenObtainsPrincipal() { MethodParameter parameter = this.authenticationPrincipal.arg(String.class); - when(this.authentication.getPrincipal()).thenReturn("user"); + given(this.authentication.getPrincipal()).willReturn("user"); Mono argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); @@ -114,7 +114,7 @@ public class AuthenticationPrincipalArgumentResolverTests { @Test public void resolveArgumentWhenMonoIsAuthenticationThenObtainsPrincipal() { MethodParameter parameter = this.authenticationPrincipal.arg(Mono.class, String.class); - when(this.authentication.getPrincipal()).thenReturn("user"); + given(this.authentication.getPrincipal()).willReturn("user"); Mono argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); @@ -126,7 +126,7 @@ public class AuthenticationPrincipalArgumentResolverTests { public void resolveArgumentWhenMonoIsAuthenticationAndNoGenericThenObtainsPrincipal() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("authenticationPrincipalNoGeneric").build() .arg(Mono.class); - when(this.authentication.getPrincipal()).thenReturn("user"); + given(this.authentication.getPrincipal()).willReturn("user"); Mono argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); @@ -138,7 +138,7 @@ public class AuthenticationPrincipalArgumentResolverTests { public void resolveArgumentWhenSpelThenObtainsPrincipal() { MyUser user = new MyUser(3L); MethodParameter parameter = this.spel.arg(Long.class); - when(this.authentication.getPrincipal()).thenReturn(user); + given(this.authentication.getPrincipal()).willReturn(user); Mono argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); @@ -150,8 +150,8 @@ public class AuthenticationPrincipalArgumentResolverTests { public void resolveArgumentWhenBeanThenObtainsPrincipal() throws Exception { MyUser user = new MyUser(3L); MethodParameter parameter = this.bean.arg(Long.class); - when(this.authentication.getPrincipal()).thenReturn(user); - when(this.beanResolver.resolve(any(), eq("beanName"))).thenReturn(new Bean()); + given(this.authentication.getPrincipal()).willReturn(user); + given(this.beanResolver.resolve(any(), eq("beanName"))).willReturn(new Bean()); Mono argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); @@ -162,7 +162,7 @@ public class AuthenticationPrincipalArgumentResolverTests { @Test public void resolveArgumentWhenMetaThenObtainsPrincipal() { MethodParameter parameter = this.meta.arg(String.class); - when(this.authentication.getPrincipal()).thenReturn("user"); + given(this.authentication.getPrincipal()).willReturn("user"); Mono argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); @@ -174,7 +174,7 @@ public class AuthenticationPrincipalArgumentResolverTests { public void resolveArgumentWhenErrorOnInvalidTypeImplicit() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenImplicit").build() .arg(Integer.class); - when(this.authentication.getPrincipal()).thenReturn("user"); + given(this.authentication.getPrincipal()).willReturn("user"); Mono argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); @@ -186,7 +186,7 @@ public class AuthenticationPrincipalArgumentResolverTests { public void resolveArgumentWhenErrorOnInvalidTypeExplicitFalse() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitFalse").build() .arg(Integer.class); - when(this.authentication.getPrincipal()).thenReturn("user"); + given(this.authentication.getPrincipal()).willReturn("user"); Mono argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); @@ -198,7 +198,7 @@ public class AuthenticationPrincipalArgumentResolverTests { public void resolveArgumentWhenErrorOnInvalidTypeExplicitTrue() { MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitTrue").build() .arg(Integer.class); - when(this.authentication.getPrincipal()).thenReturn("user"); + given(this.authentication.getPrincipal()).willReturn("user"); Mono argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); diff --git a/web/src/test/java/org/springframework/security/web/server/DelegatingServerAuthenticationEntryPointTests.java b/web/src/test/java/org/springframework/security/web/server/DelegatingServerAuthenticationEntryPointTests.java index ccd315867f..924a940fd4 100644 --- a/web/src/test/java/org/springframework/security/web/server/DelegatingServerAuthenticationEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/server/DelegatingServerAuthenticationEntryPointTests.java @@ -32,9 +32,9 @@ import org.springframework.security.web.server.util.matcher.ServerWebExchangeMat import org.springframework.web.server.ServerWebExchange; 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.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -64,9 +64,9 @@ public class DelegatingServerAuthenticationEntryPointTests { @Test public void commenceWhenNotMatchThenMatchThenOnlySecondDelegateInvoked() { Mono expectedResult = Mono.empty(); - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); - when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match()); - when(this.delegate2.commence(this.exchange, this.e)).thenReturn(expectedResult); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match()); + given(this.delegate2.commence(this.exchange, this.e)).willReturn(expectedResult); this.entryPoint = new DelegatingServerAuthenticationEntryPoint(new DelegateEntry(this.matcher1, this.delegate1), new DelegateEntry(this.matcher2, this.delegate2)); @@ -79,7 +79,7 @@ public class DelegatingServerAuthenticationEntryPointTests { @Test public void commenceWhenNotMatchThenDefault() { - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); this.entryPoint = new DelegatingServerAuthenticationEntryPoint( new DelegateEntry(this.matcher1, this.delegate1)); diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcherTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcherTests.java index 92c76b25e3..9cee39d0d9 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcherTests.java @@ -31,7 +31,7 @@ import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author David Kovac @@ -63,35 +63,35 @@ public class AuthenticationConverterServerWebExchangeMatcherTests { @Test public void matchesWhenNotEmptyThenReturnTrue() { - when(this.converter.convert(any())).thenReturn(Mono.just(this.authentication)); + given(this.converter.convert(any())).willReturn(Mono.just(this.authentication)); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue(); } @Test public void matchesWhenEmptyThenReturnFalse() { - when(this.converter.convert(any())).thenReturn(Mono.empty()); + given(this.converter.convert(any())).willReturn(Mono.empty()); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse(); } @Test public void matchesWhenErrorThenReturnFalse() { - when(this.converter.convert(any())).thenReturn(Mono.error(new RuntimeException())); + given(this.converter.convert(any())).willReturn(Mono.error(new RuntimeException())); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse(); } @Test public void matchesWhenNullThenThrowsException() { - when(this.converter.convert(any())).thenReturn(null); + given(this.converter.convert(any())).willReturn(null); assertThatCode(() -> this.matcher.matches(this.exchange).block()).isInstanceOf(NullPointerException.class); } @Test public void matchesWhenExceptionThenPropagates() { - when(this.converter.convert(any())).thenThrow(RuntimeException.class); + given(this.converter.convert(any())).willThrow(RuntimeException.class); assertThatCode(() -> this.matcher.matches(this.exchange).block()).isInstanceOf(RuntimeException.class); } diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationWebFilterTests.java index 0850d3cdff..6e381d1220 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/AuthenticationWebFilterTests.java @@ -38,10 +38,10 @@ import org.springframework.web.server.ServerWebExchange; 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.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -110,8 +110,8 @@ public class AuthenticationWebFilterTests { @Test public void filterWhenDefaultsAndAuthenticationSuccessThenContinues() { - when(this.authenticationManager.authenticate(any())) - .thenReturn(Mono.just(new TestingAuthenticationToken("test", "this", "ROLE"))); + given(this.authenticationManager.authenticate(any())) + .willReturn(Mono.just(new TestingAuthenticationToken("test", "this", "ROLE"))); this.filter = new AuthenticationWebFilter(this.authenticationManager); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); @@ -126,9 +126,9 @@ public class AuthenticationWebFilterTests { @Test public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationSuccessThenContinues() { - when(this.authenticationManager.authenticate(any())) - .thenReturn(Mono.just(new TestingAuthenticationToken("test", "this", "ROLE"))); - when(this.authenticationManagerResolver.resolve(any())).thenReturn(Mono.just(this.authenticationManager)); + given(this.authenticationManager.authenticate(any())) + .willReturn(Mono.just(new TestingAuthenticationToken("test", "this", "ROLE"))); + given(this.authenticationManagerResolver.resolve(any())).willReturn(Mono.just(this.authenticationManager)); this.filter = new AuthenticationWebFilter(this.authenticationManagerResolver); @@ -144,8 +144,8 @@ public class AuthenticationWebFilterTests { @Test public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() { - when(this.authenticationManager.authenticate(any())) - .thenReturn(Mono.error(new BadCredentialsException("failed"))); + given(this.authenticationManager.authenticate(any())) + .willReturn(Mono.error(new BadCredentialsException("failed"))); this.filter = new AuthenticationWebFilter(this.authenticationManager); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); @@ -159,9 +159,9 @@ public class AuthenticationWebFilterTests { @Test public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized() { - when(this.authenticationManager.authenticate(any())) - .thenReturn(Mono.error(new BadCredentialsException("failed"))); - when(this.authenticationManagerResolver.resolve(any())).thenReturn(Mono.just(this.authenticationManager)); + given(this.authenticationManager.authenticate(any())) + .willReturn(Mono.error(new BadCredentialsException("failed"))); + given(this.authenticationManagerResolver.resolve(any())).willReturn(Mono.just(this.authenticationManager)); this.filter = new AuthenticationWebFilter(this.authenticationManagerResolver); @@ -176,7 +176,7 @@ public class AuthenticationWebFilterTests { @Test public void filterWhenConvertEmptyThenOk() { - when(this.authenticationConverter.convert(any())).thenReturn(Mono.empty()); + given(this.authenticationConverter.convert(any())).willReturn(Mono.empty()); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); @@ -189,7 +189,7 @@ public class AuthenticationWebFilterTests { @Test public void filterWhenConvertErrorThenServerError() { - when(this.authenticationConverter.convert(any())).thenReturn(Mono.error(new RuntimeException("Unexpected"))); + given(this.authenticationConverter.convert(any())).willReturn(Mono.error(new RuntimeException("Unexpected"))); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); @@ -202,10 +202,10 @@ public class AuthenticationWebFilterTests { @Test public void filterWhenConvertAndAuthenticationSuccessThenSuccess() { Mono authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER")); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); - when(this.successHandler.onAuthenticationSuccess(any(), any())).thenReturn(Mono.empty()); - when(this.securityContextRepository.save(any(), any())).thenAnswer(a -> Mono.just(a.getArguments()[0])); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(authentication); + given(this.successHandler.onAuthenticationSuccess(any(), any())).willReturn(Mono.empty()); + given(this.securityContextRepository.save(any(), any())).willAnswer(a -> Mono.just(a.getArguments()[0])); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); @@ -219,8 +219,8 @@ public class AuthenticationWebFilterTests { @Test public void filterWhenConvertAndAuthenticationEmptyThenServerError() { Mono authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER")); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())).thenReturn(Mono.empty()); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(Mono.empty()); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); @@ -248,10 +248,10 @@ public class AuthenticationWebFilterTests { @Test public void filterWhenConvertAndAuthenticationFailThenEntryPoint() { Mono authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER")); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())) - .thenReturn(Mono.error(new BadCredentialsException("Failed"))); - when(this.failureHandler.onAuthenticationFailure(any(), any())).thenReturn(Mono.empty()); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())) + .willReturn(Mono.error(new BadCredentialsException("Failed"))); + given(this.failureHandler.onAuthenticationFailure(any(), any())).willReturn(Mono.empty()); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); @@ -265,8 +265,8 @@ public class AuthenticationWebFilterTests { @Test public void filterWhenConvertAndAuthenticationExceptionThenServerError() { Mono authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER")); - when(this.authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())).thenReturn(Mono.error(new RuntimeException("Failed"))); + given(this.authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new RuntimeException("Failed"))); WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build(); diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandlerTests.java index fabf198d03..4ced5bd408 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/DelegatingServerAuthenticationSuccessHandlerTests.java @@ -35,7 +35,7 @@ import org.springframework.security.web.server.WebFilterExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -62,8 +62,8 @@ public class DelegatingServerAuthenticationSuccessHandlerTests { @Before public void setup() { - when(this.delegate1.onAuthenticationSuccess(any(), any())).thenReturn(this.delegate1Result.mono()); - when(this.delegate2.onAuthenticationSuccess(any(), any())).thenReturn(this.delegate2Result.mono()); + given(this.delegate1.onAuthenticationSuccess(any(), any())).willReturn(this.delegate1Result.mono()); + given(this.delegate2.onAuthenticationSuccess(any(), any())).willReturn(this.delegate2Result.mono()); } @Test diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/ReactivePreAuthenticatedAuthenticationManagerTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/ReactivePreAuthenticatedAuthenticationManagerTests.java index 65ccc44332..f5e40368dd 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/ReactivePreAuthenticatedAuthenticationManagerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/ReactivePreAuthenticatedAuthenticationManagerTests.java @@ -33,8 +33,8 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedA import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * @author Alexey Nesterov @@ -62,7 +62,7 @@ public class ReactivePreAuthenticatedAuthenticationManagerTests { @Test public void returnsAuthenticatedTokenForValidAccount() { - when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.validAccount)); + given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.validAccount)); Authentication authentication = this.manager.authenticate(tokenForUser(this.validAccount.getUsername())) .block(); @@ -71,36 +71,36 @@ public class ReactivePreAuthenticatedAuthenticationManagerTests { @Test(expected = UsernameNotFoundException.class) public void returnsNullForNonExistingAccount() { - when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.empty()); + given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.empty()); this.manager.authenticate(tokenForUser(this.nonExistingAccount.getUsername())).block(); } @Test(expected = LockedException.class) public void throwsExceptionForLockedAccount() { - when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.lockedAccount)); + given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.lockedAccount)); this.manager.authenticate(tokenForUser(this.lockedAccount.getUsername())).block(); } @Test(expected = DisabledException.class) public void throwsExceptionForDisabledAccount() { - when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.disabledAccount)); + given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.disabledAccount)); this.manager.authenticate(tokenForUser(this.disabledAccount.getUsername())).block(); } @Test(expected = AccountExpiredException.class) public void throwsExceptionForExpiredAccount() { - when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.expiredAccount)); + given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.expiredAccount)); this.manager.authenticate(tokenForUser(this.expiredAccount.getUsername())).block(); } @Test(expected = CredentialsExpiredException.class) public void throwsExceptionForAccountWithExpiredCredentials() { - when(this.mockUserDetailsService.findByUsername(anyString())) - .thenReturn(Mono.just(this.accountWithExpiredCredentials)); + given(this.mockUserDetailsService.findByUsername(anyString())) + .willReturn(Mono.just(this.accountWithExpiredCredentials)); this.manager.authenticate(tokenForUser(this.accountWithExpiredCredentials.getUsername())).block(); } diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationEntryPointTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationEntryPointTests.java index 6630efac28..e6b075f2ad 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationEntryPointTests.java @@ -32,7 +32,7 @@ import org.springframework.web.server.ServerWebExchange; 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 @@ -82,7 +82,7 @@ public class RedirectServerAuthenticationEntryPointTests { @Test public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() { PublisherProbe redirectResult = PublisherProbe.empty(); - when(this.redirectStrategy.sendRedirect(any(), any())).thenReturn(redirectResult.mono()); + given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono()); this.entryPoint.setRedirectStrategy(this.redirectStrategy); this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationFailureHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationFailureHandlerTests.java index 9f884fb884..84b295f9ad 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationFailureHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationFailureHandlerTests.java @@ -34,7 +34,7 @@ import org.springframework.web.server.handler.DefaultWebFilterChain; 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 @@ -83,7 +83,7 @@ public class RedirectServerAuthenticationFailureHandlerTests { @Test public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() { PublisherProbe redirectResult = PublisherProbe.empty(); - when(this.redirectStrategy.sendRedirect(any(), any())).thenReturn(redirectResult.mono()); + given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono()); this.handler.setRedirectStrategy(this.redirectStrategy); this.exchange = createExchange(); diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationSuccessHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationSuccessHandlerTests.java index 178a18eae8..8fe06ccb91 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/RedirectServerAuthenticationSuccessHandlerTests.java @@ -36,8 +36,8 @@ import org.springframework.web.server.WebFilterChain; 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.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -91,7 +91,7 @@ public class RedirectServerAuthenticationSuccessHandlerTests { @Test public void successWhenCustomLocationThenCustomLocationUsed() { PublisherProbe redirectResult = PublisherProbe.empty(); - when(this.redirectStrategy.sendRedirect(any(), any())).thenReturn(redirectResult.mono()); + given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono()); this.handler.setRedirectStrategy(this.redirectStrategy); this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/ServerAuthenticationEntryPointFailureHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/ServerAuthenticationEntryPointFailureHandlerTests.java index e7490bc5d7..23d0288917 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/ServerAuthenticationEntryPointFailureHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/ServerAuthenticationEntryPointFailureHandlerTests.java @@ -30,7 +30,7 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -64,7 +64,7 @@ public class ServerAuthenticationEntryPointFailureHandlerTests { public void onAuthenticationFailureWhenInvokedThenDelegatesToEntryPoint() { Mono result = Mono.empty(); BadCredentialsException e = new BadCredentialsException("Failed"); - when(this.authenticationEntryPoint.commence(this.exchange, e)).thenReturn(result); + given(this.authenticationEntryPoint.commence(this.exchange, e)).willReturn(result); assertThat(this.handler.onAuthenticationFailure(this.filterExchange, e)).isEqualTo(result); } diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/ServerFormLoginAuthenticationConverterTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/ServerFormLoginAuthenticationConverterTests.java index 623d772621..0088aa89b8 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/ServerFormLoginAuthenticationConverterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/ServerFormLoginAuthenticationConverterTests.java @@ -29,7 +29,7 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -47,7 +47,7 @@ public class ServerFormLoginAuthenticationConverterTests { @Before public void setup() { - when(this.exchange.getFormData()).thenReturn(Mono.just(this.data)); + given(this.exchange.getFormData()).willReturn(Mono.just(this.data)); } @Test diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/ServerX509AuthenticationConverterTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/ServerX509AuthenticationConverterTests.java index 02dd8c067f..6e5d2e83db 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/ServerX509AuthenticationConverterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/ServerX509AuthenticationConverterTests.java @@ -34,7 +34,7 @@ import org.springframework.security.web.authentication.preauth.x509.X509TestUtil 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; @RunWith(MockitoJUnitRunner.class) public class ServerX509AuthenticationConverterTests { @@ -54,7 +54,7 @@ public class ServerX509AuthenticationConverterTests { this.request = MockServerHttpRequest.get("/"); this.certificate = X509TestUtils.buildTestCertificate(); - when(this.principalExtractor.extractPrincipal(any())).thenReturn("Luke Taylor"); + given(this.principalExtractor.extractPrincipal(any())).willReturn("Luke Taylor"); } @Test diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java index 0787ccf4fa..aad5b64049 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java @@ -57,10 +57,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.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.security.core.context.ReactiveSecurityContextHolder.withSecurityContext; import static org.springframework.security.web.server.authentication.SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR; @@ -100,7 +100,7 @@ public class SwitchUserWebFilterTests { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/not/existing")); WebFilterChain chain = mock(WebFilterChain.class); - when(chain.filter(exchange)).thenReturn(Mono.empty()); + given(chain.filter(exchange)).willReturn(Mono.empty()); // when this.switchUserWebFilter.filter(exchange, chain).block(); @@ -128,11 +128,11 @@ public class SwitchUserWebFilterTests { "credentials"); final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication); - when(this.userDetailsService.findByUsername(targetUsername)).thenReturn(Mono.just(switchUserDetails)); - when(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))) - .thenReturn(Mono.empty()); - when(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))) - .thenReturn(Mono.empty()); + given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails)); + given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))) + .willReturn(Mono.empty()); + given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))) + .willReturn(Mono.empty()); // when this.switchUserWebFilter.filter(exchange, chain) @@ -182,12 +182,12 @@ public class SwitchUserWebFilterTests { final WebFilterChain chain = mock(WebFilterChain.class); - when(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))) - .thenReturn(Mono.empty()); - when(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))) - .thenReturn(Mono.empty()); - when(this.userDetailsService.findByUsername(targetUsername)) - .thenReturn(Mono.just(switchUserDetails(targetUsername, true))); + given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))) + .willReturn(Mono.empty()); + given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))) + .willReturn(Mono.empty()); + given(this.userDetailsService.findByUsername(targetUsername)) + .willReturn(Mono.just(switchUserDetails(targetUsername, true))); // when this.switchUserWebFilter.filter(exchange, chain) @@ -235,9 +235,9 @@ public class SwitchUserWebFilterTests { final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class)); final UserDetails switchUserDetails = switchUserDetails(targetUsername, false); - when(this.userDetailsService.findByUsername(any(String.class))).thenReturn(Mono.just(switchUserDetails)); - when(this.failureHandler.onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class))) - .thenReturn(Mono.empty()); + given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails)); + given(this.failureHandler.onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class))) + .willReturn(Mono.empty()); // when this.switchUserWebFilter.filter(exchange, chain) @@ -260,7 +260,7 @@ public class SwitchUserWebFilterTests { final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class)); final UserDetails switchUserDetails = switchUserDetails(targetUsername, false); - when(this.userDetailsService.findByUsername(any(String.class))).thenReturn(Mono.just(switchUserDetails)); + given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails)); this.exceptionRule.expect(DisabledException.class); @@ -287,10 +287,10 @@ public class SwitchUserWebFilterTests { final WebFilterChain chain = mock(WebFilterChain.class); final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication); - when(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))) - .thenReturn(Mono.empty()); - when(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))) - .thenReturn(Mono.empty()); + given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))) + .willReturn(Mono.empty()); + given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))) + .willReturn(Mono.empty()); // when this.switchUserWebFilter.filter(exchange, chain) diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandlerTests.java index 1d0b697926..e531624c8e 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/logout/DelegatingServerLogoutHandlerTests.java @@ -36,7 +36,7 @@ import org.springframework.security.web.server.WebFilterExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Eric Deandrea @@ -63,10 +63,10 @@ public class DelegatingServerLogoutHandlerTests { @Before public void setup() { - when(this.delegate1.logout(any(WebFilterExchange.class), any(Authentication.class))) - .thenReturn(this.delegate1Result.mono()); - when(this.delegate2.logout(any(WebFilterExchange.class), any(Authentication.class))) - .thenReturn(this.delegate2Result.mono()); + given(this.delegate1.logout(any(WebFilterExchange.class), any(Authentication.class))) + .willReturn(this.delegate1Result.mono()); + given(this.delegate2.logout(any(WebFilterExchange.class), any(Authentication.class))) + .willReturn(this.delegate2Result.mono()); } @Test diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/logout/HeaderWriterServerLogoutHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/logout/HeaderWriterServerLogoutHandlerTests.java index 0989750a2f..083bc7f105 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/logout/HeaderWriterServerLogoutHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/logout/HeaderWriterServerLogoutHandlerTests.java @@ -23,9 +23,9 @@ import org.springframework.security.web.server.header.ServerHttpHeadersWriter; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author MD Sayem Ahmed @@ -45,7 +45,7 @@ public class HeaderWriterServerLogoutHandlerTests { HeaderWriterServerLogoutHandler handler = new HeaderWriterServerLogoutHandler(headersWriter); ServerWebExchange serverWebExchange = mock(ServerWebExchange.class); WebFilterExchange filterExchange = mock(WebFilterExchange.class); - when(filterExchange.getExchange()).thenReturn(serverWebExchange); + given(filterExchange.getExchange()).willReturn(serverWebExchange); Authentication authentication = mock(Authentication.class); handler.logout(filterExchange, authentication); diff --git a/web/src/test/java/org/springframework/security/web/server/authorization/AuthorizationWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/authorization/AuthorizationWebFilterTests.java index 1b4771e78f..a35a1d5215 100644 --- a/web/src/test/java/org/springframework/security/web/server/authorization/AuthorizationWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authorization/AuthorizationWebFilterTests.java @@ -33,7 +33,7 @@ import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -52,7 +52,7 @@ public class AuthorizationWebFilterTests { @Test public void filterWhenNoSecurityContextThenThrowsAccessDenied() { - when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono()); + given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter( (a, e) -> Mono.error(new AccessDeniedException("Denied"))); @@ -64,7 +64,7 @@ public class AuthorizationWebFilterTests { @Test public void filterWhenNoAuthenticationThenThrowsAccessDenied() { - when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono()); + given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter( (a, e) -> a.flatMap(auth -> Mono.error(new AccessDeniedException("Denied")))); @@ -77,7 +77,7 @@ public class AuthorizationWebFilterTests { @Test public void filterWhenAuthenticationThenThrowsAccessDenied() { - when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono()); + given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter( (a, e) -> Mono.error(new AccessDeniedException("Denied"))); @@ -91,7 +91,7 @@ public class AuthorizationWebFilterTests { @Test public void filterWhenDoesNotAccessAuthenticationThenSecurityContextNotSubscribed() { PublisherProbe context = PublisherProbe.empty(); - when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono()); + given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter( (a, e) -> Mono.error(new AccessDeniedException("Denied"))); @@ -106,7 +106,7 @@ public class AuthorizationWebFilterTests { @Test public void filterWhenGrantedAndDoesNotAccessAuthenticationThenChainSubscribedAndSecurityContextNotSubscribed() { PublisherProbe context = PublisherProbe.empty(); - when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono()); + given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter( (a, e) -> Mono.just(new AuthorizationDecision(true))); @@ -121,7 +121,7 @@ public class AuthorizationWebFilterTests { @Test public void filterWhenGrantedAndDoeAccessAuthenticationThenChainSubscribedAndSecurityContextSubscribed() { PublisherProbe context = PublisherProbe.empty(); - when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono()); + given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono()); AuthorizationWebFilter filter = new AuthorizationWebFilter((a, e) -> a .map(auth -> new AuthorizationDecision(true)).defaultIfEmpty(new AuthorizationDecision(true))); diff --git a/web/src/test/java/org/springframework/security/web/server/authorization/DelegatingReactiveAuthorizationManagerTests.java b/web/src/test/java/org/springframework/security/web/server/authorization/DelegatingReactiveAuthorizationManagerTests.java index fd51b46a10..ec9056cd2f 100644 --- a/web/src/test/java/org/springframework/security/web/server/authorization/DelegatingReactiveAuthorizationManagerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authorization/DelegatingReactiveAuthorizationManagerTests.java @@ -33,8 +33,8 @@ import org.springframework.web.server.ServerWebExchange; 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.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -75,9 +75,9 @@ public class DelegatingReactiveAuthorizationManagerTests { @Test public void checkWhenFirstMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() { - when(this.match1.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match()); - when(this.delegate1.check(eq(this.authentication), any(AuthorizationContext.class))) - .thenReturn(Mono.just(this.decision)); + given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match()); + given(this.delegate1.check(eq(this.authentication), any(AuthorizationContext.class))) + .willReturn(Mono.just(this.decision)); assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision); @@ -86,10 +86,10 @@ public class DelegatingReactiveAuthorizationManagerTests { @Test public void checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() { - when(this.match1.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); - when(this.match2.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match()); - when(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class))) - .thenReturn(Mono.just(this.decision)); + given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(this.match2.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match()); + given(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class))) + .willReturn(Mono.just(this.decision)); assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision); diff --git a/web/src/test/java/org/springframework/security/web/server/authorization/ExceptionTranslationWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/authorization/ExceptionTranslationWebFilterTests.java index 8995ae1a4e..79ae02cbc2 100644 --- a/web/src/test/java/org/springframework/security/web/server/authorization/ExceptionTranslationWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authorization/ExceptionTranslationWebFilterTests.java @@ -36,7 +36,7 @@ import org.springframework.web.server.WebFilterChain; 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 @@ -68,9 +68,9 @@ public class ExceptionTranslationWebFilterTests { @Before public void setup() { - when(this.exchange.getResponse()).thenReturn(new MockServerHttpResponse()); - when(this.deniedHandler.handle(any(), any())).thenReturn(this.deniedPublisher.mono()); - when(this.entryPoint.commence(any(), any())).thenReturn(this.entryPointPublisher.mono()); + given(this.exchange.getResponse()).willReturn(new MockServerHttpResponse()); + given(this.deniedHandler.handle(any(), any())).willReturn(this.deniedPublisher.mono()); + given(this.entryPoint.commence(any(), any())).willReturn(this.entryPointPublisher.mono()); this.filter.setAuthenticationEntryPoint(this.entryPoint); this.filter.setAccessDeniedHandler(this.deniedHandler); @@ -78,7 +78,7 @@ public class ExceptionTranslationWebFilterTests { @Test public void filterWhenNoExceptionThenNotHandled() { - when(this.chain.filter(this.exchange)).thenReturn(Mono.empty()); + given(this.chain.filter(this.exchange)).willReturn(Mono.empty()); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify(); @@ -88,7 +88,7 @@ public class ExceptionTranslationWebFilterTests { @Test public void filterWhenNotAccessDeniedExceptionThenNotHandled() { - when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new IllegalArgumentException("oops"))); + given(this.chain.filter(this.exchange)).willReturn(Mono.error(new IllegalArgumentException("oops"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectError(IllegalArgumentException.class) .verify(); @@ -99,8 +99,8 @@ public class ExceptionTranslationWebFilterTests { @Test public void filterWhenAccessDeniedExceptionAndNotAuthenticatedThenHandled() { - when(this.exchange.getPrincipal()).thenReturn(Mono.empty()); - when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized"))); + given(this.exchange.getPrincipal()).willReturn(Mono.empty()); + given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).verifyComplete(); @@ -111,8 +111,8 @@ public class ExceptionTranslationWebFilterTests { @Test public void filterWhenDefaultsAndAccessDeniedExceptionAndAuthenticatedThenForbidden() { this.filter = new ExceptionTranslationWebFilter(); - when(this.exchange.getPrincipal()).thenReturn(Mono.just(this.principal)); - when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized"))); + given(this.exchange.getPrincipal()).willReturn(Mono.just(this.principal)); + given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify(); @@ -122,8 +122,8 @@ public class ExceptionTranslationWebFilterTests { @Test public void filterWhenDefaultsAndAccessDeniedExceptionAndNotAuthenticatedThenUnauthorized() { this.filter = new ExceptionTranslationWebFilter(); - when(this.exchange.getPrincipal()).thenReturn(Mono.empty()); - when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized"))); + given(this.exchange.getPrincipal()).willReturn(Mono.empty()); + given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify(); @@ -132,8 +132,8 @@ public class ExceptionTranslationWebFilterTests { @Test public void filterWhenAccessDeniedExceptionAndAuthenticatedThenHandled() { - when(this.exchange.getPrincipal()).thenReturn(Mono.just(this.principal)); - when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized"))); + given(this.exchange.getPrincipal()).willReturn(Mono.just(this.principal)); + given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized"))); StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify(); diff --git a/web/src/test/java/org/springframework/security/web/server/authorization/ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authorization/ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java index 4d5ae38707..da71f648a6 100644 --- a/web/src/test/java/org/springframework/security/web/server/authorization/ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authorization/ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java @@ -27,10 +27,10 @@ import org.springframework.security.web.server.authorization.ServerWebExchangeDe import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; import org.springframework.web.server.ServerWebExchange; +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.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.match; import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.notMatch; @@ -55,9 +55,9 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests { public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() { ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class); - when(matcher.matches(this.exchange)).thenReturn(notMatch()); - when(handler.handle(this.exchange, null)).thenReturn(Mono.empty()); - when(this.accessDeniedHandler.handle(this.exchange, null)).thenReturn(Mono.empty()); + given(matcher.matches(this.exchange)).willReturn(notMatch()); + given(handler.handle(this.exchange, null)).willReturn(Mono.empty()); + given(this.accessDeniedHandler.handle(this.exchange, null)).willReturn(Mono.empty()); this.entries.add(new DelegateEntry(matcher, handler)); this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries); @@ -75,9 +75,9 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests { ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class); ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class); - when(firstMatcher.matches(this.exchange)).thenReturn(match()); - when(firstHandler.handle(this.exchange, null)).thenReturn(Mono.empty()); - when(secondHandler.handle(this.exchange, null)).thenReturn(Mono.empty()); + given(firstMatcher.matches(this.exchange)).willReturn(match()); + given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty()); + given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty()); this.entries.add(new DelegateEntry(firstMatcher, firstHandler)); this.entries.add(new DelegateEntry(secondMatcher, secondHandler)); @@ -98,10 +98,10 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests { ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class); ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class); - when(firstMatcher.matches(this.exchange)).thenReturn(notMatch()); - when(secondMatcher.matches(this.exchange)).thenReturn(match()); - when(firstHandler.handle(this.exchange, null)).thenReturn(Mono.empty()); - when(secondHandler.handle(this.exchange, null)).thenReturn(Mono.empty()); + given(firstMatcher.matches(this.exchange)).willReturn(notMatch()); + given(secondMatcher.matches(this.exchange)).willReturn(match()); + given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty()); + given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty()); this.entries.add(new DelegateEntry(firstMatcher, firstHandler)); this.entries.add(new DelegateEntry(secondMatcher, secondHandler)); diff --git a/web/src/test/java/org/springframework/security/web/server/context/ReactorContextWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/context/ReactorContextWebFilterTests.java index 29b19d2654..0f3024dd7f 100644 --- a/web/src/test/java/org/springframework/security/web/server/context/ReactorContextWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/context/ReactorContextWebFilterTests.java @@ -39,7 +39,7 @@ import org.springframework.web.server.handler.DefaultWebFilterChain; 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 @@ -66,7 +66,7 @@ public class ReactorContextWebFilterTests { public void setup() { this.filter = new ReactorContextWebFilter(this.repository); this.handler = WebTestHandler.bindToWebFilters(this.filter); - when(this.repository.load(any())).thenReturn(this.securityContext.mono()); + given(this.repository.load(any())).willReturn(this.securityContext.mono()); } @Test(expected = IllegalArgumentException.class) @@ -97,7 +97,7 @@ public class ReactorContextWebFilterTests { @Test public void filterWhenPrincipalAndGetPrincipalThenInteractAndUseOriginalPrincipal() { SecurityContextImpl context = new SecurityContextImpl(this.principal); - when(this.repository.load(any())).thenReturn(Mono.just(context)); + given(this.repository.load(any())).willReturn(Mono.just(context)); this.handler = WebTestHandler.bindToWebFilters(this.filter, (e, c) -> ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication) .doOnSuccess(p -> assertThat(p).isSameAs(this.principal)).flatMap(p -> c.filter(e))); diff --git a/web/src/test/java/org/springframework/security/web/server/csrf/CsrfServerLogoutHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/csrf/CsrfServerLogoutHandlerTests.java index 0c7a38378e..f48c29295e 100644 --- a/web/src/test/java/org/springframework/security/web/server/csrf/CsrfServerLogoutHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/csrf/CsrfServerLogoutHandlerTests.java @@ -29,8 +29,8 @@ import org.springframework.security.web.server.WebFilterExchange; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Eric Deandrea @@ -56,7 +56,7 @@ public class CsrfServerLogoutHandlerTests { this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); this.filterExchange = new WebFilterExchange(this.exchange, this.filterChain); this.handler = new CsrfServerLogoutHandler(this.csrfTokenRepository); - when(this.csrfTokenRepository.saveToken(this.exchange, null)).thenReturn(Mono.empty()); + given(this.csrfTokenRepository.saveToken(this.exchange, null)).willReturn(Mono.empty()); } @Test diff --git a/web/src/test/java/org/springframework/security/web/server/csrf/CsrfWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/csrf/CsrfWebFilterTests.java index 4f440ff8bc..d301f227e2 100644 --- a/web/src/test/java/org/springframework/security/web/server/csrf/CsrfWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/csrf/CsrfWebFilterTests.java @@ -40,9 +40,9 @@ import org.springframework.web.server.WebSession; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; import static org.springframework.mock.web.server.MockServerWebExchange.from; import static org.springframework.web.reactive.function.BodyInserters.fromMultipartData; @@ -71,7 +71,7 @@ public class CsrfWebFilterTests { @Test public void filterWhenGetThenSessionNotCreatedAndChainContinues() { PublisherProbe chainResult = PublisherProbe.empty(); - when(this.chain.filter(this.get)).thenReturn(chainResult.mono()); + given(this.chain.filter(this.get)).willReturn(chainResult.mono()); Mono result = this.csrfFilter.filter(this.get, this.chain); @@ -95,7 +95,7 @@ public class CsrfWebFilterTests { @Test public void filterWhenPostAndEstablishedCsrfTokenAndRequestMissingTokenThenCsrfException() { this.csrfFilter.setCsrfTokenRepository(this.repository); - when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token)); + given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); Mono result = this.csrfFilter.filter(this.post, this.chain); @@ -107,7 +107,7 @@ public class CsrfWebFilterTests { @Test public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamInvalidTokenThenCsrfException() { this.csrfFilter.setCsrfTokenRepository(this.repository); - when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token)); + given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); this.post = from(MockServerHttpRequest.post("/") .body(this.token.getParameterName() + "=" + this.token.getToken() + "INVALID")); @@ -121,11 +121,11 @@ public class CsrfWebFilterTests { @Test public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamValidTokenThenContinues() { PublisherProbe chainResult = PublisherProbe.empty(); - when(this.chain.filter(any())).thenReturn(chainResult.mono()); + given(this.chain.filter(any())).willReturn(chainResult.mono()); this.csrfFilter.setCsrfTokenRepository(this.repository); - when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token)); - when(this.repository.generateToken(any())).thenReturn(Mono.just(this.token)); + given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); + given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); this.post = from(MockServerHttpRequest.post("/").contentType(MediaType.APPLICATION_FORM_URLENCODED) .body(this.token.getParameterName() + "=" + this.token.getToken())); @@ -139,7 +139,7 @@ public class CsrfWebFilterTests { @Test public void filterWhenPostAndEstablishedCsrfTokenAndHeaderInvalidTokenThenCsrfException() { this.csrfFilter.setCsrfTokenRepository(this.repository); - when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token)); + given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); this.post = from( MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken() + "INVALID")); @@ -153,11 +153,11 @@ public class CsrfWebFilterTests { @Test public void filterWhenPostAndEstablishedCsrfTokenAndHeaderValidTokenThenContinues() { PublisherProbe chainResult = PublisherProbe.empty(); - when(this.chain.filter(any())).thenReturn(chainResult.mono()); + given(this.chain.filter(any())).willReturn(chainResult.mono()); this.csrfFilter.setCsrfTokenRepository(this.repository); - when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token)); - when(this.repository.generateToken(any())).thenReturn(Mono.just(this.token)); + given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); + given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); this.post = from(MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken())); Mono result = this.csrfFilter.filter(this.post, this.chain); @@ -181,7 +181,7 @@ public class CsrfWebFilterTests { @Test public void doFilterWhenSkipExchangeInvokedThenSkips() { PublisherProbe chainResult = PublisherProbe.empty(); - when(this.chain.filter(any())).thenReturn(chainResult.mono()); + given(this.chain.filter(any())).willReturn(chainResult.mono()); ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class); this.csrfFilter.setRequireCsrfProtectionMatcher(matcher); @@ -196,7 +196,7 @@ public class CsrfWebFilterTests { @Test public void filterWhenMultipartFormDataAndNotEnabledThenDenied() { this.csrfFilter.setCsrfTokenRepository(this.repository); - when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token)); + given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); @@ -209,8 +209,8 @@ public class CsrfWebFilterTests { public void filterWhenMultipartFormDataAndEnabledThenGranted() { this.csrfFilter.setCsrfTokenRepository(this.repository); this.csrfFilter.setTokenFromMultipartDataEnabled(true); - when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token)); - when(this.repository.generateToken(any())).thenReturn(Mono.just(this.token)); + given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); + given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); @@ -223,8 +223,8 @@ public class CsrfWebFilterTests { public void filterWhenFormDataAndEnabledThenGranted() { this.csrfFilter.setCsrfTokenRepository(this.repository); this.csrfFilter.setTokenFromMultipartDataEnabled(true); - when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token)); - when(this.repository.generateToken(any())).thenReturn(Mono.just(this.token)); + given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); + given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); @@ -237,7 +237,7 @@ public class CsrfWebFilterTests { public void filterWhenMultipartMixedAndEnabledThenNotRead() { this.csrfFilter.setCsrfTokenRepository(this.repository); this.csrfFilter.setTokenFromMultipartDataEnabled(true); - when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token)); + given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); diff --git a/web/src/test/java/org/springframework/security/web/server/header/CompositeServerHttpHeadersWriterTests.java b/web/src/test/java/org/springframework/security/web/server/header/CompositeServerHttpHeadersWriterTests.java index 2c442bde7a..b49441fa89 100644 --- a/web/src/test/java/org/springframework/security/web/server/header/CompositeServerHttpHeadersWriterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/header/CompositeServerHttpHeadersWriterTests.java @@ -34,8 +34,8 @@ import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; 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 @@ -61,7 +61,7 @@ public class CompositeServerHttpHeadersWriterTests { @Test public void writeHttpHeadersWhenErrorNoErrorThenError() { - when(this.writer1.writeHttpHeaders(this.exchange)).thenReturn(Mono.error(new RuntimeException())); + given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException())); Mono result = this.writer.writeHttpHeaders(this.exchange); @@ -72,7 +72,7 @@ public class CompositeServerHttpHeadersWriterTests { @Test public void writeHttpHeadersWhenErrorErrorThenError() { - when(this.writer1.writeHttpHeaders(this.exchange)).thenReturn(Mono.error(new RuntimeException())); + given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException())); Mono result = this.writer.writeHttpHeaders(this.exchange); @@ -83,8 +83,8 @@ public class CompositeServerHttpHeadersWriterTests { @Test public void writeHttpHeadersWhenNoErrorThenNoError() { - when(this.writer1.writeHttpHeaders(this.exchange)).thenReturn(Mono.empty()); - when(this.writer2.writeHttpHeaders(this.exchange)).thenReturn(Mono.empty()); + given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.empty()); + given(this.writer2.writeHttpHeaders(this.exchange)).willReturn(Mono.empty()); Mono result = this.writer.writeHttpHeaders(this.exchange); diff --git a/web/src/test/java/org/springframework/security/web/server/header/HttpHeaderWriterWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/header/HttpHeaderWriterWebFilterTests.java index 576dc5c349..293e85b8a5 100644 --- a/web/src/test/java/org/springframework/security/web/server/header/HttpHeaderWriterWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/header/HttpHeaderWriterWebFilterTests.java @@ -29,9 +29,9 @@ import org.springframework.security.test.web.reactive.server.WebTestHandler.WebH import org.springframework.test.web.reactive.server.WebTestClient; 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; /** * @author Rob Winch @@ -47,7 +47,7 @@ public class HttpHeaderWriterWebFilterTests { @Before public void setup() { - when(this.writer.writeHttpHeaders(any())).thenReturn(Mono.empty()); + given(this.writer.writeHttpHeaders(any())).willReturn(Mono.empty()); this.filter = new HttpHeaderWriterWebFilter(this.writer); } diff --git a/web/src/test/java/org/springframework/security/web/server/savedrequest/ServerRequestCacheWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/savedrequest/ServerRequestCacheWebFilterTests.java index 5ce76f1faa..5652b680f0 100644 --- a/web/src/test/java/org/springframework/security/web/server/savedrequest/ServerRequestCacheWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/savedrequest/ServerRequestCacheWebFilterTests.java @@ -35,8 +35,8 @@ import org.springframework.web.server.WebFilterChain; 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; /** * Tests for {@link ServerRequestCacheWebFilter} @@ -61,7 +61,7 @@ public class ServerRequestCacheWebFilterTests { public void setup() { this.requestCacheFilter = new ServerRequestCacheWebFilter(); this.requestCacheFilter.setRequestCache(this.requestCache); - when(this.chain.filter(any(ServerWebExchange.class))).thenReturn(Mono.empty()); + given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty()); } @Test @@ -69,7 +69,7 @@ public class ServerRequestCacheWebFilterTests { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/")); ServerHttpRequest savedRequest = MockServerHttpRequest.get("/") .header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML.getType()).build(); - when(this.requestCache.removeMatchingRequest(any())).thenReturn(Mono.just(savedRequest)); + given(this.requestCache.removeMatchingRequest(any())).willReturn(Mono.just(savedRequest)); this.requestCacheFilter.filter(exchange, this.chain).block(); @@ -82,7 +82,7 @@ public class ServerRequestCacheWebFilterTests { public void filterWhenRequestDoesNotMatchThenRequestDoesNotChange() { MockServerHttpRequest initialRequest = MockServerHttpRequest.get("/").build(); ServerWebExchange exchange = MockServerWebExchange.from(initialRequest); - when(this.requestCache.removeMatchingRequest(any())).thenReturn(Mono.empty()); + given(this.requestCache.removeMatchingRequest(any())).willReturn(Mono.empty()); this.requestCacheFilter.filter(exchange, this.chain).block(); diff --git a/web/src/test/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilterTests.java index 0601e3c8d7..dfff77d0a2 100644 --- a/web/src/test/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilterTests.java @@ -34,9 +34,9 @@ import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.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; /** * Tests for {@link HttpsRedirectWebFilter} @@ -54,7 +54,7 @@ public class HttpsRedirectWebFilterTests { @Before public void configureFilter() { this.filter = new HttpsRedirectWebFilter(); - when(this.chain.filter(any(ServerWebExchange.class))).thenReturn(Mono.empty()); + given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty()); } @Test @@ -75,7 +75,8 @@ public class HttpsRedirectWebFilterTests { @Test public void filterWhenExchangeMismatchesThenNoRedirect() { ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class); - when(matcher.matches(any(ServerWebExchange.class))).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(matcher.matches(any(ServerWebExchange.class))) + .willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); this.filter.setRequiresHttpsRedirectMatcher(matcher); ServerWebExchange exchange = get("http://localhost:8080"); @@ -86,7 +87,7 @@ public class HttpsRedirectWebFilterTests { @Test public void filterWhenExchangeMatchesAndRequestIsInsecureThenRedirects() { ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class); - when(matcher.matches(any(ServerWebExchange.class))).thenReturn(ServerWebExchangeMatcher.MatchResult.match()); + given(matcher.matches(any(ServerWebExchange.class))).willReturn(ServerWebExchangeMatcher.MatchResult.match()); this.filter.setRequiresHttpsRedirectMatcher(matcher); ServerWebExchange exchange = get("http://localhost:8080"); @@ -100,7 +101,7 @@ public class HttpsRedirectWebFilterTests { @Test public void filterWhenRequestIsInsecureThenPortMapperRemapsPort() { PortMapper portMapper = mock(PortMapper.class); - when(portMapper.lookupHttpsPort(314)).thenReturn(159); + given(portMapper.lookupHttpsPort(314)).willReturn(159); this.filter.setPortMapper(portMapper); ServerWebExchange exchange = get("http://localhost:314"); diff --git a/web/src/test/java/org/springframework/security/web/server/util/matcher/AndServerWebExchangeMatcherTests.java b/web/src/test/java/org/springframework/security/web/server/util/matcher/AndServerWebExchangeMatcherTests.java index 9c32a9f027..4c94122877 100644 --- a/web/src/test/java/org/springframework/security/web/server/util/matcher/AndServerWebExchangeMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/server/util/matcher/AndServerWebExchangeMatcherTests.java @@ -28,9 +28,9 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -59,8 +59,8 @@ public class AndServerWebExchangeMatcherTests { public void matchesWhenTrueTrueThenTrue() { Map params1 = Collections.singletonMap("foo", "bar"); Map params2 = Collections.singletonMap("x", "y"); - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params1)); - when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params2)); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params1)); + given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params2)); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); @@ -75,7 +75,7 @@ public class AndServerWebExchangeMatcherTests { @Test public void matchesWhenFalseFalseThenFalseAndMatcher2NotInvoked() { - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); @@ -89,8 +89,8 @@ public class AndServerWebExchangeMatcherTests { @Test public void matchesWhenTrueFalseThenFalse() { Map params = Collections.singletonMap("foo", "bar"); - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params)); - when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params)); + given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); @@ -103,7 +103,7 @@ public class AndServerWebExchangeMatcherTests { @Test public void matchesWhenFalseTrueThenFalse() { - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); diff --git a/web/src/test/java/org/springframework/security/web/server/util/matcher/NegatedServerWebExchangeMatcherTests.java b/web/src/test/java/org/springframework/security/web/server/util/matcher/NegatedServerWebExchangeMatcherTests.java index ae7d339dc3..56684e0e01 100644 --- a/web/src/test/java/org/springframework/security/web/server/util/matcher/NegatedServerWebExchangeMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/server/util/matcher/NegatedServerWebExchangeMatcherTests.java @@ -25,8 +25,8 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.web.server.ServerWebExchange; 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 Tao Qian @@ -50,7 +50,7 @@ public class NegatedServerWebExchangeMatcherTests { @Test public void matchesWhenFalseThenTrue() { - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); @@ -62,7 +62,7 @@ public class NegatedServerWebExchangeMatcherTests { @Test public void matchesWhenTrueThenFalse() { - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match()); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); diff --git a/web/src/test/java/org/springframework/security/web/server/util/matcher/OrServerWebExchangeMatcherTests.java b/web/src/test/java/org/springframework/security/web/server/util/matcher/OrServerWebExchangeMatcherTests.java index c46c4f0951..2bdc51806a 100644 --- a/web/src/test/java/org/springframework/security/web/server/util/matcher/OrServerWebExchangeMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/server/util/matcher/OrServerWebExchangeMatcherTests.java @@ -28,9 +28,9 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -57,8 +57,8 @@ public class OrServerWebExchangeMatcherTests { @Test public void matchesWhenFalseFalseThenFalse() { - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); - when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); @@ -72,7 +72,7 @@ public class OrServerWebExchangeMatcherTests { @Test public void matchesWhenTrueFalseThenTrueAndMatcher2NotInvoked() { Map params = Collections.singletonMap("foo", "bar"); - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params)); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params)); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); @@ -86,8 +86,8 @@ public class OrServerWebExchangeMatcherTests { @Test public void matchesWhenFalseTrueThenTrue() { Map params = Collections.singletonMap("foo", "bar"); - when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); - when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params)); + given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch()); + given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params)); ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block(); diff --git a/web/src/test/java/org/springframework/security/web/server/util/matcher/PathMatcherServerWebExchangeMatcherTests.java b/web/src/test/java/org/springframework/security/web/server/util/matcher/PathMatcherServerWebExchangeMatcherTests.java index 870347f26c..0f12d95dd0 100644 --- a/web/src/test/java/org/springframework/security/web/server/util/matcher/PathMatcherServerWebExchangeMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/server/util/matcher/PathMatcherServerWebExchangeMatcherTests.java @@ -32,8 +32,8 @@ import org.springframework.web.util.pattern.PathPattern; 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.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -77,16 +77,16 @@ public class PathMatcherServerWebExchangeMatcherTests { @Test public void matchesWhenPathMatcherTrueThenReturnTrue() { - when(this.pattern.matches(any())).thenReturn(true); - when(this.pattern.matchAndExtract(any())).thenReturn(this.pathMatchInfo); - when(this.pathMatchInfo.getUriVariables()).thenReturn(new HashMap<>()); + given(this.pattern.matches(any())).willReturn(true); + given(this.pattern.matchAndExtract(any())).willReturn(this.pathMatchInfo); + given(this.pathMatchInfo.getUriVariables()).willReturn(new HashMap<>()); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue(); } @Test public void matchesWhenPathMatcherFalseThenReturnFalse() { - when(this.pattern.matches(any())).thenReturn(false); + given(this.pattern.matches(any())).willReturn(false); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse(); } @@ -95,9 +95,9 @@ public class PathMatcherServerWebExchangeMatcherTests { public void matchesWhenPathMatcherTrueAndMethodTrueThenReturnTrue() { this.matcher = new PathPatternParserServerWebExchangeMatcher(this.pattern, this.exchange.getRequest().getMethod()); - when(this.pattern.matches(any())).thenReturn(true); - when(this.pattern.matchAndExtract(any())).thenReturn(this.pathMatchInfo); - when(this.pathMatchInfo.getUriVariables()).thenReturn(new HashMap<>()); + given(this.pattern.matches(any())).willReturn(true); + given(this.pattern.matchAndExtract(any())).willReturn(this.pathMatchInfo); + given(this.pathMatchInfo.getUriVariables()).willReturn(new HashMap<>()); assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue(); } diff --git a/web/src/test/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcherTests.java index 09d9eec0ca..867d3ff476 100644 --- a/web/src/test/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/servlet/util/matcher/MvcRequestMatcherTests.java @@ -35,8 +35,8 @@ import org.springframework.web.servlet.handler.RequestMatchResult; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * @author Rob Winch @@ -72,7 +72,7 @@ public class MvcRequestMatcherTests { @Test public void extractUriTemplateVariablesSuccess() throws Exception { this.matcher = new MvcRequestMatcher(this.introspector, "/{p}"); - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(null); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null); assertThat(this.matcher.extractUriTemplateVariables(this.request)).containsEntry("p", "path"); assertThat(this.matcher.matcher(this.request).getVariables()).containsEntry("p", "path"); @@ -80,9 +80,9 @@ public class MvcRequestMatcherTests { @Test public void extractUriTemplateVariablesFail() throws Exception { - when(this.result.extractUriTemplateVariables()).thenReturn(Collections.emptyMap()); - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping); - when(this.mapping.match(eq(this.request), this.pattern.capture())).thenReturn(this.result); + given(this.result.extractUriTemplateVariables()).willReturn(Collections.emptyMap()); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); + given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result); assertThat(this.matcher.extractUriTemplateVariables(this.request)).isEmpty(); assertThat(this.matcher.matcher(this.request).getVariables()).isEmpty(); @@ -91,7 +91,7 @@ public class MvcRequestMatcherTests { @Test public void extractUriTemplateVariablesDefaultSuccess() throws Exception { this.matcher = new MvcRequestMatcher(this.introspector, "/{p}"); - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(null); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null); assertThat(this.matcher.extractUriTemplateVariables(this.request)).containsEntry("p", "path"); assertThat(this.matcher.matcher(this.request).getVariables()).containsEntry("p", "path"); @@ -100,7 +100,7 @@ public class MvcRequestMatcherTests { @Test public void extractUriTemplateVariablesDefaultFail() throws Exception { this.matcher = new MvcRequestMatcher(this.introspector, "/nomatch/{p}"); - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(null); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null); assertThat(this.matcher.extractUriTemplateVariables(this.request)).isEmpty(); assertThat(this.matcher.matcher(this.request).getVariables()).isEmpty(); @@ -108,8 +108,8 @@ public class MvcRequestMatcherTests { @Test public void matchesServletPathTrue() throws Exception { - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping); - when(this.mapping.match(eq(this.request), this.pattern.capture())).thenReturn(this.result); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); + given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result); this.matcher.setServletPath("/spring"); this.request.setServletPath("/spring"); @@ -127,8 +127,8 @@ public class MvcRequestMatcherTests { @Test public void matchesPathOnlyTrue() throws Exception { - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping); - when(this.mapping.match(eq(this.request), this.pattern.capture())).thenReturn(this.result); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); + given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result); assertThat(this.matcher.matches(this.request)).isTrue(); assertThat(this.pattern.getValue()).isEqualTo("/path"); @@ -136,7 +136,7 @@ public class MvcRequestMatcherTests { @Test public void matchesDefaultMatches() throws Exception { - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(null); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null); assertThat(this.matcher.matches(this.request)).isTrue(); } @@ -144,14 +144,14 @@ public class MvcRequestMatcherTests { @Test public void matchesDefaultDoesNotMatch() throws Exception { this.request.setServletPath("/other"); - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(null); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null); assertThat(this.matcher.matches(this.request)).isFalse(); } @Test public void matchesPathOnlyFalse() throws Exception { - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); assertThat(this.matcher.matches(this.request)).isFalse(); } @@ -159,8 +159,8 @@ public class MvcRequestMatcherTests { @Test public void matchesMethodAndPathTrue() throws Exception { this.matcher.setMethod(HttpMethod.GET); - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping); - when(this.mapping.match(eq(this.request), this.pattern.capture())).thenReturn(this.result); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); + given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result); assertThat(this.matcher.matches(this.request)).isTrue(); assertThat(this.pattern.getValue()).isEqualTo("/path"); @@ -193,7 +193,7 @@ public class MvcRequestMatcherTests { @Test public void matchesMethodAndPathFalsePath() throws Exception { this.matcher.setMethod(HttpMethod.GET); - when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping); + given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping); assertThat(this.matcher.matches(this.request)).isFalse(); } @@ -205,8 +205,8 @@ public class MvcRequestMatcherTests { @Test public void matchesGetMatchableHandlerMappingThrows() throws Exception { - when(this.introspector.getMatchableHandlerMapping(this.request)) - .thenThrow(new HttpRequestMethodNotSupportedException(this.request.getMethod())); + given(this.introspector.getMatchableHandlerMapping(this.request)) + .willThrow(new HttpRequestMethodNotSupportedException(this.request.getMethod())); assertThat(this.matcher.matches(this.request)).isTrue(); } diff --git a/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java b/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java index aaca1c9f64..f973fe6331 100644 --- a/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/session/SessionManagementFilterTests.java @@ -36,12 +36,12 @@ import org.springframework.security.web.context.SecurityContextRepository; 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.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; /** * @author Luke Taylor @@ -71,7 +71,7 @@ public class SessionManagementFilterTests { SecurityContextRepository repo = mock(SecurityContextRepository.class); SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class); // mock that repo contains a security context - when(repo.containsContext(any(HttpServletRequest.class))).thenReturn(true); + given(repo.containsContext(any(HttpServletRequest.class))).willReturn(true); SessionManagementFilter filter = new SessionManagementFilter(repo, strategy); HttpServletRequest request = new MockHttpServletRequest(); authenticateUser(); @@ -125,7 +125,7 @@ public class SessionManagementFilterTests { FilterChain fc = mock(FilterChain.class); authenticateUser(); SessionAuthenticationException exception = new SessionAuthenticationException("Failure"); - doThrow(exception).when(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(), + willThrow(exception).given(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(), request, response); filter.doFilter(request, response, fc); diff --git a/web/src/test/java/org/springframework/security/web/util/OnCommittedResponseWrapperTests.java b/web/src/test/java/org/springframework/security/web/util/OnCommittedResponseWrapperTests.java index 52bbca8413..d22541e9da 100644 --- a/web/src/test/java/org/springframework/security/web/util/OnCommittedResponseWrapperTests.java +++ b/web/src/test/java/org/springframework/security/web/util/OnCommittedResponseWrapperTests.java @@ -29,8 +29,8 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; 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; @RunWith(MockitoJUnitRunner.class) public class OnCommittedResponseWrapperTests { @@ -58,8 +58,8 @@ public class OnCommittedResponseWrapperTests { OnCommittedResponseWrapperTests.this.committed = true; } }; - when(this.delegate.getWriter()).thenReturn(this.writer); - when(this.delegate.getOutputStream()).thenReturn(this.out); + given(this.delegate.getWriter()).willReturn(this.writer); + given(this.delegate.getOutputStream()).willReturn(this.out); } // --- printwriter @@ -74,7 +74,7 @@ public class OnCommittedResponseWrapperTests { @Test public void printWriterCheckError() throws Exception { boolean expected = true; - when(this.writer.checkError()).thenReturn(expected); + given(this.writer.checkError()).willReturn(expected); assertThat(this.response.getWriter().checkError()).isEqualTo(expected); } @@ -1118,7 +1118,7 @@ public class OnCommittedResponseWrapperTests { @Test public void bufferSizePrintWriterWriteCommits() throws Exception { String expected = "1234567890"; - when(this.response.getBufferSize()).thenReturn(expected.length()); + given(this.response.getBufferSize()).willReturn(expected.length()); this.response.getWriter().write(expected); @@ -1128,7 +1128,7 @@ public class OnCommittedResponseWrapperTests { @Test public void bufferSizeCommitsOnce() throws Exception { String expected = "1234567890"; - when(this.response.getBufferSize()).thenReturn(expected.length()); + given(this.response.getBufferSize()).willReturn(expected.length()); this.response.getWriter().write(expected); diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/AndRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/AndRequestMatcherTests.java index bfb6196e15..cd83fe120d 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/AndRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/AndRequestMatcherTests.java @@ -27,7 +27,7 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -79,7 +79,7 @@ public class AndRequestMatcherTests { @Test public void matchesSingleTrue() { - when(this.delegate.matches(this.request)).thenReturn(true); + given(this.delegate.matches(this.request)).willReturn(true); this.matcher = new AndRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isTrue(); @@ -87,8 +87,8 @@ public class AndRequestMatcherTests { @Test public void matchesMultiTrue() { - when(this.delegate.matches(this.request)).thenReturn(true); - when(this.delegate2.matches(this.request)).thenReturn(true); + given(this.delegate.matches(this.request)).willReturn(true); + given(this.delegate2.matches(this.request)).willReturn(true); this.matcher = new AndRequestMatcher(this.delegate, this.delegate2); assertThat(this.matcher.matches(this.request)).isTrue(); @@ -96,7 +96,7 @@ public class AndRequestMatcherTests { @Test public void matchesSingleFalse() { - when(this.delegate.matches(this.request)).thenReturn(false); + given(this.delegate.matches(this.request)).willReturn(false); this.matcher = new AndRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isFalse(); @@ -104,7 +104,7 @@ public class AndRequestMatcherTests { @Test public void matchesMultiBothFalse() { - when(this.delegate.matches(this.request)).thenReturn(false); + given(this.delegate.matches(this.request)).willReturn(false); this.matcher = new AndRequestMatcher(this.delegate, this.delegate2); assertThat(this.matcher.matches(this.request)).isFalse(); @@ -112,8 +112,8 @@ public class AndRequestMatcherTests { @Test public void matchesMultiSingleFalse() { - when(this.delegate.matches(this.request)).thenReturn(true); - when(this.delegate2.matches(this.request)).thenReturn(false); + given(this.delegate.matches(this.request)).willReturn(true); + given(this.delegate2.matches(this.request)).willReturn(false); this.matcher = new AndRequestMatcher(this.delegate, this.delegate2); assertThat(this.matcher.matches(this.request)).isFalse(); diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/AntPathRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/AntPathRequestMatcherTests.java index 600792426e..80696a0735 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/AntPathRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/AntPathRequestMatcherTests.java @@ -27,7 +27,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.util.UrlPathHelper; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Luke Taylor @@ -206,7 +206,7 @@ public class AntPathRequestMatcherTests { } private HttpServletRequest createRequestWithNullMethod(String path) { - when(this.request.getServletPath()).thenReturn(path); + given(this.request.getServletPath()).willReturn(path); return this.request; } diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcherTests.java index 0f8db758d2..558ea6d6a5 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/MediaTypeRequestMatcherTests.java @@ -33,7 +33,7 @@ import org.springframework.web.context.request.NativeWebRequest; 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 @@ -93,8 +93,8 @@ public class MediaTypeRequestMatcherTests { @Test public void negotiationStrategyThrowsHMTNAE() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenThrow(new HttpMediaTypeNotAcceptableException("oops")); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willThrow(new HttpMediaTypeNotAcceptableException("oops")); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.ALL); assertThat(this.matcher.matches(this.request)).isFalse(); @@ -103,8 +103,8 @@ public class MediaTypeRequestMatcherTests { @Test public void mediaAllMatches() throws Exception { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(MediaType.ALL)); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(MediaType.ALL)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); assertThat(this.matcher.matches(this.request)).isTrue(); @@ -187,8 +187,8 @@ public class MediaTypeRequestMatcherTests { @Test public void multipleMediaType() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.APPLICATION_XHTML_XML, MediaType.TEXT_HTML)); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.APPLICATION_XHTML_XML, MediaType.TEXT_HTML)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_ATOM_XML, MediaType.TEXT_HTML); @@ -205,8 +205,8 @@ public class MediaTypeRequestMatcherTests { @Test public void resolveTextPlainMatchesTextAll() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(MediaType.TEXT_PLAIN)); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(MediaType.TEXT_PLAIN)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, new MediaType("text", "*")); assertThat(this.matcher.matches(this.request)).isTrue(); @@ -222,8 +222,8 @@ public class MediaTypeRequestMatcherTests { @Test public void resolveTextAllMatchesTextPlain() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(new MediaType("text", "*"))); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(new MediaType("text", "*"))); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_PLAIN); assertThat(this.matcher.matches(this.request)).isTrue(); @@ -241,8 +241,8 @@ public class MediaTypeRequestMatcherTests { @Test public void useEqualsResolveTextAllMatchesTextPlain() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(new MediaType("text", "*"))); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(new MediaType("text", "*"))); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_PLAIN); this.matcher.setUseEquals(true); @@ -260,8 +260,8 @@ public class MediaTypeRequestMatcherTests { @Test public void useEqualsResolveTextPlainMatchesTextAll() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(MediaType.TEXT_PLAIN)); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(MediaType.TEXT_PLAIN)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, new MediaType("text", "*")); this.matcher.setUseEquals(true); @@ -279,8 +279,8 @@ public class MediaTypeRequestMatcherTests { @Test public void useEqualsSame() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(MediaType.TEXT_PLAIN)); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(MediaType.TEXT_PLAIN)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_PLAIN); this.matcher.setUseEquals(true); @@ -298,8 +298,8 @@ public class MediaTypeRequestMatcherTests { @Test public void useEqualsWithCustomMediaType() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(new MediaType("text", "unique"))); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(new MediaType("text", "unique"))); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, new MediaType("text", "unique")); this.matcher.setUseEquals(true); @@ -319,8 +319,8 @@ public class MediaTypeRequestMatcherTests { @Test public void mediaAllIgnoreMediaTypeAll() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(MediaType.ALL)); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(MediaType.ALL)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); @@ -338,8 +338,8 @@ public class MediaTypeRequestMatcherTests { @Test public void mediaAllAndTextHtmlIgnoreMediaTypeAll() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(MediaType.ALL, MediaType.TEXT_HTML)); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(MediaType.ALL, MediaType.TEXT_HTML)); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); @@ -357,8 +357,8 @@ public class MediaTypeRequestMatcherTests { @Test public void mediaAllQ08AndTextPlainIgnoreMediaTypeAll() throws HttpMediaTypeNotAcceptableException { - when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) - .thenReturn(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.parseMediaType("*/*;q=0.8"))); + given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class))) + .willReturn(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.parseMediaType("*/*;q=0.8"))); this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML); this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL)); diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/NegatedRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/NegatedRequestMatcherTests.java index c587839f38..64ecf24e69 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/NegatedRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/NegatedRequestMatcherTests.java @@ -23,7 +23,7 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -47,7 +47,7 @@ public class NegatedRequestMatcherTests { @Test public void matchesDelegateFalse() { - when(this.delegate.matches(this.request)).thenReturn(false); + given(this.delegate.matches(this.request)).willReturn(false); this.matcher = new NegatedRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isTrue(); @@ -55,7 +55,7 @@ public class NegatedRequestMatcherTests { @Test public void matchesDelegateTrue() { - when(this.delegate.matches(this.request)).thenReturn(true); + given(this.delegate.matches(this.request)).willReturn(true); this.matcher = new NegatedRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isFalse(); diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/OrRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/OrRequestMatcherTests.java index 0401304aa7..8da438fb84 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/OrRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/OrRequestMatcherTests.java @@ -27,7 +27,7 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Rob Winch @@ -79,7 +79,7 @@ public class OrRequestMatcherTests { @Test public void matchesSingleTrue() { - when(this.delegate.matches(this.request)).thenReturn(true); + given(this.delegate.matches(this.request)).willReturn(true); this.matcher = new OrRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isTrue(); @@ -87,7 +87,7 @@ public class OrRequestMatcherTests { @Test public void matchesMultiTrue() { - when(this.delegate.matches(this.request)).thenReturn(true); + given(this.delegate.matches(this.request)).willReturn(true); this.matcher = new OrRequestMatcher(this.delegate, this.delegate2); assertThat(this.matcher.matches(this.request)).isTrue(); @@ -95,7 +95,7 @@ public class OrRequestMatcherTests { @Test public void matchesSingleFalse() { - when(this.delegate.matches(this.request)).thenReturn(false); + given(this.delegate.matches(this.request)).willReturn(false); this.matcher = new OrRequestMatcher(this.delegate); assertThat(this.matcher.matches(this.request)).isFalse(); @@ -103,8 +103,8 @@ public class OrRequestMatcherTests { @Test public void matchesMultiBothFalse() { - when(this.delegate.matches(this.request)).thenReturn(false); - when(this.delegate2.matches(this.request)).thenReturn(false); + given(this.delegate.matches(this.request)).willReturn(false); + given(this.delegate2.matches(this.request)).willReturn(false); this.matcher = new OrRequestMatcher(this.delegate, this.delegate2); assertThat(this.matcher.matches(this.request)).isFalse(); @@ -112,7 +112,7 @@ public class OrRequestMatcherTests { @Test public void matchesMultiSingleFalse() { - when(this.delegate.matches(this.request)).thenReturn(true); + given(this.delegate.matches(this.request)).willReturn(true); this.matcher = new OrRequestMatcher(this.delegate, this.delegate2); assertThat(this.matcher.matches(this.request)).isTrue(); diff --git a/web/src/test/java/org/springframework/security/web/util/matcher/RegexRequestMatcherTests.java b/web/src/test/java/org/springframework/security/web/util/matcher/RegexRequestMatcherTests.java index 298629371b..37d2b2fca4 100644 --- a/web/src/test/java/org/springframework/security/web/util/matcher/RegexRequestMatcherTests.java +++ b/web/src/test/java/org/springframework/security/web/util/matcher/RegexRequestMatcherTests.java @@ -26,7 +26,7 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.BDDMockito.given; /** * @author Luke Taylor @@ -115,8 +115,8 @@ public class RegexRequestMatcherTests { } private HttpServletRequest createRequestWithNullMethod(String path) { - when(this.request.getQueryString()).thenReturn("doesntMatter"); - when(this.request.getServletPath()).thenReturn(path); + given(this.request.getQueryString()).willReturn("doesntMatter"); + given(this.request.getServletPath()).willReturn(path); return this.request; }