Replace expected @Test attributes with AssertJ

Replace JUnit expected @Test attributes with AssertJ calls.
This commit is contained in:
Phillip Webb 2020-09-10 21:33:16 -07:00 committed by Josh Cummings
parent 20baa7d409
commit c502312719
243 changed files with 2115 additions and 1591 deletions

View File

@ -166,7 +166,7 @@ public class AclImplTests {
assertThat(acl.getEntries().get(2).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2")); assertThat(acl.getEntries().get(2).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2"));
} }
@Test(expected = NotFoundException.class) @Test
public void insertAceFailsForNonExistentElement() { public void insertAceFailsForNonExistentElement() {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
@ -174,7 +174,8 @@ public class AclImplTests {
// Insert one permission // Insert one permission
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true); acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
service.updateAcl(acl); service.updateAcl(acl);
acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true); assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true));
} }
@Test @Test
@ -411,38 +412,40 @@ public class AclImplTests {
.isFalse(); .isFalse();
} }
@Test(expected = NotFoundException.class) @Test
public void insertAceRaisesNotFoundExceptionForIndexLessThanZero() { public void insertAceRaisesNotFoundExceptionForIndexLessThanZero() {
AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
acl.insertAce(-1, mock(Permission.class), mock(Sid.class), true); assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> acl.insertAce(-1, mock(Permission.class), mock(Sid.class), true));
} }
@Test(expected = NotFoundException.class) @Test
public void deleteAceRaisesNotFoundExceptionForIndexLessThanZero() { public void deleteAceRaisesNotFoundExceptionForIndexLessThanZero() {
AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
acl.deleteAce(-1); assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> acl.deleteAce(-1));
} }
@Test(expected = NotFoundException.class) @Test
public void insertAceRaisesNotFoundExceptionForIndexGreaterThanSize() { public void insertAceRaisesNotFoundExceptionForIndexGreaterThanSize() {
AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
// Insert at zero, OK. // Insert at zero, OK.
acl.insertAce(0, mock(Permission.class), mock(Sid.class), true); acl.insertAce(0, mock(Permission.class), mock(Sid.class), true);
// Size is now 1 // Size is now 1
acl.insertAce(2, mock(Permission.class), mock(Sid.class), true); assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> acl.insertAce(2, mock(Permission.class), mock(Sid.class), true));
} }
// SEC-1151 // SEC-1151
@Test(expected = NotFoundException.class) @Test
public void deleteAceRaisesNotFoundExceptionForIndexEqualToSize() { public void deleteAceRaisesNotFoundExceptionForIndexEqualToSize() {
AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
acl.insertAce(0, mock(Permission.class), mock(Sid.class), true); acl.insertAce(0, mock(Permission.class), mock(Sid.class), true);
// Size is now 1 // Size is now 1
acl.deleteAce(1); assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> acl.deleteAce(1));
} }
// SEC-1795 // SEC-1795

View File

@ -72,9 +72,9 @@ public class ObjectIdentityImplTests {
assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(mockId)); assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(mockId));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorRejectsInvalidTypeParameter() { public void constructorRejectsInvalidTypeParameter() {
new ObjectIdentityImpl("", 1L); assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl("", 1L));
} }
@Test @Test

View File

@ -54,6 +54,7 @@ import org.springframework.security.acls.model.Sid;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link BasicLookupStrategy} * Tests {@link BasicLookupStrategy}
@ -294,12 +295,13 @@ public abstract class AbstractBasicLookupStrategyTests {
assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue(); assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void nullOwnerIsNotSupported() { public void nullOwnerIsNotSupported() {
String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,104,null,null,1);"; String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,104,null,null,1);";
getJdbcTemplate().execute(query); getJdbcTemplate().execute(query);
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 104L); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 104L);
this.strategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)); assertThatIllegalArgumentException()
.isThrownBy(() -> this.strategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)));
} }
@Test @Test

View File

@ -31,6 +31,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.ConversionService;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
/** /**
@ -125,14 +126,14 @@ public class AclClassIdUtilsTests {
assertThat(newIdentifier).isEqualTo(identifier); assertThat(newIdentifier).isEqualTo(identifier);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void shouldNotAcceptNullConversionServiceInConstruction() { public void shouldNotAcceptNullConversionServiceInConstruction() {
new AclClassIdUtils(null); assertThatIllegalArgumentException().isThrownBy(() -> new AclClassIdUtils(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void shouldNotAcceptNullConversionServiceInSetter() { public void shouldNotAcceptNullConversionServiceInSetter() {
this.aclClassIdUtils.setConversionService(null); assertThatIllegalArgumentException().isThrownBy(() -> this.aclClassIdUtils.setConversionService(null));
} }
} }

View File

@ -37,6 +37,8 @@ import org.springframework.security.acls.domain.ObjectIdentityImpl;
import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentity;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests {@link BasicLookupStrategy} with Acl Class type id set to UUID. * Tests {@link BasicLookupStrategy} with Acl Class type id set to UUID.
* *
@ -110,10 +112,11 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
Assert.assertNotNull(foundAcls.get(oid)); Assert.assertNotNull(foundAcls.get(oid));
} }
@Test(expected = ConversionFailedException.class) @Test
public void testReadObjectIdentityUsingNonUuidInDatabase() { public void testReadObjectIdentityUsingNonUuidInDatabase() {
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_LONG_AS_UUID); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_LONG_AS_UUID);
this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)); assertThatExceptionOfType(ConversionFailedException.class)
.isThrownBy(() -> this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)));
} }
} }

View File

@ -94,10 +94,11 @@ public class EhCacheBasedAclCacheTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorRejectsNullParameters() { public void constructorRejectsNullParameters() {
new EhCacheBasedAclCache(null, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), assertThatIllegalArgumentException().isThrownBy(
new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER"))); () -> new EhCacheBasedAclCache(null, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()),
new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER"))));
} }
@Test @Test

View File

@ -44,6 +44,7 @@ import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.Sid;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
@ -95,13 +96,14 @@ public class JdbcAclServiceTests {
} }
// SEC-1898 // SEC-1898
@Test(expected = NotFoundException.class) @Test
public void readAclByIdMissingAcl() { public void readAclByIdMissingAcl() {
Map<ObjectIdentity, Acl> result = new HashMap<>(); Map<ObjectIdentity, Acl> result = new HashMap<>();
given(this.lookupStrategy.readAclsById(anyList(), anyList())).willReturn(result); given(this.lookupStrategy.readAclsById(anyList(), anyList())).willReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 1); ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 1);
List<Sid> sids = Arrays.<Sid>asList(new PrincipalSid("user")); List<Sid> sids = Arrays.<Sid>asList(new PrincipalSid("user"));
this.aclService.readAclById(objectIdentity, sids); assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.aclService.readAclById(objectIdentity, sids));
} }
@Test @Test

View File

@ -43,6 +43,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.util.FieldUtils; import org.springframework.security.util.FieldUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link org.springframework.security.acls.domain.SpringCacheBasedAclCache} * Tests {@link org.springframework.security.acls.domain.SpringCacheBasedAclCache}
@ -74,9 +75,9 @@ public class SpringCacheBasedAclCacheTests {
return cache; return cache;
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorRejectsNullParameters() { public void constructorRejectsNullParameters() {
new SpringCacheBasedAclCache(null, null, null); assertThatIllegalArgumentException().isThrownBy(() -> new SpringCacheBasedAclCache(null, null, null));
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")

View File

@ -98,9 +98,10 @@ public class AnnotationSecurityAspectTests {
this.secured.securedMethod(); this.secured.securedMethod();
} }
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test
public void securedClassMethodDeniesUnauthenticatedAccess() { public void securedClassMethodDeniesUnauthenticatedAccess() {
this.secured.securedClassMethod(); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.secured.securedClassMethod());
} }
@Test @Test
@ -109,17 +110,17 @@ public class AnnotationSecurityAspectTests {
this.secured.securedClassMethod(); this.secured.securedClassMethod();
} }
@Test(expected = AccessDeniedException.class) @Test
public void internalPrivateCallIsIntercepted() { public void internalPrivateCallIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(this.anne); SecurityContextHolder.getContext().setAuthentication(this.anne);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.publicCallsPrivate()); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.publicCallsPrivate());
this.securedSub.publicCallsPrivate(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.securedSub.publicCallsPrivate());
} }
@Test(expected = AccessDeniedException.class) @Test
public void protectedMethodIsIntercepted() { public void protectedMethodIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(this.anne); SecurityContextHolder.getContext().setAuthentication(this.anne);
this.secured.protectedMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.protectedMethod());
} }
@Test @Test
@ -129,11 +130,11 @@ public class AnnotationSecurityAspectTests {
} }
// SEC-1262 // SEC-1262
@Test(expected = AccessDeniedException.class) @Test
public void denyAllPreAuthorizeDeniesAccess() { public void denyAllPreAuthorizeDeniesAccess() {
configureForElAnnotations(); configureForElAnnotations();
SecurityContextHolder.getContext().setAuthentication(this.anne); SecurityContextHolder.getContext().setAuthentication(this.anne);
this.prePostSecured.denyAllMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.prePostSecured::denyAllMethod);
} }
@Test @Test

View File

@ -41,6 +41,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.authentication.WebAuthenticationDetails;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@ -199,7 +201,7 @@ public class CasAuthenticationProviderTests {
assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token)); assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
} }
@Test(expected = BadCredentialsException.class) @Test
public void missingTicketIdIsDetected() throws Exception { public void missingTicketIdIsDetected() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider(); CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
@ -211,10 +213,10 @@ public class CasAuthenticationProviderTests {
cap.afterPropertiesSet(); cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER, ""); CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER, "");
cap.authenticate(token); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> cap.authenticate(token));
} }
@Test(expected = BadCredentialsException.class) @Test
public void invalidKeyIsDetected() throws Exception { public void invalidKeyIsDetected() throws Exception {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationProvider cap = new CasAuthenticationProvider(); CasAuthenticationProvider cap = new CasAuthenticationProvider();
@ -227,30 +229,30 @@ public class CasAuthenticationProviderTests {
cap.afterPropertiesSet(); cap.afterPropertiesSet();
CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials", CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials",
AuthorityUtils.createAuthorityList("XX"), makeUserDetails(), assertion); AuthorityUtils.createAuthorityList("XX"), makeUserDetails(), assertion);
cap.authenticate(token); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> cap.authenticate(token));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void detectsMissingAuthoritiesPopulator() throws Exception { public void detectsMissingAuthoritiesPopulator() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider(); CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setKey("qwerty"); cap.setKey("qwerty");
cap.setStatelessTicketCache(new MockStatelessTicketCache()); cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setTicketValidator(new MockTicketValidator(true)); cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties()); cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void detectsMissingKey() throws Exception { public void detectsMissingKey() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider(); CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setStatelessTicketCache(new MockStatelessTicketCache()); cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setTicketValidator(new MockTicketValidator(true)); cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties()); cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void detectsMissingStatelessTicketCache() throws Exception { public void detectsMissingStatelessTicketCache() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider(); CasAuthenticationProvider cap = new CasAuthenticationProvider();
// set this explicitly to null to test failure // set this explicitly to null to test failure
@ -259,17 +261,17 @@ public class CasAuthenticationProviderTests {
cap.setKey("qwerty"); cap.setKey("qwerty");
cap.setTicketValidator(new MockTicketValidator(true)); cap.setTicketValidator(new MockTicketValidator(true));
cap.setServiceProperties(makeServiceProperties()); cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void detectsMissingTicketValidator() throws Exception { public void detectsMissingTicketValidator() throws Exception {
CasAuthenticationProvider cap = new CasAuthenticationProvider(); CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty"); cap.setKey("qwerty");
cap.setStatelessTicketCache(new MockStatelessTicketCache()); cap.setStatelessTicketCache(new MockStatelessTicketCache());
cap.setServiceProperties(makeServiceProperties()); cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet());
} }
@Test @Test

View File

@ -68,10 +68,11 @@ public class CasAuthenticationTokenTests {
"Password", AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion)); "Password", AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorWhenEmptyKeyThenThrowsException() { public void constructorWhenEmptyKeyThenThrowsException() {
new CasAuthenticationToken("", "user", "password", Collections.<GrantedAuthority>emptyList(), assertThatIllegalArgumentException().isThrownBy(
new User("user", "password", Collections.<GrantedAuthority>emptyList()), null); () -> new CasAuthenticationToken("", "user", "password", Collections.<GrantedAuthority>emptyList(),
new User("user", "password", Collections.<GrantedAuthority>emptyList()), null));
} }
@Test @Test

View File

@ -23,6 +23,7 @@ import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests * Tests
@ -56,9 +57,9 @@ public class SpringCacheBasedTicketCacheTests extends AbstractStatelessTicketCac
assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull(); assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testStartupDetectsMissingCache() throws Exception { public void testStartupDetectsMissingCache() throws Exception {
new SpringCacheBasedTicketCache(null); assertThatIllegalArgumentException().isThrownBy(() -> new SpringCacheBasedTicketCache(null));
} }
} }

View File

@ -36,6 +36,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -76,13 +77,14 @@ public class CasAuthenticationFilterTests {
assertThat(result != null).isTrue(); assertThat(result != null).isTrue();
} }
@Test(expected = AuthenticationException.class) @Test
public void testNullServiceTicketHandledGracefully() throws Exception { public void testNullServiceTicketHandledGracefully() throws Exception {
CasAuthenticationFilter filter = new CasAuthenticationFilter(); CasAuthenticationFilter filter = new CasAuthenticationFilter();
filter.setAuthenticationManager((a) -> { filter.setAuthenticationManager((a) -> {
throw new BadCredentialsException("Rejected"); throw new BadCredentialsException("Rejected");
}); });
filter.attemptAuthentication(new MockHttpServletRequest(), new MockHttpServletResponse()); assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> filter.attemptAuthentication(new MockHttpServletRequest(), new MockHttpServletResponse()));
} }
@Test @Test

View File

@ -31,10 +31,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*/ */
public class ServicePropertiesTests { public class ServicePropertiesTests {
@Test(expected = IllegalArgumentException.class) @Test
public void detectsMissingService() throws Exception { public void detectsMissingService() throws Exception {
ServiceProperties sp = new ServiceProperties(); ServiceProperties sp = new ServiceProperties();
sp.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet);
} }
@Test @Test

View File

@ -33,6 +33,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper; import org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class LdapProviderBeanDefinitionParserTests { public class LdapProviderBeanDefinitionParserTests {
@ -73,10 +74,10 @@ public class LdapProviderBeanDefinitionParserTests {
.containsExactly("member={0}", "uniqueMember={0}"); .containsExactly("member={0}", "uniqueMember={0}");
} }
@Test(expected = ApplicationContextException.class) @Test
public void missingServerEltCausesConfigException() { public void missingServerEltCausesConfigException() {
new InMemoryXmlApplicationContext( assertThatExceptionOfType(ApplicationContextException.class).isThrownBy(() -> new InMemoryXmlApplicationContext(
"<authentication-manager>" + " <ldap-authentication-provider />" + "</authentication-manager>"); "<authentication-manager>" + " <ldap-authentication-provider />" + "</authentication-manager>"));
} }
@Test @Test

View File

@ -47,14 +47,16 @@ public class InvalidConfigurationTests {
} }
// Parser should throw a SAXParseException // Parser should throw a SAXParseException
@Test(expected = XmlBeanDefinitionStoreException.class) @Test
public void passwordEncoderCannotAppearAtTopLevel() { public void passwordEncoderCannotAppearAtTopLevel() {
setContext("<password-encoder hash='md5'/>"); assertThatExceptionOfType(XmlBeanDefinitionStoreException.class)
.isThrownBy(() -> setContext("<password-encoder hash='md5'/>"));
} }
@Test(expected = XmlBeanDefinitionStoreException.class) @Test
public void authenticationProviderCannotAppearAtTopLevel() { public void authenticationProviderCannotAppearAtTopLevel() {
setContext("<authentication-provider ref='blah'/>"); assertThatExceptionOfType(XmlBeanDefinitionStoreException.class)
.isThrownBy(() -> setContext("<authentication-provider ref='blah'/>"));
} }
@Test @Test

View File

@ -38,6 +38,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Rob Winch * @author Rob Winch
@ -71,15 +72,17 @@ public class Issue50Tests {
// no exception // no exception
} }
@Test(expected = UsernameNotFoundException.class) @Test
public void authenticateWhenMissingUserThenUsernameNotFoundException() { public void authenticateWhenMissingUserThenUsernameNotFoundException() {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("test", "password")); assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "password")));
} }
@Test(expected = BadCredentialsException.class) @Test
public void authenticateWhenInvalidPasswordThenBadCredentialsException() { public void authenticateWhenInvalidPasswordThenBadCredentialsException() {
this.userRepo.save(User.withUsernameAndPassword("test", "password")); this.userRepo.save(User.withUsernameAndPassword("test", "password"));
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("test", "invalid")); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "invalid")));
} }
@Test @Test
@ -90,12 +93,12 @@ public class Issue50Tests {
assertThat(result.getName()).isEqualTo("test"); assertThat(result.getName()).isEqualTo("test");
} }
@Test(expected = AccessDeniedException.class) @Test
public void globalMethodSecurityIsEnabledWhenNotAllowedThenAccessDenied() { public void globalMethodSecurityIsEnabledWhenNotAllowedThenAccessDenied() {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test", null, "ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test", null, "ROLE_USER"));
this.userRepo.save(User.withUsernameAndPassword("denied", "password")); this.userRepo.save(User.withUsernameAndPassword("denied", "password"));
Authentication result = this.authenticationManager assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("test", "password")); .authenticate(new UsernamePasswordAuthenticationToken("test", "password")));
} }
} }

View File

@ -27,6 +27,8 @@ import org.springframework.security.config.annotation.SecurityConfigurer;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter; import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -44,14 +46,14 @@ public class AbstractConfiguredSecurityBuilderTests {
this.builder = new TestConfiguredSecurityBuilder(mock(ObjectPostProcessor.class)); this.builder = new TestConfiguredSecurityBuilder(mock(ObjectPostProcessor.class));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorWhenObjectPostProcessorIsNullThenThrowIllegalArgumentException() { public void constructorWhenObjectPostProcessorIsNullThenThrowIllegalArgumentException() {
new TestConfiguredSecurityBuilder(null); assertThatIllegalArgumentException().isThrownBy(() -> new TestConfiguredSecurityBuilder(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void objectPostProcessorWhenNullThenThrowIllegalArgumentException() { public void objectPostProcessorWhenNullThenThrowIllegalArgumentException() {
this.builder.objectPostProcessor(null); assertThatIllegalArgumentException().isThrownBy(() -> this.builder.objectPostProcessor(null));
} }
@Test @Test
@ -61,15 +63,15 @@ public class AbstractConfiguredSecurityBuilderTests {
assertThat(this.builder.getConfigurers(TestSecurityConfigurer.class)).hasSize(1); assertThat(this.builder.getConfigurers(TestSecurityConfigurer.class)).hasSize(1);
} }
@Test(expected = IllegalStateException.class) @Test
public void buildWhenBuildTwiceThenThrowIllegalStateException() throws Exception { public void buildWhenBuildTwiceThenThrowIllegalStateException() throws Exception {
this.builder.build(); this.builder.build();
this.builder.build(); assertThatIllegalStateException().isThrownBy(() -> this.builder.build());
} }
@Test(expected = IllegalStateException.class) @Test
public void getObjectWhenNotBuiltThenThrowIllegalStateException() { public void getObjectWhenNotBuiltThenThrowIllegalStateException() {
this.builder.getObject(); assertThatIllegalStateException().isThrownBy(this.builder::getObject);
} }
@Test @Test
@ -81,22 +83,22 @@ public class AbstractConfiguredSecurityBuilderTests {
verify(DelegateSecurityConfigurer.CONFIGURER).configure(this.builder); verify(DelegateSecurityConfigurer.CONFIGURER).configure(this.builder);
} }
@Test(expected = IllegalStateException.class) @Test
public void getConfigurerWhenMultipleConfigurersThenThrowIllegalStateException() throws Exception { public void getConfigurerWhenMultipleConfigurersThenThrowIllegalStateException() throws Exception {
TestConfiguredSecurityBuilder builder = new TestConfiguredSecurityBuilder(mock(ObjectPostProcessor.class), TestConfiguredSecurityBuilder builder = new TestConfiguredSecurityBuilder(mock(ObjectPostProcessor.class),
true); true);
builder.apply(new DelegateSecurityConfigurer()); builder.apply(new DelegateSecurityConfigurer());
builder.apply(new DelegateSecurityConfigurer()); builder.apply(new DelegateSecurityConfigurer());
builder.getConfigurer(DelegateSecurityConfigurer.class); assertThatIllegalStateException().isThrownBy(() -> builder.getConfigurer(DelegateSecurityConfigurer.class));
} }
@Test(expected = IllegalStateException.class) @Test
public void removeConfigurerWhenMultipleConfigurersThenThrowIllegalStateException() throws Exception { public void removeConfigurerWhenMultipleConfigurersThenThrowIllegalStateException() throws Exception {
TestConfiguredSecurityBuilder builder = new TestConfiguredSecurityBuilder(mock(ObjectPostProcessor.class), TestConfiguredSecurityBuilder builder = new TestConfiguredSecurityBuilder(mock(ObjectPostProcessor.class),
true); true);
builder.apply(new DelegateSecurityConfigurer()); builder.apply(new DelegateSecurityConfigurer());
builder.apply(new DelegateSecurityConfigurer()); builder.apply(new DelegateSecurityConfigurer());
builder.removeConfigurer(DelegateSecurityConfigurer.class); assertThatIllegalStateException().isThrownBy(() -> builder.removeConfigurer(DelegateSecurityConfigurer.class));
} }
@Test @Test

View File

@ -26,6 +26,8 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link AbstractRequestMatcherRegistry}. * Tests for {@link AbstractRequestMatcherRegistry}.
* *
@ -33,29 +35,34 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon
*/ */
public class AbstractRequestMatcherRegistryAnyMatcherTests { public class AbstractRequestMatcherRegistryAnyMatcherTests {
@Test(expected = BeanCreationException.class) @Test
public void antMatchersCanNotWorkAfterAnyRequest() { public void antMatchersCanNotWorkAfterAnyRequest() {
loadConfig(AntMatchersAfterAnyRequestConfig.class); assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(AntMatchersAfterAnyRequestConfig.class));
} }
@Test(expected = BeanCreationException.class) @Test
public void mvcMatchersCanNotWorkAfterAnyRequest() { public void mvcMatchersCanNotWorkAfterAnyRequest() {
loadConfig(MvcMatchersAfterAnyRequestConfig.class); assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(MvcMatchersAfterAnyRequestConfig.class));
} }
@Test(expected = BeanCreationException.class) @Test
public void regexMatchersCanNotWorkAfterAnyRequest() { public void regexMatchersCanNotWorkAfterAnyRequest() {
loadConfig(RegexMatchersAfterAnyRequestConfig.class); assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(RegexMatchersAfterAnyRequestConfig.class));
} }
@Test(expected = BeanCreationException.class) @Test
public void anyRequestCanNotWorkAfterItself() { public void anyRequestCanNotWorkAfterItself() {
loadConfig(AnyRequestAfterItselfConfig.class); assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(AnyRequestAfterItselfConfig.class));
} }
@Test(expected = BeanCreationException.class) @Test
public void requestMatchersCanNotWorkAfterAnyRequest() { public void requestMatchersCanNotWorkAfterAnyRequest() {
loadConfig(RequestMatchersAfterAnyRequestConfig.class); assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(RequestMatchersAfterAnyRequestConfig.class));
} }
private void loadConfig(Class<?>... configs) { private void loadConfig(Class<?>... configs) {

View File

@ -30,6 +30,7 @@ import org.springframework.security.config.test.SpringTestRule;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -41,14 +42,16 @@ public class Sec2515Tests {
public final SpringTestRule spring = new SpringTestRule(); public final SpringTestRule spring = new SpringTestRule();
// SEC-2515 // SEC-2515
@Test(expected = FatalBeanException.class) @Test
public void loadConfigWhenAuthenticationManagerNotConfiguredAndRegisterBeanThenThrowFatalBeanException() { public void loadConfigWhenAuthenticationManagerNotConfiguredAndRegisterBeanThenThrowFatalBeanException() {
this.spring.register(StackOverflowSecurityConfig.class).autowire(); assertThatExceptionOfType(FatalBeanException.class)
.isThrownBy(() -> this.spring.register(StackOverflowSecurityConfig.class).autowire());
} }
@Test(expected = FatalBeanException.class) @Test
public void loadConfigWhenAuthenticationManagerNotConfiguredAndRegisterBeanCustomNameThenThrowFatalBeanException() { public void loadConfigWhenAuthenticationManagerNotConfiguredAndRegisterBeanCustomNameThenThrowFatalBeanException() {
this.spring.register(CustomBeanNameStackOverflowSecurityConfig.class).autowire(); assertThatExceptionOfType(FatalBeanException.class)
.isThrownBy(() -> this.spring.register(CustomBeanNameStackOverflowSecurityConfig.class).autowire());
} }
// SEC-2549 // SEC-2549

View File

@ -34,6 +34,7 @@ import org.springframework.security.messaging.util.matcher.MessageMatcher;
import org.springframework.util.AntPathMatcher; import org.springframework.util.AntPathMatcher;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
@ -96,9 +97,9 @@ public class MessageSecurityMetadataSourceRegistryTests {
assertThat(getAttribute()).isEqualTo("permitAll"); assertThat(getAttribute()).isEqualTo("permitAll");
} }
@Test(expected = IllegalArgumentException.class) @Test
public void pathMatcherNull() { public void pathMatcherNull() {
this.messages.simpDestPathMatcher(null); assertThatIllegalArgumentException().isThrownBy(() -> this.messages.simpDestPathMatcher(null));
} }
@Test @Test

View File

@ -31,6 +31,8 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.crypto.password.LdapShaPasswordEncoder; import org.springframework.security.crypto.password.LdapShaPasswordEncoder;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder; import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link AuthenticationProviderBeanDefinitionParser}. * Tests for {@link AuthenticationProviderBeanDefinitionParser}.
* *
@ -140,18 +142,20 @@ public class AuthenticationProviderBeanDefinitionParserTests {
} }
// SEC-1466 // SEC-1466
@Test(expected = BeanDefinitionParsingException.class) @Test
public void exernalProviderDoesNotSupportChildElements() { public void exernalProviderDoesNotSupportChildElements() {
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
// @formatter:off // @formatter:off
this.appContext = new InMemoryXmlApplicationContext(" <authentication-manager>" this.appContext = new InMemoryXmlApplicationContext(" <authentication-manager>"
+ " <authentication-provider ref='aProvider'> " + " <authentication-provider ref='aProvider'> "
+ " <password-encoder ref='customPasswordEncoder'/>" + " <password-encoder ref='customPasswordEncoder'/>"
+ " </authentication-provider>" + " </authentication-provider>"
+ " </authentication-manager>" + " </authentication-manager>"
+ " <b:bean id='aProvider' class='org.springframework.security.authentication.TestingAuthenticationProvider'/>" + " <b:bean id='aProvider' class='org.springframework.security.authentication.TestingAuthenticationProvider'/>"
+ " <b:bean id='customPasswordEncoder' " + " <b:bean id='customPasswordEncoder' "
+ " class='org.springframework.security.authentication.encoding.Md5PasswordEncoder'/>"); + " class='org.springframework.security.authentication.encoding.Md5PasswordEncoder'/>")
// @formatter:on // @formatter:on
);
} }
private AuthenticationProvider getProvider() { private AuthenticationProvider getProvider() {

View File

@ -26,6 +26,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Luke Taylor * @author Luke Taylor
@ -122,26 +123,28 @@ public class UserServiceBeanDefinitionParserTests {
assertThat(bob.isEnabled()).isFalse(); assertThat(bob.isEnabled()).isFalse();
} }
@Test(expected = FatalBeanException.class) @Test
public void userWithBothPropertiesAndEmbeddedUsersThrowsException() { public void userWithBothPropertiesAndEmbeddedUsersThrowsException() {
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() ->
// @formatter:off // @formatter:off
setContext("<user-service id='service' properties='doesntmatter.props'>" setContext("<user-service id='service' properties='doesntmatter.props'>"
+ " <user name='joe' password='joespassword' authorities='ROLE_A'/>" + " <user name='joe' password='joespassword' authorities='ROLE_A'/>"
+ "</user-service>"); + "</user-service>")
// @formatter:on // @formatter:on
UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service"); );
userService.loadUserByUsername("Joe");
} }
@Test(expected = FatalBeanException.class) @Test
public void multipleTopLevelUseWithoutIdThrowsException() { public void multipleTopLevelUseWithoutIdThrowsException() {
setContext("<user-service properties='classpath:org/springframework/security/config/users.properties'/>" assertThatExceptionOfType(FatalBeanException.class).isThrownBy(() -> setContext(
+ "<user-service properties='classpath:org/springframework/security/config/users.properties'/>"); "<user-service properties='classpath:org/springframework/security/config/users.properties'/>"
+ "<user-service properties='classpath:org/springframework/security/config/users.properties'/>"));
} }
@Test(expected = FatalBeanException.class) @Test
public void userServiceWithMissingPropertiesFileThrowsException() { public void userServiceWithMissingPropertiesFileThrowsException() {
setContext("<user-service id='service' properties='classpath:doesntexist.properties'/>"); assertThatExceptionOfType(FatalBeanException.class).isThrownBy(
() -> setContext("<user-service id='service' properties='classpath:doesntexist.properties'/>"));
} }
private void setContext(String context) { private void setContext(String context) {

View File

@ -50,6 +50,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration @ContextConfiguration
@ -110,16 +111,16 @@ public class GrantedAuthorityDefaultsJcTests {
this.messageService.getJsrMessage(); this.messageService.getJsrMessage();
} }
@Test(expected = AccessDeniedException.class) @Test
public void messageDenied() { public void messageDenied() {
setup("DENIED"); setup("DENIED");
this.messageService.getMessage(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messageService::getMessage);
} }
@Test(expected = AccessDeniedException.class) @Test
public void jsrMessageDenied() { public void jsrMessageDenied() {
setup("DENIED"); setup("DENIED");
this.messageService.getJsrMessage(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messageService::getJsrMessage);
} }
// SEC-2926 // SEC-2926

View File

@ -43,6 +43,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration @ContextConfiguration
@ -103,16 +104,16 @@ public class GrantedAuthorityDefaultsXmlTests {
this.messageService.getJsrMessage(); this.messageService.getJsrMessage();
} }
@Test(expected = AccessDeniedException.class) @Test
public void messageDenied() { public void messageDenied() {
setup("DENIED"); setup("DENIED");
this.messageService.getMessage(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messageService::getMessage);
} }
@Test(expected = AccessDeniedException.class) @Test
public void jsrMessageDenied() { public void jsrMessageDenied() {
setup("DENIED"); setup("DENIED");
this.messageService.getJsrMessage(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messageService::getJsrMessage);
} }
// SEC-2926 // SEC-2926

View File

@ -36,6 +36,7 @@ import org.springframework.security.web.access.expression.ExpressionBasedFilterI
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource; import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link FilterInvocationSecurityMetadataSourceParser}. * Tests for {@link FilterInvocationSecurityMetadataSourceParser}.
@ -119,11 +120,12 @@ public class FilterSecurityMetadataSourceBeanDefinitionParserTests {
// @formatter:on // @formatter:on
} }
@Test(expected = BeanDefinitionParsingException.class) @Test
public void parsingInterceptUrlServletPathFails() { public void parsingInterceptUrlServletPathFails() {
setContext("<filter-security-metadata-source id='fids' use-expressions='false'>" assertThatExceptionOfType(BeanDefinitionParsingException.class)
+ " <intercept-url pattern='/secure' access='ROLE_USER' servlet-path='/spring' />" .isThrownBy(() -> setContext("<filter-security-metadata-source id='fids' use-expressions='false'>"
+ "</filter-security-metadata-source>"); + " <intercept-url pattern='/secure' access='ROLE_USER' servlet-path='/spring' />"
+ "</filter-security-metadata-source>"));
} }
private FilterInvocation createFilterInvocation(String path, String method) { private FilterInvocation createFilterInvocation(String path, String method) {

View File

@ -96,10 +96,11 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
this.target = null; this.target = null;
} }
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test
public void targetShouldPreventProtectedMethodInvocationWithNoContext() { public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
loadContext(); loadContext();
this.target.someUserMethod1(); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(this.target::someUserMethod1);
} }
@Test @Test
@ -114,13 +115,13 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
assertThat(((MethodSecurityMetadataSourceAdvisor) advisors[0]).getOrder()).isEqualTo(1001); assertThat(((MethodSecurityMetadataSourceAdvisor) advisors[0]).getOrder()).isEqualTo(1001);
} }
@Test(expected = AccessDeniedException.class) @Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() { public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
loadContext(); loadContext();
TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password", "ROLE_SOMEOTHERROLE"); TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password", "ROLE_SOMEOTHERROLE");
token.setAuthenticated(true); token.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target.someAdminMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
} }
@Test @Test
@ -138,7 +139,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
assertThat(service.getPostProcessorWasHere()).isEqualTo("Hello from the post processor!"); assertThat(service.getPostProcessorWasHere()).isEqualTo("Hello from the post processor!");
} }
@Test(expected = AccessDeniedException.class) @Test
public void worksWithAspectJAutoproxy() { public void worksWithAspectJAutoproxy() {
// @formatter:off // @formatter:off
setContext("<global-method-security>" setContext("<global-method-security>"
@ -155,7 +156,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
service.loadUserByUsername("notused"); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> service.loadUserByUsername("notused"));
} }
@Test @Test
@ -201,13 +202,14 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
this.target.someOther(0); this.target.someOther(0);
} }
@Test(expected = BeanDefinitionParsingException.class) @Test
public void duplicateElementCausesError() { public void duplicateElementCausesError() {
setContext("<global-method-security />" + "<global-method-security />"); assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> setContext("<global-method-security />" + "<global-method-security />"));
} }
// SEC-936 // SEC-936
@Test(expected = AccessDeniedException.class) @Test
public void worksWithoutTargetOrClass() { public void worksWithoutTargetOrClass() {
// @formatter:off // @formatter:off
setContext("<global-method-security secured-annotations='enabled'/>" setContext("<global-method-security secured-annotations='enabled'/>"
@ -221,7 +223,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target = (BusinessService) this.appContext.getBean("businessService"); this.target = (BusinessService) this.appContext.getBean("businessService");
this.target.someUserMethod1(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someUserMethod1);
} }
// Expression configuration tests // Expression configuration tests
@ -242,7 +244,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
.isSameAs(FieldUtils.getFieldValue(aip, "postAdvice.expressionHandler")); .isSameAs(FieldUtils.getFieldValue(aip, "postAdvice.expressionHandler"));
} }
@Test(expected = AccessDeniedException.class) @Test
public void accessIsDeniedForHasRoleExpression() { public void accessIsDeniedForHasRoleExpression() {
// @formatter:off // @formatter:off
setContext("<global-method-security pre-post-annotations='enabled'/>" setContext("<global-method-security pre-post-annotations='enabled'/>"
@ -251,7 +253,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// @formatter:on // @formatter:on
SecurityContextHolder.getContext().setAuthentication(this.bob); SecurityContextHolder.getContext().setAuthentication(this.bob);
this.target = (BusinessService) this.appContext.getBean("target"); this.target = (BusinessService) this.appContext.getBean("target");
this.target.someAdminMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
} }
@Test @Test
@ -322,7 +324,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
} }
// SEC-1450 // SEC-1450
@Test(expected = AuthenticationException.class) @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void genericsAreMatchedByProtectPointcut() { public void genericsAreMatchedByProtectPointcut() {
// @formatter:off // @formatter:off
@ -334,7 +336,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ ConfigTestUtils.AUTH_PROVIDER_XML); + ConfigTestUtils.AUTH_PROVIDER_XML);
// @formatter:on // @formatter:on
Foo foo = (Foo) this.appContext.getBean("target"); Foo foo = (Foo) this.appContext.getBean("target");
foo.foo(new SecurityConfig("A")); assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
} }
// SEC-1448 // SEC-1448

View File

@ -40,6 +40,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Luke Taylor * @author Luke Taylor
@ -82,9 +83,10 @@ public class InterceptMethodsBeanDefinitionDecoratorTests implements Application
this.target.unprotected(); this.target.unprotected();
} }
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test
public void targetShouldPreventProtectedMethodInvocationWithNoContext() { public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
this.target.doSomething(); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(this.target::doSomething);
} }
@Test @Test
@ -95,17 +97,17 @@ public class InterceptMethodsBeanDefinitionDecoratorTests implements Application
this.target.doSomething(); this.target.doSomething();
} }
@Test(expected = AccessDeniedException.class) @Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() { public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target.doSomething(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::doSomething);
} }
@Test(expected = AuthenticationException.class) @Test
public void transactionalMethodsShouldBeSecured() { public void transactionalMethodsShouldBeSecured() {
this.transactionalTarget.doSomething(); assertThatExceptionOfType(AuthenticationException.class).isThrownBy(this.transactionalTarget::doSomething);
} }
@Override @Override

View File

@ -29,6 +29,8 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Luke Taylor * @author Luke Taylor
*/ */
@ -57,9 +59,10 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test
public void targetShouldPreventProtectedMethodInvocationWithNoContext() { public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
this.target.someUserMethod1(); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.target.someUserMethod1());
} }
@Test @Test
@ -78,12 +81,12 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
this.target.someUserMethod1(); this.target.someUserMethod1();
} }
@Test(expected = AccessDeniedException.class) @Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() { public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target.someAdminMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
} }
@Test @Test

View File

@ -27,6 +27,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Rob Winch * @author Rob Winch
* *
@ -43,11 +45,11 @@ public class PreAuthorizeTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = AccessDeniedException.class) @Test
public void preAuthorizeAdminRoleDenied() { public void preAuthorizeAdminRoleDenied() {
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER")); .setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER"));
this.service.preAuthorizeAdminRole(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.service::preAuthorizeAdminRole);
} }
@Test @Test
@ -64,11 +66,12 @@ public class PreAuthorizeTests {
this.service.contactPermission(new Contact("user")); this.service.contactPermission(new Contact("user"));
} }
@Test(expected = AccessDeniedException.class) @Test
public void preAuthorizeContactPermissionDenied() { public void preAuthorizeContactPermissionDenied() {
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_ADMIN")); .setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_ADMIN"));
this.service.contactPermission(new Contact("admin")); assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.service.contactPermission(new Contact("admin")));
} }
} }

View File

@ -26,6 +26,8 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.util.InMemoryXmlApplicationContext; import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Rob Winch * @author Rob Winch
* *
@ -34,14 +36,14 @@ public class Sec2196Tests {
private ConfigurableApplicationContext context; private ConfigurableApplicationContext context;
@Test(expected = AccessDeniedException.class) @Test
public void genericMethodsProtected() { public void genericMethodsProtected() {
loadContext("<global-method-security secured-annotations=\"enabled\" pre-post-annotations=\"enabled\"/>" loadContext("<global-method-security secured-annotations=\"enabled\" pre-post-annotations=\"enabled\"/>"
+ "<b:bean class='" + Service.class.getName() + "'/>"); + "<b:bean class='" + Service.class.getName() + "'/>");
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("test", "pass", "ROLE_USER")); .setAuthentication(new TestingAuthenticationToken("test", "pass", "ROLE_USER"));
Service service = this.context.getBean(Service.class); Service service = this.context.getBean(Service.class);
service.save(new User()); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> service.save(new User()));
} }
@Test @Test

View File

@ -65,9 +65,10 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test
public void targetShouldPreventProtectedMethodInvocationWithNoContext() { public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
this.target.someUserMethod1(); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(this.target::someUserMethod1);
} }
@Test @Test
@ -78,28 +79,29 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
this.target.someUserMethod1(); this.target.someUserMethod1();
} }
@Test(expected = AccessDeniedException.class) @Test
public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() { public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHER")); AuthorityUtils.createAuthorityList("ROLE_SOMEOTHER"));
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
this.target.someAdminMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.target::someAdminMethod);
} }
// SEC-1387 // SEC-1387
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test
public void targetIsSerializableBeforeUse() throws Exception { public void targetIsSerializableBeforeUse() throws Exception {
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target); BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target);
chompedTarget.someAdminMethod(); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(chompedTarget::someAdminMethod);
} }
@Test(expected = AccessDeniedException.class) @Test
public void targetIsSerializableAfterUse() throws Exception { public void targetIsSerializableAfterUse() throws Exception {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(this.target::someAdminMethod); .isThrownBy(this.target::someAdminMethod);
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("u", "p", "ROLE_A")); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("u", "p", "ROLE_A"));
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target); BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target);
chompedTarget.someAdminMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(chompedTarget::someAdminMethod);
} }
private Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException { private Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException {

View File

@ -27,6 +27,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Rob Winch * @author Rob Winch
* *
@ -43,11 +45,11 @@ public class SecuredTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = AccessDeniedException.class) @Test
public void securedAdminRoleDenied() { public void securedAdminRoleDenied() {
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER")); .setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER"));
this.service.securedAdminRole(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.service::securedAdminRole);
} }
@Test @Test

View File

@ -31,6 +31,7 @@ import org.springframework.security.config.annotation.method.configuration.Enabl
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -44,9 +45,9 @@ public class Gh4020GlobalMethodSecurityConfigurationTests {
DenyAllService denyAll; DenyAllService denyAll;
// gh-4020 // gh-4020
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test
public void denyAll() { public void denyAll() {
this.denyAll.denyAll(); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(this.denyAll::denyAll);
} }
@Configuration @Configuration

View File

@ -23,6 +23,8 @@ import org.springframework.security.config.annotation.web.reactive.ServerHttpSec
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder; import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/** /**
* @author Rob Winch * @author Rob Winch
* @since 5.0 * @since 5.0
@ -105,31 +107,34 @@ public class AuthorizeExchangeSpecTests {
// @formatter:on // @formatter:on
} }
@Test(expected = IllegalStateException.class) @Test
public void antMatchersWhenNoAccessAndAnotherMatcherThenThrowsException() { public void antMatchersWhenNoAccessAndAnotherMatcherThenThrowsException() {
this.http.authorizeExchange().pathMatchers("/incomplete"); this.http.authorizeExchange().pathMatchers("/incomplete");
this.http.authorizeExchange().pathMatchers("/throws-exception"); assertThatIllegalStateException()
.isThrownBy(() -> this.http.authorizeExchange().pathMatchers("/throws-exception"));
} }
@Test(expected = IllegalStateException.class) @Test
public void anyExchangeWhenFollowedByMatcherThenThrowsException() { public void anyExchangeWhenFollowedByMatcherThenThrowsException() {
assertThatIllegalStateException().isThrownBy(() ->
// @formatter:off // @formatter:off
this.http.authorizeExchange() this.http.authorizeExchange()
.anyExchange().denyAll() .anyExchange().denyAll()
.pathMatchers("/never-reached"); .pathMatchers("/never-reached")
// @formatter:on // @formatter:on
);
} }
@Test(expected = IllegalStateException.class) @Test
public void buildWhenMatcherDefinedWithNoAccessThenThrowsException() { public void buildWhenMatcherDefinedWithNoAccessThenThrowsException() {
this.http.authorizeExchange().pathMatchers("/incomplete"); this.http.authorizeExchange().pathMatchers("/incomplete");
this.http.build(); assertThatIllegalStateException().isThrownBy(this.http::build);
} }
@Test(expected = IllegalStateException.class) @Test
public void buildWhenMatcherDefinedWithNoAccessInLambdaThenThrowsException() { public void buildWhenMatcherDefinedWithNoAccessInLambdaThenThrowsException() {
this.http.authorizeExchange((exchanges) -> exchanges.pathMatchers("/incomplete")); this.http.authorizeExchange((exchanges) -> exchanges.pathMatchers("/incomplete"));
this.http.build(); assertThatIllegalStateException().isThrownBy(this.http::build);
} }
private WebTestClient buildClient() { private WebTestClient buildClient() {

View File

@ -84,7 +84,7 @@ public class MethodSecurityInterceptorWithAopConfigTests {
} }
} }
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test
public void securityInterceptorIsAppliedWhenUsedWithAopConfig() { public void securityInterceptorIsAppliedWhenUsedWithAopConfig() {
// @formatter:off // @formatter:off
setContext("<aop:config>" setContext("<aop:config>"
@ -99,10 +99,11 @@ public class MethodSecurityInterceptorWithAopConfigTests {
// Check both against interface and class // Check both against interface and class
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeLowerCase("TEST")); .isThrownBy(() -> target.makeLowerCase("TEST"));
target.makeUpperCase("test"); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeUpperCase("test"));
} }
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test
public void securityInterceptorIsAppliedWhenUsedWithBeanNameAutoProxyCreator() { public void securityInterceptorIsAppliedWhenUsedWithBeanNameAutoProxyCreator() {
// @formatter:off // @formatter:off
setContext("<b:bean id='autoProxyCreator' class='org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator'>" setContext("<b:bean id='autoProxyCreator' class='org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator'>"
@ -126,7 +127,8 @@ public class MethodSecurityInterceptorWithAopConfigTests {
ITargetObject target = (ITargetObject) this.appContext.getBean("target"); ITargetObject target = (ITargetObject) this.appContext.getBean("target");
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeLowerCase("TEST")); .isThrownBy(() -> target.makeLowerCase("TEST"));
target.makeUpperCase("test"); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeUpperCase("test"));
} }
private void setContext(String context) { private void setContext(String context) {

View File

@ -22,6 +22,8 @@ import org.springframework.security.access.event.AuthenticationCredentialsNotFou
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.util.SimpleMethodInvocation; import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link AuthenticationCredentialsNotFoundEvent}. * Tests {@link AuthenticationCredentialsNotFoundEvent}.
* *
@ -29,22 +31,24 @@ import org.springframework.security.util.SimpleMethodInvocation;
*/ */
public class AuthenticationCredentialsNotFoundEventTests { public class AuthenticationCredentialsNotFoundEventTests {
@Test(expected = IllegalArgumentException.class) @Test
public void testRejectsNulls() { public void testRejectsNulls() {
new AuthenticationCredentialsNotFoundEvent(null, SecurityConfig.createList("TEST"), assertThatIllegalArgumentException().isThrownBy(() -> new AuthenticationCredentialsNotFoundEvent(null,
new AuthenticationCredentialsNotFoundException("test")); SecurityConfig.createList("TEST"), new AuthenticationCredentialsNotFoundException("test")));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testRejectsNulls2() { public void testRejectsNulls2() {
new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), null, assertThatIllegalArgumentException()
new AuthenticationCredentialsNotFoundException("test")); .isThrownBy(() -> new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), null,
new AuthenticationCredentialsNotFoundException("test")));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testRejectsNulls3() { public void testRejectsNulls3() {
new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(), SecurityConfig.createList("TEST"), assertThatIllegalArgumentException()
null); .isThrownBy(() -> new AuthenticationCredentialsNotFoundEvent(new SimpleMethodInvocation(),
SecurityConfig.createList("TEST"), null));
} }
} }

View File

@ -25,6 +25,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.util.SimpleMethodInvocation; import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link AuthorizationFailureEvent}. * Tests {@link AuthorizationFailureEvent}.
@ -39,24 +40,29 @@ public class AuthorizationFailureEventTests {
private AccessDeniedException exception = new AuthorizationServiceException("error", new Throwable()); private AccessDeniedException exception = new AuthorizationServiceException("error", new Throwable());
@Test(expected = IllegalArgumentException.class) @Test
public void rejectsNullSecureObject() { public void rejectsNullSecureObject() {
new AuthorizationFailureEvent(null, this.attributes, this.foo, this.exception); assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizationFailureEvent(null, this.attributes, this.foo, this.exception));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void rejectsNullAttributesList() { public void rejectsNullAttributesList() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), null, this.foo, this.exception); assertThatIllegalArgumentException().isThrownBy(
() -> new AuthorizationFailureEvent(new SimpleMethodInvocation(), null, this.foo, this.exception));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void rejectsNullAuthentication() { public void rejectsNullAuthentication() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, null, this.exception); assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, null,
this.exception));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void rejectsNullException() { public void rejectsNullException() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, this.foo, null); assertThatIllegalArgumentException().isThrownBy(
() -> new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, this.foo, null));
} }
@Test @Test

View File

@ -22,6 +22,8 @@ import org.springframework.security.access.event.AuthorizedEvent;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.util.SimpleMethodInvocation; import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link AuthorizedEvent}. * Tests {@link AuthorizedEvent}.
* *
@ -29,20 +31,22 @@ import org.springframework.security.util.SimpleMethodInvocation;
*/ */
public class AuthorizedEventTests { public class AuthorizedEventTests {
@Test(expected = IllegalArgumentException.class) @Test
public void testRejectsNulls() { public void testRejectsNulls() {
new AuthorizedEvent(null, SecurityConfig.createList("TEST"), assertThatIllegalArgumentException().isThrownBy(() -> new AuthorizedEvent(null,
new UsernamePasswordAuthenticationToken("foo", "bar")); SecurityConfig.createList("TEST"), new UsernamePasswordAuthenticationToken("foo", "bar")));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testRejectsNulls2() { public void testRejectsNulls2() {
new AuthorizedEvent(new SimpleMethodInvocation(), null, new UsernamePasswordAuthenticationToken("foo", "bar")); assertThatIllegalArgumentException().isThrownBy(() -> new AuthorizedEvent(new SimpleMethodInvocation(), null,
new UsernamePasswordAuthenticationToken("foo", "bar")));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testRejectsNulls3() { public void testRejectsNulls3() {
new AuthorizedEvent(new SimpleMethodInvocation(), SecurityConfig.createList("TEST"), null); assertThatIllegalArgumentException().isThrownBy(
() -> new AuthorizedEvent(new SimpleMethodInvocation(), SecurityConfig.createList("TEST"), null));
} }
} }

View File

@ -19,6 +19,8 @@ package org.springframework.security.access;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link SecurityConfig}. * Tests {@link SecurityConfig}.
@ -33,19 +35,20 @@ public class SecurityConfigTests {
assertThat(config.hashCode()).isEqualTo("TEST".hashCode()); assertThat(config.hashCode()).isEqualTo("TEST".hashCode());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCannotConstructWithNullAttribute() { public void testCannotConstructWithNullAttribute() {
new SecurityConfig(null); // SEC-727 assertThatIllegalArgumentException().isThrownBy(() -> new SecurityConfig(null)); // SEC-727
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testCannotConstructWithEmptyAttribute() { public void testCannotConstructWithEmptyAttribute() {
new SecurityConfig(""); // SEC-727 assertThatIllegalArgumentException().isThrownBy(() -> new SecurityConfig("")); // SEC-727
} }
@Test(expected = NoSuchMethodException.class) @Test
public void testNoArgConstructorDoesntExist() throws Exception { public void testNoArgConstructorDoesntExist() throws Exception {
SecurityConfig.class.getDeclaredConstructor((Class[]) null); assertThatExceptionOfType(NoSuchMethodException.class)
.isThrownBy(() -> SecurityConfig.class.getDeclaredConstructor((Class[]) null));
} }
@Test @Test

View File

@ -27,6 +27,7 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -57,9 +58,9 @@ public class AbstractSecurityExpressionHandlerTests {
.isEqualTo(true); .isEqualTo(true);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void setExpressionParserNull() { public void setExpressionParserNull() {
this.handler.setExpressionParser(null); assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setExpressionParser(null));
} }
@Test @Test

View File

@ -37,6 +37,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
@ -69,9 +70,9 @@ public class DefaultMethodSecurityExpressionHandlerTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void setTrustResolverNull() { public void setTrustResolverNull() {
this.handler.setTrustResolver(null); assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setTrustResolver(null));
} }
@Test @Test

View File

@ -30,6 +30,7 @@ import org.springframework.security.access.prepost.PreInvocationAttribute;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link ExpressionBasedPreInvocationAdvice} * Tests {@link ExpressionBasedPreInvocationAdvice}
@ -50,21 +51,23 @@ public class ExpressionBasedPreInvocationAdviceTests {
this.expressionBasedPreInvocationAdvice = new ExpressionBasedPreInvocationAdvice(); this.expressionBasedPreInvocationAdvice = new ExpressionBasedPreInvocationAdvice();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void findFilterTargetNameProvidedButNotMatch() throws Exception { public void findFilterTargetNameProvidedButNotMatch() throws Exception {
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "filterTargetDoesNotMatch", PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "filterTargetDoesNotMatch",
null); null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingCollection", new Class[] { List.class }, new Object[] { new ArrayList<>() }); "doSomethingCollection", new Class[] { List.class }, new Object[] { new ArrayList<>() });
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute); assertThatIllegalArgumentException().isThrownBy(
() -> this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void findFilterTargetNameProvidedArrayUnsupported() throws Exception { public void findFilterTargetNameProvidedArrayUnsupported() throws Exception {
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "param", null); PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "param", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingArray", new Class[] { String[].class }, new Object[] { new String[0] }); "doSomethingArray", new Class[] { String[].class }, new Object[] { new String[0] });
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute); assertThatIllegalArgumentException().isThrownBy(
() -> this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute));
} }
@Test @Test
@ -77,12 +80,13 @@ public class ExpressionBasedPreInvocationAdviceTests {
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void findFilterTargetNameNotProvidedArrayUnsupported() throws Exception { public void findFilterTargetNameNotProvidedArrayUnsupported() throws Exception {
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null); PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingArray", new Class[] { String[].class }, new Object[] { new String[0] }); "doSomethingArray", new Class[] { String[].class }, new Object[] { new String[0] });
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute); assertThatIllegalArgumentException().isThrownBy(
() -> this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute));
} }
@Test @Test
@ -95,21 +99,23 @@ public class ExpressionBasedPreInvocationAdviceTests {
assertThat(result).isTrue(); assertThat(result).isTrue();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void findFilterTargetNameNotProvidedTypeNotSupported() throws Exception { public void findFilterTargetNameNotProvidedTypeNotSupported() throws Exception {
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null); PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingString", new Class[] { String.class }, new Object[] { "param" }); "doSomethingString", new Class[] { String.class }, new Object[] { "param" });
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute); assertThatIllegalArgumentException().isThrownBy(
() -> this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void findFilterTargetNameNotProvidedMethodAcceptMoreThenOneArgument() throws Exception { public void findFilterTargetNameNotProvidedMethodAcceptMoreThenOneArgument() throws Exception {
PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null); PreInvocationAttribute attribute = new PreInvocationExpressionAttribute("true", "", null);
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class, MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingTwoArgs", new Class[] { String.class, List.class }, "doSomethingTwoArgs", new Class[] { String.class, List.class },
new Object[] { "param", new ArrayList<>() }); new Object[] { "param", new ArrayList<>() });
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute); assertThatIllegalArgumentException().isThrownBy(
() -> this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute));
} }
private class TestClass { private class TestClass {

View File

@ -32,6 +32,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.util.SimpleMethodInvocation; import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public class MethodExpressionVoterTests { public class MethodExpressionVoterTests {
@ -86,28 +87,28 @@ public class MethodExpressionVoterTests {
assertThat(arg).containsExactly("joe", "sam"); assertThat(arg).containsExactly("joe", "sam");
} }
@Test(expected = IllegalArgumentException.class) @Test
public void arraysCannotBePrefiltered() throws Exception { public void arraysCannotBePrefiltered() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray(), MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray(),
createArrayArg("sam", "joe")); createArrayArg("sam", "joe"));
this.am.vote(this.joe, mi, assertThatIllegalArgumentException().isThrownBy(() -> this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'jim')", "someArray", null))); createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'jim')", "someArray", null))));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void incorrectFilterTargetNameIsRejected() throws Exception { public void incorrectFilterTargetNameIsRejected() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(), MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(),
createCollectionArg("joe", "bob")); createCollectionArg("joe", "bob"));
this.am.vote(this.joe, mi, assertThatIllegalArgumentException().isThrownBy(() -> this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collcetion", null))); createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collcetion", null))));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void nullNamedFilterTargetIsRejected() throws Exception { public void nullNamedFilterTargetIsRejected() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(), MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(),
new Object[] { null }); new Object[] { null });
this.am.vote(this.joe, mi, assertThatIllegalArgumentException().isThrownBy(() -> this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collection", null))); createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collection", null))));
} }
@Test @Test

View File

@ -26,6 +26,7 @@ import java.util.TreeMap;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests for {@link RoleHierarchyUtils}. * Tests for {@link RoleHierarchyUtils}.
@ -52,42 +53,47 @@ public class RoleHierarchyUtilsTests {
assertThat(roleHierarchy).isEqualTo(expectedRoleHierarchy); assertThat(roleHierarchy).isEqualTo(expectedRoleHierarchy);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void roleHierarchyFromMapWhenMapNullThenThrowsIllegalArgumentException() { public void roleHierarchyFromMapWhenMapNullThenThrowsIllegalArgumentException() {
RoleHierarchyUtils.roleHierarchyFromMap(null); assertThatIllegalArgumentException().isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void roleHierarchyFromMapWhenMapEmptyThenThrowsIllegalArgumentException() { public void roleHierarchyFromMapWhenMapEmptyThenThrowsIllegalArgumentException() {
RoleHierarchyUtils.roleHierarchyFromMap(Collections.<String, List<String>>emptyMap()); assertThatIllegalArgumentException().isThrownBy(
() -> RoleHierarchyUtils.roleHierarchyFromMap(Collections.<String, List<String>>emptyMap()));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void roleHierarchyFromMapWhenRoleNullThenThrowsIllegalArgumentException() { public void roleHierarchyFromMapWhenRoleNullThenThrowsIllegalArgumentException() {
Map<String, List<String>> roleHierarchyMap = new HashMap<>(); Map<String, List<String>> roleHierarchyMap = new HashMap<>();
roleHierarchyMap.put(null, Arrays.asList("ROLE_B", "ROLE_C")); roleHierarchyMap.put(null, Arrays.asList("ROLE_B", "ROLE_C"));
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap); assertThatIllegalArgumentException()
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void roleHierarchyFromMapWhenRoleEmptyThenThrowsIllegalArgumentException() { public void roleHierarchyFromMapWhenRoleEmptyThenThrowsIllegalArgumentException() {
Map<String, List<String>> roleHierarchyMap = new HashMap<>(); Map<String, List<String>> roleHierarchyMap = new HashMap<>();
roleHierarchyMap.put("", Arrays.asList("ROLE_B", "ROLE_C")); roleHierarchyMap.put("", Arrays.asList("ROLE_B", "ROLE_C"));
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap); assertThatIllegalArgumentException()
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void roleHierarchyFromMapWhenImpliedRolesNullThenThrowsIllegalArgumentException() { public void roleHierarchyFromMapWhenImpliedRolesNullThenThrowsIllegalArgumentException() {
Map<String, List<String>> roleHierarchyMap = new HashMap<>(); Map<String, List<String>> roleHierarchyMap = new HashMap<>();
roleHierarchyMap.put("ROLE_A", null); roleHierarchyMap.put("ROLE_A", null);
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap); assertThatIllegalArgumentException()
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void roleHierarchyFromMapWhenImpliedRolesEmptyThenThrowsIllegalArgumentException() { public void roleHierarchyFromMapWhenImpliedRolesEmptyThenThrowsIllegalArgumentException() {
Map<String, List<String>> roleHierarchyMap = new HashMap<>(); Map<String, List<String>> roleHierarchyMap = new HashMap<>();
roleHierarchyMap.put("ROLE_A", Collections.<String>emptyList()); roleHierarchyMap.put("ROLE_A", Collections.<String>emptyList());
RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap); assertThatIllegalArgumentException()
.isThrownBy(() -> RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap));
} }
} }

View File

@ -23,6 +23,7 @@ import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.util.SimpleMethodInvocation; import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -33,7 +34,7 @@ import static org.mockito.Mockito.mock;
*/ */
public class AbstractSecurityInterceptorTests { public class AbstractSecurityInterceptorTests {
@Test(expected = IllegalArgumentException.class) @Test
public void detectsIfInvocationPassedIncompatibleSecureObject() { public void detectsIfInvocationPassedIncompatibleSecureObject() {
MockSecurityInterceptorWhichOnlySupportsStrings si = new MockSecurityInterceptorWhichOnlySupportsStrings(); MockSecurityInterceptorWhichOnlySupportsStrings si = new MockSecurityInterceptorWhichOnlySupportsStrings();
si.setRunAsManager(mock(RunAsManager.class)); si.setRunAsManager(mock(RunAsManager.class));
@ -41,10 +42,10 @@ public class AbstractSecurityInterceptorTests {
si.setAfterInvocationManager(mock(AfterInvocationManager.class)); si.setAfterInvocationManager(mock(AfterInvocationManager.class));
si.setAccessDecisionManager(mock(AccessDecisionManager.class)); si.setAccessDecisionManager(mock(AccessDecisionManager.class));
si.setSecurityMetadataSource(mock(SecurityMetadataSource.class)); si.setSecurityMetadataSource(mock(SecurityMetadataSource.class));
si.beforeInvocation(new SimpleMethodInvocation()); assertThatIllegalArgumentException().isThrownBy(() -> si.beforeInvocation(new SimpleMethodInvocation()));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void detectsViolationOfGetSecureObjectClassMethod() throws Exception { public void detectsViolationOfGetSecureObjectClassMethod() throws Exception {
MockSecurityInterceptorReturnsNull si = new MockSecurityInterceptorReturnsNull(); MockSecurityInterceptorReturnsNull si = new MockSecurityInterceptorReturnsNull();
si.setRunAsManager(mock(RunAsManager.class)); si.setRunAsManager(mock(RunAsManager.class));
@ -52,7 +53,7 @@ public class AbstractSecurityInterceptorTests {
si.setAfterInvocationManager(mock(AfterInvocationManager.class)); si.setAfterInvocationManager(mock(AfterInvocationManager.class));
si.setAccessDecisionManager(mock(AccessDecisionManager.class)); si.setAccessDecisionManager(mock(AccessDecisionManager.class));
si.setSecurityMetadataSource(mock(SecurityMetadataSource.class)); si.setSecurityMetadataSource(mock(SecurityMetadataSource.class));
si.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(si::afterPropertiesSet);
} }
private class MockSecurityInterceptorReturnsNull extends AbstractSecurityInterceptor { private class MockSecurityInterceptorReturnsNull extends AbstractSecurityInterceptor {

View File

@ -26,19 +26,21 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link RunAsImplAuthenticationProvider}. * Tests {@link RunAsImplAuthenticationProvider}.
*/ */
public class RunAsImplAuthenticationProviderTests { public class RunAsImplAuthenticationProviderTests {
@Test(expected = BadCredentialsException.class) @Test
public void testAuthenticationFailDueToWrongKey() { public void testAuthenticationFailDueToWrongKey() {
RunAsUserToken token = new RunAsUserToken("wrong_key", "Test", "Password", RunAsUserToken token = new RunAsUserToken("wrong_key", "Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class); AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), UsernamePasswordAuthenticationToken.class);
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider(); RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
provider.setKey("hello_world"); provider.setKey("hello_world");
provider.authenticate(token); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
} }
@Test @Test
@ -53,10 +55,10 @@ public class RunAsImplAuthenticationProviderTests {
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode()); assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testStartupFailsIfNoKey() throws Exception { public void testStartupFailsIfNoKey() throws Exception {
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider(); RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
provider.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
} }
@Test @Test

View File

@ -48,6 +48,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
@ -124,63 +125,63 @@ public class MethodSecurityInterceptorTests {
assertThat(this.interceptor.getAfterInvocationManager()).isEqualTo(aim); assertThat(this.interceptor.getAfterInvocationManager()).isEqualTo(aim);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void missingAccessDecisionManagerIsDetected() throws Exception { public void missingAccessDecisionManagerIsDetected() throws Exception {
this.interceptor.setAccessDecisionManager(null); this.interceptor.setAccessDecisionManager(null);
this.interceptor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void missingAuthenticationManagerIsDetected() throws Exception { public void missingAuthenticationManagerIsDetected() throws Exception {
this.interceptor.setAuthenticationManager(null); this.interceptor.setAuthenticationManager(null);
this.interceptor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void missingMethodSecurityMetadataSourceIsRejected() throws Exception { public void missingMethodSecurityMetadataSourceIsRejected() throws Exception {
this.interceptor.setSecurityMetadataSource(null); this.interceptor.setSecurityMetadataSource(null);
this.interceptor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void missingRunAsManagerIsRejected() throws Exception { public void missingRunAsManagerIsRejected() throws Exception {
this.interceptor.setRunAsManager(null); this.interceptor.setRunAsManager(null);
this.interceptor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation() throws Throwable { public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation() throws Throwable {
given(this.mds.supports(MethodInvocation.class)).willReturn(false); given(this.mds.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation() throws Exception { public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation() throws Exception {
given(this.mds.supports(MethodInvocation.class)).willReturn(true); given(this.mds.supports(MethodInvocation.class)).willReturn(true);
given(this.adm.supports(MethodInvocation.class)).willReturn(false); given(this.adm.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation() throws Exception { public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation() throws Exception {
final RunAsManager ram = mock(RunAsManager.class); final RunAsManager ram = mock(RunAsManager.class);
given(ram.supports(MethodInvocation.class)).willReturn(false); given(ram.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.setRunAsManager(ram); this.interceptor.setRunAsManager(ram);
this.interceptor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation() throws Exception { public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation() throws Exception {
final AfterInvocationManager aim = mock(AfterInvocationManager.class); final AfterInvocationManager aim = mock(AfterInvocationManager.class);
given(aim.supports(MethodInvocation.class)).willReturn(false); given(aim.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.setAfterInvocationManager(aim); this.interceptor.setAfterInvocationManager(aim);
this.interceptor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes() throws Exception { public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes() throws Exception {
given(this.adm.supports(any(ConfigAttribute.class))).willReturn(false); given(this.adm.supports(any(ConfigAttribute.class))).willReturn(false);
this.interceptor.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet());
} }
@Test @Test
@ -219,13 +220,14 @@ public class MethodSecurityInterceptorTests {
assertThat(!this.token.isAuthenticated()).isTrue(); assertThat(!this.token.isAuthenticated()).isTrue();
} }
@Test(expected = AuthenticationException.class) @Test
public void callIsntMadeWhenAuthenticationManagerRejectsAuthentication() { public void callIsntMadeWhenAuthenticationManagerRejectsAuthentication() {
final TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password"); final TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password");
SecurityContextHolder.getContext().setAuthentication(token); SecurityContextHolder.getContext().setAuthentication(token);
mdsReturnsUserRole(); mdsReturnsUserRole();
given(this.authman.authenticate(token)).willThrow(new BadCredentialsException("rejected")); given(this.authman.authenticate(token)).willThrow(new BadCredentialsException("rejected"));
this.advisedTarget.makeLowerCase("HELLO"); assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> this.advisedTarget.makeLowerCase("HELLO"));
} }
@Test @Test
@ -256,9 +258,9 @@ public class MethodSecurityInterceptorTests {
verify(this.eventPublisher).publishEvent(any(AuthorizationFailureEvent.class)); verify(this.eventPublisher).publishEvent(any(AuthorizationFailureEvent.class));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void rejectsNullSecuredObjects() throws Throwable { public void rejectsNullSecuredObjects() throws Throwable {
this.interceptor.invoke(null); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.invoke(null));
} }
@Test @Test
@ -299,10 +301,11 @@ public class MethodSecurityInterceptorTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
} }
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test
public void emptySecurityContextIsRejected() { public void emptySecurityContextIsRejected() {
mdsReturnsUserRole(); mdsReturnsUserRole();
this.advisedTarget.makeUpperCase("hello"); assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.advisedTarget.makeUpperCase("hello"));
} }
@Test @Test

View File

@ -30,6 +30,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -89,19 +90,21 @@ public class AffirmativeBasedTests {
this.mgr.decide(this.user, new Object(), this.attrs); this.mgr.decide(this.user, new Object(), this.attrs);
} }
@Test(expected = AccessDeniedException.class) @Test
public void oneDenyVoteTwoAbstainVotesDeniesAccess() { public void oneDenyVoteTwoAbstainVotesDeniesAccess() {
this.mgr = new AffirmativeBased( this.mgr = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.deny, this.abstain, this.abstain)); Arrays.<AccessDecisionVoter<? extends Object>>asList(this.deny, this.abstain, this.abstain));
this.mgr.decide(this.user, new Object(), this.attrs); assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.mgr.decide(this.user, new Object(), this.attrs));
} }
@Test(expected = AccessDeniedException.class) @Test
public void onlyAbstainVotesDeniesAccessWithDefault() { public void onlyAbstainVotesDeniesAccessWithDefault() {
this.mgr = new AffirmativeBased( this.mgr = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.abstain, this.abstain, this.abstain)); Arrays.<AccessDecisionVoter<? extends Object>>asList(this.abstain, this.abstain, this.abstain));
assertThat(!this.mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default assertThat(!this.mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
this.mgr.decide(this.user, new Object(), this.attrs); assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.mgr.decide(this.user, new Object(), this.attrs));
} }
@Test @Test

View File

@ -28,7 +28,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.TestingAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests {@link ConsensusBased}. * Tests {@link ConsensusBased}.
@ -37,14 +37,14 @@ import static org.assertj.core.api.Assertions.fail;
*/ */
public class ConsensusBasedTests { public class ConsensusBasedTests {
@Test(expected = AccessDeniedException.class) @Test
public void testOneAffirmativeVoteOneDenyVoteOneAbstainVoteDeniesAccessWithoutDefault() { public void testOneAffirmativeVoteOneDenyVoteOneAbstainVoteDeniesAccessWithoutDefault() {
TestingAuthenticationToken auth = makeTestToken(); TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager(); ConsensusBased mgr = makeDecisionManager();
mgr.setAllowIfEqualGrantedDeniedDecisions(false); mgr.setAllowIfEqualGrantedDeniedDecisions(false);
assertThat(!mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check changed assertThat(!mgr.isAllowIfEqualGrantedDeniedDecisions()).isTrue(); // check changed
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1", "DENY_FOR_SURE"); List<ConfigAttribute> config = SecurityConfig.createList("ROLE_1", "DENY_FOR_SURE");
mgr.decide(auth, new Object(), config); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config));
} }
@Test @Test
@ -63,20 +63,21 @@ public class ConsensusBasedTests {
mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_2")); mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_2"));
} }
@Test(expected = AccessDeniedException.class) @Test
public void testOneDenyVoteTwoAbstainVotesDeniesAccess() { public void testOneDenyVoteTwoAbstainVotesDeniesAccess() {
TestingAuthenticationToken auth = makeTestToken(); TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager(); ConsensusBased mgr = makeDecisionManager();
mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE")); assertThatExceptionOfType(AccessDeniedException.class)
fail("Should have thrown AccessDeniedException"); .isThrownBy(() -> mgr.decide(auth, new Object(), SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE")));
} }
@Test(expected = AccessDeniedException.class) @Test
public void testThreeAbstainVotesDeniesAccessWithDefault() { public void testThreeAbstainVotesDeniesAccessWithDefault() {
TestingAuthenticationToken auth = makeTestToken(); TestingAuthenticationToken auth = makeTestToken();
ConsensusBased mgr = makeDecisionManager(); ConsensusBased mgr = makeDecisionManager();
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL")); assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> mgr.decide(auth, new Object(), SecurityConfig.createList("IGNORED_BY_ALL")));
} }
@Test @Test

View File

@ -27,6 +27,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
@ -46,12 +47,13 @@ public class AbstractAuthenticationTokenTests {
this.authorities = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"); this.authorities = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
} }
@Test(expected = UnsupportedOperationException.class) @Test
public void testAuthoritiesAreImmutable() { public void testAuthoritiesAreImmutable() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", this.authorities); MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", this.authorities);
List<GrantedAuthority> gotAuthorities = (List<GrantedAuthority>) token.getAuthorities(); List<GrantedAuthority> gotAuthorities = (List<GrantedAuthority>) token.getAuthorities();
assertThat(gotAuthorities).isNotSameAs(this.authorities); assertThat(gotAuthorities).isNotSameAs(this.authorities);
gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER")); assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER")));
} }
@Test @Test

View File

@ -36,6 +36,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset; import static org.mockito.Mockito.reset;
@ -111,12 +113,13 @@ public class DefaultAuthenticationEventPublisherTests {
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class)); verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
} }
@Test(expected = RuntimeException.class) @Test
public void missingEventClassExceptionCausesException() { public void missingEventClassExceptionCausesException() {
this.publisher = new DefaultAuthenticationEventPublisher(); this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties(); Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), "NoSuchClass"); p.put(MockAuthenticationException.class.getName(), "NoSuchClass");
this.publisher.setAdditionalExceptionMappings(p); assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(p));
} }
@Test @Test
@ -132,27 +135,27 @@ public class DefaultAuthenticationEventPublisherTests {
verifyZeroInteractions(appPublisher); verifyZeroInteractions(appPublisher);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void emptyMapCausesException() { public void emptyMapCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>(); Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
this.publisher = new DefaultAuthenticationEventPublisher(); this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setAdditionalExceptionMappings(mappings); assertThatIllegalArgumentException().isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(mappings));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void missingExceptionClassCausesException() { public void missingExceptionClassCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>(); Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(null, AuthenticationFailureLockedEvent.class); mappings.put(null, AuthenticationFailureLockedEvent.class);
this.publisher = new DefaultAuthenticationEventPublisher(); this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setAdditionalExceptionMappings(mappings); assertThatIllegalArgumentException().isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(mappings));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void missingEventClassAsMapValueCausesException() { public void missingEventClassAsMapValueCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>(); Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(LockedException.class, null); mappings.put(LockedException.class, null);
this.publisher = new DefaultAuthenticationEventPublisher(); this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setAdditionalExceptionMappings(mappings); assertThatIllegalArgumentException().isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(mappings));
} }
@Test @Test
@ -168,10 +171,11 @@ public class DefaultAuthenticationEventPublisherTests {
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class)); verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void defaultAuthenticationFailureEventClassSetNullThen() { public void defaultAuthenticationFailureEventClassSetNullThen() {
this.publisher = new DefaultAuthenticationEventPublisher(); this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setDefaultAuthenticationFailureEvent(null); assertThatIllegalArgumentException()
.isThrownBy(() -> this.publisher.setDefaultAuthenticationFailureEvent(null));
} }
@Test @Test
@ -185,11 +189,11 @@ public class DefaultAuthenticationEventPublisherTests {
verify(appPublisher).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class)); verify(appPublisher).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
} }
@Test(expected = RuntimeException.class) @Test
public void defaultAuthenticationFailureEventMissingAppropriateConstructorThen() { public void defaultAuthenticationFailureEventMissingAppropriateConstructorThen() {
this.publisher = new DefaultAuthenticationEventPublisher(); this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.publisher
.setDefaultAuthenticationFailureEvent(AuthenticationFailureEventWithoutAppropriateConstructor.class); .setDefaultAuthenticationFailureEvent(AuthenticationFailureEventWithoutAppropriateConstructor.class));
} }
private static final class AuthenticationFailureEventWithoutAppropriateConstructor private static final class AuthenticationFailureEventWithoutAppropriateConstructor

View File

@ -29,6 +29,7 @@ import org.springframework.security.core.AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -45,7 +46,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
*/ */
public class ProviderManagerTests { public class ProviderManagerTests {
@Test(expected = ProviderNotFoundException.class) @Test
public void authenticationFailsWithUnsupportedToken() { public void authenticationFailsWithUnsupportedToken() {
Authentication token = new AbstractAuthenticationToken(null) { Authentication token = new AbstractAuthenticationToken(null) {
@Override @Override
@ -60,7 +61,7 @@ public class ProviderManagerTests {
}; };
ProviderManager mgr = makeProviderManager(); ProviderManager mgr = makeProviderManager();
mgr.setMessageSource(mock(MessageSource.class)); mgr.setMessageSource(mock(MessageSource.class));
mgr.authenticate(token); assertThatExceptionOfType(ProviderNotFoundException.class).isThrownBy(() -> mgr.authenticate(token));
} }
@Test @Test
@ -98,19 +99,20 @@ public class ProviderManagerTests {
verify(publisher).publishAuthenticationSuccess(result); verify(publisher).publishAuthenticationSuccess(result);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testStartupFailsIfProvidersNotSetAsList() { public void testStartupFailsIfProvidersNotSetAsList() {
new ProviderManager((List<AuthenticationProvider>) null); assertThatIllegalArgumentException().isThrownBy(() -> new ProviderManager((List<AuthenticationProvider>) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testStartupFailsIfProvidersNotSetAsVarargs() { public void testStartupFailsIfProvidersNotSetAsVarargs() {
new ProviderManager((AuthenticationProvider) null); assertThatIllegalArgumentException().isThrownBy(() -> new ProviderManager((AuthenticationProvider) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testStartupFailsIfProvidersContainNullElement() { public void testStartupFailsIfProvidersContainNullElement() {
new ProviderManager(Arrays.asList(mock(AuthenticationProvider.class), null)); assertThatIllegalArgumentException()
.isThrownBy(() -> new ProviderManager(Arrays.asList(mock(AuthenticationProvider.class), null)));
} }
// gh-8689 // gh-8689

View File

@ -27,6 +27,7 @@ import reactor.test.StepVerifier;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -50,14 +51,14 @@ public class ReactiveAuthenticationManagerAdapterTests {
this.manager = new ReactiveAuthenticationManagerAdapter(this.delegate); this.manager = new ReactiveAuthenticationManagerAdapter(this.delegate);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullAuthenticationManager() { public void constructorNullAuthenticationManager() {
new ReactiveAuthenticationManagerAdapter(null); assertThatIllegalArgumentException().isThrownBy(() -> new ReactiveAuthenticationManagerAdapter(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void setSchedulerNull() { public void setSchedulerNull() {
this.manager.setScheduler(null); assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setScheduler(null));
} }
@Test @Test

View File

@ -33,6 +33,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -62,10 +63,10 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
this.password = "pass"; this.password = "pass";
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullUserDetailsService() { public void constructorNullUserDetailsService() {
ReactiveUserDetailsService userDetailsService = null; assertThatIllegalArgumentException()
new UserDetailsRepositoryReactiveAuthenticationManager(userDetailsService); .isThrownBy(() -> new UserDetailsRepositoryReactiveAuthenticationManager(null));
} }
@Test @Test

View File

@ -165,7 +165,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
verifyZeroInteractions(this.postAuthenticationChecks); verifyZeroInteractions(this.postAuthenticationChecks);
} }
@Test(expected = AccountExpiredException.class) @Test
public void authenticateWhenAccountExpiredThenException() { public void authenticateWhenAccountExpiredThenException() {
this.manager.setPasswordEncoder(this.encoder); this.manager.setPasswordEncoder(this.encoder);
// @formatter:off // @formatter:off
@ -178,10 +178,11 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(expiredUser)); given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(expiredUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(expiredUser, UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(expiredUser,
expiredUser.getPassword()); expiredUser.getPassword());
this.manager.authenticate(token).block(); assertThatExceptionOfType(AccountExpiredException.class)
.isThrownBy(() -> this.manager.authenticate(token).block());
} }
@Test(expected = LockedException.class) @Test
public void authenticateWhenAccountLockedThenException() { public void authenticateWhenAccountLockedThenException() {
this.manager.setPasswordEncoder(this.encoder); this.manager.setPasswordEncoder(this.encoder);
// @formatter:off // @formatter:off
@ -194,10 +195,10 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(lockedUser)); given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(lockedUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(lockedUser, UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(lockedUser,
lockedUser.getPassword()); lockedUser.getPassword());
this.manager.authenticate(token).block(); assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager.authenticate(token).block());
} }
@Test(expected = DisabledException.class) @Test
public void authenticateWhenAccountDisabledThenException() { public void authenticateWhenAccountDisabledThenException() {
this.manager.setPasswordEncoder(this.encoder); this.manager.setPasswordEncoder(this.encoder);
// @formatter:off // @formatter:off
@ -210,7 +211,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(disabledUser)); given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(disabledUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(disabledUser, UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(disabledUser,
disabledUser.getPassword()); disabledUser.getPassword());
this.manager.authenticate(token).block(); assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> this.manager.authenticate(token).block());
} }
} }

View File

@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
@ -63,10 +64,11 @@ public class UsernamePasswordAuthenticationTokenTests {
assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_TWO"); assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_TWO");
} }
@Test(expected = NoSuchMethodException.class) @Test
public void testNoArgConstructorDoesntExist() throws Exception { public void testNoArgConstructorDoesntExist() throws Exception {
Class<?> clazz = UsernamePasswordAuthenticationToken.class; Class<?> clazz = UsernamePasswordAuthenticationToken.class;
clazz.getDeclaredConstructor((Class[]) null); assertThatExceptionOfType(NoSuchMethodException.class)
.isThrownBy(() -> clazz.getDeclaredConstructor((Class[]) null));
} }
} }

View File

@ -101,19 +101,21 @@ public class AnonymousAuthenticationTokenTests {
assertThat(!token.isAuthenticated()).isTrue(); assertThat(!token.isAuthenticated()).isTrue();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorWhenNullAuthoritiesThenThrowIllegalArgumentException() { public void constructorWhenNullAuthoritiesThenThrowIllegalArgumentException() {
new AnonymousAuthenticationToken("key", "principal", null); assertThatIllegalArgumentException()
.isThrownBy(() -> new AnonymousAuthenticationToken("key", "principal", null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorWhenEmptyAuthoritiesThenThrowIllegalArgumentException() { public void constructorWhenEmptyAuthoritiesThenThrowIllegalArgumentException() {
new AnonymousAuthenticationToken("key", "principal", Collections.<GrantedAuthority>emptyList()); assertThatIllegalArgumentException().isThrownBy(
() -> new AnonymousAuthenticationToken("key", "principal", Collections.<GrantedAuthority>emptyList()));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorWhenPrincipalIsEmptyStringThenThrowIllegalArgumentException() { public void constructorWhenPrincipalIsEmptyStringThenThrowIllegalArgumentException() {
new AnonymousAuthenticationToken("key", "", ROLES_12); assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken("key", "", ROLES_12));
} }
} }

View File

@ -45,6 +45,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isA;
@ -82,16 +83,16 @@ public class DefaultJaasAuthenticationProviderTests {
ReflectionTestUtils.setField(this.provider, "log", this.log); ReflectionTestUtils.setField(this.provider, "log", this.log);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void afterPropertiesSetNullConfiguration() throws Exception { public void afterPropertiesSetNullConfiguration() throws Exception {
this.provider.setConfiguration(null); this.provider.setConfiguration(null);
this.provider.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(this.provider::afterPropertiesSet);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void afterPropertiesSetNullAuthorityGranters() throws Exception { public void afterPropertiesSetNullAuthorityGranters() throws Exception {
this.provider.setAuthorityGranters(null); this.provider.setAuthorityGranters(null);
this.provider.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(this.provider::afterPropertiesSet);
} }
@Test @Test

View File

@ -29,6 +29,7 @@ import org.junit.Test;
import org.springframework.security.authentication.jaas.TestLoginModule; import org.springframework.security.authentication.jaas.TestLoginModule;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link InMemoryConfiguration}. * Tests {@link InMemoryConfiguration}.
@ -55,9 +56,10 @@ public class InMemoryConfigurationTests {
assertThat(new InMemoryConfiguration((AppConfigurationEntry[]) null).getAppConfigurationEntry("name")).isNull(); assertThat(new InMemoryConfiguration((AppConfigurationEntry[]) null).getAppConfigurationEntry("name")).isNull();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullMapped() { public void constructorNullMapped() {
new InMemoryConfiguration((Map<String, AppConfigurationEntry[]>) null); assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryConfiguration((Map<String, AppConfigurationEntry[]>) null));
} }
@Test @Test
@ -72,9 +74,9 @@ public class InMemoryConfigurationTests {
.getAppConfigurationEntry("name")).isNull(); .getAppConfigurationEntry("name")).isNull();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullMapNullDefault() { public void constructorNullMapNullDefault() {
new InMemoryConfiguration(null, null); assertThatIllegalArgumentException().isThrownBy(() -> new InMemoryConfiguration(null, null));
} }
@Test @Test

View File

@ -23,6 +23,7 @@ import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -35,13 +36,14 @@ import static org.mockito.Mockito.mock;
*/ */
public class RemoteAuthenticationManagerImplTests { public class RemoteAuthenticationManagerImplTests {
@Test(expected = RemoteAuthenticationException.class) @Test
public void testFailedAuthenticationReturnsRemoteAuthenticationException() { public void testFailedAuthenticationReturnsRemoteAuthenticationException() {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl(); RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
AuthenticationManager am = mock(AuthenticationManager.class); AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
manager.setAuthenticationManager(am); manager.setAuthenticationManager(am);
manager.attemptAuthentication("rod", "password"); assertThatExceptionOfType(RemoteAuthenticationException.class)
.isThrownBy(() -> manager.attemptAuthentication("rod", "password"));
} }
@Test @Test

View File

@ -29,6 +29,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
/** /**
@ -120,42 +121,40 @@ public class AuthorityReactiveAuthorizationManagerTests {
assertThat(granted).isFalse(); assertThat(granted).isFalse();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void hasRoleWhenNullThenException() { public void hasRoleWhenNullThenException() {
String role = null; assertThatIllegalArgumentException()
AuthorityReactiveAuthorizationManager.hasRole(role); .isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasRole((String) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void hasAuthorityWhenNullThenException() { public void hasAuthorityWhenNullThenException() {
String authority = null; assertThatIllegalArgumentException()
AuthorityReactiveAuthorizationManager.hasAuthority(authority); .isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAuthority((String) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void hasAnyRoleWhenNullThenException() { public void hasAnyRoleWhenNullThenException() {
String role = null; assertThatIllegalArgumentException()
AuthorityReactiveAuthorizationManager.hasAnyRole(role); .isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyRole((String) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void hasAnyAuthorityWhenNullThenException() { public void hasAnyAuthorityWhenNullThenException() {
String authority = null; assertThatIllegalArgumentException()
AuthorityReactiveAuthorizationManager.hasAnyAuthority(authority); .isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyAuthority((String) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void hasAnyRoleWhenOneIsNullThenException() { public void hasAnyRoleWhenOneIsNullThenException() {
String role1 = "ROLE_ADMIN"; assertThatIllegalArgumentException()
String role2 = null; .isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyRole("ROLE_ADMIN", (String) null));
AuthorityReactiveAuthorizationManager.hasAnyRole(role1, role2);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void hasAnyAuthorityWhenOneIsNullThenException() { public void hasAnyAuthorityWhenOneIsNullThenException() {
String authority1 = "ADMIN"; assertThatIllegalArgumentException()
String authority2 = null; .isThrownBy(() -> AuthorityReactiveAuthorizationManager.hasAnyAuthority("ADMIN", (String) null));
AuthorityReactiveAuthorizationManager.hasAnyAuthority(authority1, authority2);
} }
} }

View File

@ -27,6 +27,7 @@ import org.junit.Test;
import org.mockito.Mock; import org.mockito.Mock;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -57,9 +58,9 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
} }
@Override @Override
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullDelegate() { public void constructorNullDelegate() {
new DelegatingSecurityContextExecutorService(null); assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextExecutorService(null));
} }
@Test @Test

View File

@ -22,6 +22,7 @@ import java.util.concurrent.ScheduledExecutorService;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mock; import org.mockito.Mock;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
/** /**
@ -42,9 +43,9 @@ public abstract class AbstractDelegatingSecurityContextExecutorTests
private DelegatingSecurityContextExecutor executor; private DelegatingSecurityContextExecutor executor;
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullDelegate() { public void constructorNullDelegate() {
new DelegatingSecurityContextExecutor(null); assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextExecutor(null));
} }
@Test @Test

View File

@ -34,6 +34,7 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -79,24 +80,26 @@ public class DelegatingSecurityContextCallableTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullDelegate() { public void constructorNullDelegate() {
new DelegatingSecurityContextCallable<>(null); assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextCallable<>(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullDelegateNonNullSecurityContext() { public void constructorNullDelegateNonNullSecurityContext() {
new DelegatingSecurityContextCallable<>(null, this.securityContext); assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingSecurityContextCallable<>(null, this.securityContext));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullDelegateAndSecurityContext() { public void constructorNullDelegateAndSecurityContext() {
new DelegatingSecurityContextCallable<>(null, null); assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextCallable<>(null, null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullSecurityContext() { public void constructorNullSecurityContext() {
new DelegatingSecurityContextCallable<>(this.delegate, null); assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingSecurityContextCallable<>(this.delegate, null));
} }
@Test @Test
@ -109,8 +112,8 @@ public class DelegatingSecurityContextCallableTests {
public void callDefaultSecurityContext() throws Exception { public void callDefaultSecurityContext() throws Exception {
SecurityContextHolder.setContext(this.securityContext); SecurityContextHolder.setContext(this.securityContext);
this.callable = new DelegatingSecurityContextCallable<>(this.delegate); this.callable = new DelegatingSecurityContextCallable<>(this.delegate);
SecurityContextHolder.clearContext(); // ensure callable is what sets up the // ensure callable is what sets up the SecurityContextHolder
// SecurityContextHolder SecurityContextHolder.clearContext();
assertWrapped(this.callable); assertWrapped(this.callable);
} }
@ -123,22 +126,23 @@ public class DelegatingSecurityContextCallableTests {
assertWrapped(this.callable.call()); assertWrapped(this.callable.call());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void createNullDelegate() { public void createNullDelegate() {
DelegatingSecurityContextCallable.create(null, this.securityContext); assertThatIllegalArgumentException()
.isThrownBy(() -> DelegatingSecurityContextCallable.create(null, this.securityContext));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void createNullDelegateAndSecurityContext() { public void createNullDelegateAndSecurityContext() {
DelegatingSecurityContextRunnable.create(null, null); assertThatIllegalArgumentException().isThrownBy(() -> DelegatingSecurityContextRunnable.create(null, null));
} }
@Test @Test
public void createNullSecurityContext() throws Exception { public void createNullSecurityContext() throws Exception {
SecurityContextHolder.setContext(this.securityContext); SecurityContextHolder.setContext(this.securityContext);
this.callable = DelegatingSecurityContextCallable.create(this.delegate, null); this.callable = DelegatingSecurityContextCallable.create(this.delegate, null);
SecurityContextHolder.clearContext(); // ensure callable is what sets up the // ensure callable is what sets up the SecurityContextHolder
// SecurityContextHolder SecurityContextHolder.clearContext();
assertWrapped(this.callable); assertWrapped(this.callable);
} }

View File

@ -34,6 +34,7 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.willAnswer; import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -74,24 +75,26 @@ public class DelegatingSecurityContextRunnableTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullDelegate() { public void constructorNullDelegate() {
new DelegatingSecurityContextRunnable(null); assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextRunnable(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullDelegateNonNullSecurityContext() { public void constructorNullDelegateNonNullSecurityContext() {
new DelegatingSecurityContextRunnable(null, this.securityContext); assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingSecurityContextRunnable(null, this.securityContext));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullDelegateAndSecurityContext() { public void constructorNullDelegateAndSecurityContext() {
new DelegatingSecurityContextRunnable(null, null); assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextRunnable(null, null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullSecurityContext() { public void constructorNullSecurityContext() {
new DelegatingSecurityContextRunnable(this.delegate, null); assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingSecurityContextRunnable(this.delegate, null));
} }
@Test @Test
@ -119,14 +122,15 @@ public class DelegatingSecurityContextRunnableTests {
assertWrapped(this.runnable); assertWrapped(this.runnable);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void createNullDelegate() { public void createNullDelegate() {
DelegatingSecurityContextRunnable.create(null, this.securityContext); assertThatIllegalArgumentException()
.isThrownBy(() -> DelegatingSecurityContextRunnable.create(null, this.securityContext));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void createNullDelegateAndSecurityContext() { public void createNullDelegateAndSecurityContext() {
DelegatingSecurityContextRunnable.create(null, null); assertThatIllegalArgumentException().isThrownBy(() -> DelegatingSecurityContextRunnable.create(null, null));
} }
@Test @Test

View File

@ -25,6 +25,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener; import org.springframework.context.event.SmartApplicationListener;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
@ -75,9 +76,9 @@ public class DelegatingApplicationListenerTests {
verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class)); verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void addNull() { public void addNull() {
this.listener.addListener(null); assertThatIllegalArgumentException().isThrownBy(() -> this.listener.addListener(null));
} }
} }

View File

@ -28,6 +28,7 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Ruud Senden * @author Ruud Senden
@ -35,44 +36,41 @@ import static org.assertj.core.api.Assertions.assertThat;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public class MapBasedAttributes2GrantedAuthoritiesMapperTests { public class MapBasedAttributes2GrantedAuthoritiesMapperTests {
@Test(expected = IllegalArgumentException.class) @Test
public void testAfterPropertiesSetNoMap() throws Exception { public void testAfterPropertiesSetNoMap() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(mapper::afterPropertiesSet);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testAfterPropertiesSetEmptyMap() throws Exception { public void testAfterPropertiesSetEmptyMap() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
mapper.setAttributes2grantedAuthoritiesMap(new HashMap()); assertThatIllegalArgumentException()
mapper.afterPropertiesSet(); .isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(new HashMap()));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testAfterPropertiesSetInvalidKeyTypeMap() throws Exception { public void testAfterPropertiesSetInvalidKeyTypeMap() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap(); HashMap m = new HashMap();
m.put(new Object(), "ga1"); m.put(new Object(), "ga1");
mapper.setAttributes2grantedAuthoritiesMap(m); assertThatIllegalArgumentException().isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(m));
mapper.afterPropertiesSet();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testAfterPropertiesSetInvalidValueTypeMap1() throws Exception { public void testAfterPropertiesSetInvalidValueTypeMap1() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap(); HashMap m = new HashMap();
m.put("role1", new Object()); m.put("role1", new Object());
mapper.setAttributes2grantedAuthoritiesMap(m); assertThatIllegalArgumentException().isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(m));
mapper.afterPropertiesSet();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testAfterPropertiesSetInvalidValueTypeMap2() throws Exception { public void testAfterPropertiesSetInvalidValueTypeMap2() throws Exception {
MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper(); MapBasedAttributes2GrantedAuthoritiesMapper mapper = new MapBasedAttributes2GrantedAuthoritiesMapper();
HashMap m = new HashMap(); HashMap m = new HashMap();
m.put("role1", new Object[] { new String[] { "ga1", "ga2" }, new Object() }); m.put("role1", new Object[] { new String[] { "ga1", "ga2" }, new Object() });
mapper.setAttributes2grantedAuthoritiesMap(m); assertThatIllegalArgumentException().isThrownBy(() -> mapper.setAttributes2grantedAuthoritiesMap(m));
mapper.afterPropertiesSet();
} }
@Test @Test

View File

@ -25,18 +25,19 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Luke Taylor * @author Luke Taylor
*/ */
public class SimpleAuthoritiesMapperTests { public class SimpleAuthoritiesMapperTests {
@Test(expected = IllegalArgumentException.class) @Test
public void rejectsInvalidCaseConversionFlags() throws Exception { public void rejectsInvalidCaseConversionFlags() {
SimpleAuthorityMapper mapper = new SimpleAuthorityMapper(); SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
mapper.setConvertToLowerCase(true); mapper.setConvertToLowerCase(true);
mapper.setConvertToUpperCase(true); mapper.setConvertToUpperCase(true);
mapper.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(mapper::afterPropertiesSet);
} }
@Test @Test

View File

@ -21,6 +21,7 @@ import java.util.Date;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link DefaultToken}. * Tests {@link DefaultToken}.
@ -40,11 +41,11 @@ public class DefaultTokenTests {
assertThat(t2).isEqualTo(t1); assertThat(t2).isEqualTo(t1);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testRejectsNullExtendedInformation() { public void testRejectsNullExtendedInformation() {
String key = "key"; String key = "key";
long created = new Date().getTime(); long created = new Date().getTime();
new DefaultToken(key, created, null); assertThatIllegalArgumentException().isThrownBy(() -> new DefaultToken(key, created, null));
} }
@Test @Test

View File

@ -22,12 +22,12 @@ import java.util.Date;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link KeyBasedPersistenceTokenService}. * Tests {@link KeyBasedPersistenceTokenService}.
* *
* @author Ben Alex * @author Ben Alex
*
*/ */
public class KeyBasedPersistenceTokenServiceTests { public class KeyBasedPersistenceTokenServiceTests {
@ -80,20 +80,22 @@ public class KeyBasedPersistenceTokenServiceTests {
assertThat(result).isEqualTo(token); assertThat(result).isEqualTo(token);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testOperationWithMissingKey() { public void testOperationWithMissingKey() {
KeyBasedPersistenceTokenService service = getService(); KeyBasedPersistenceTokenService service = getService();
Token token = new DefaultToken("", new Date().getTime(), ""); assertThatIllegalArgumentException().isThrownBy(() -> {
service.verifyToken(token.getKey()); Token token = new DefaultToken("", new Date().getTime(), "");
service.verifyToken(token.getKey());
});
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testOperationWithTamperedKey() { public void testOperationWithTamperedKey() {
KeyBasedPersistenceTokenService service = getService(); KeyBasedPersistenceTokenService service = getService();
Token goodToken = service.allocateToken(""); Token goodToken = service.allocateToken("");
String fake = goodToken.getKey().toUpperCase(); String fake = goodToken.getKey().toUpperCase();
Token token = new DefaultToken(fake, new Date().getTime(), ""); Token token = new DefaultToken(fake, new Date().getTime(), "");
service.verifyToken(token.getKey()); assertThatIllegalArgumentException().isThrownBy(() -> service.verifyToken(token.getKey()));
} }
} }

View File

@ -24,6 +24,7 @@ import org.junit.Test;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class MapReactiveUserDetailsServiceTests { public class MapReactiveUserDetailsServiceTests {
@ -35,16 +36,16 @@ public class MapReactiveUserDetailsServiceTests {
// @formatter:on // @formatter:on
private MapReactiveUserDetailsService users = new MapReactiveUserDetailsService(Arrays.asList(USER_DETAILS)); private MapReactiveUserDetailsService users = new MapReactiveUserDetailsService(Arrays.asList(USER_DETAILS));
@Test(expected = IllegalArgumentException.class) @Test
public void constructorNullUsers() { public void constructorNullUsers() {
Collection<UserDetails> users = null; assertThatIllegalArgumentException()
new MapReactiveUserDetailsService(users); .isThrownBy(() -> new MapReactiveUserDetailsService((Collection<UserDetails>) null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorEmptyUsers() { public void constructorEmptyUsers() {
Collection<UserDetails> users = Collections.emptyList(); assertThatIllegalArgumentException()
new MapReactiveUserDetailsService(users); .isThrownBy(() -> new MapReactiveUserDetailsService(Collections.emptyList()));
} }
@Test @Test

View File

@ -27,7 +27,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link EhCacheBasedUserCache}. * Tests {@link EhCacheBasedUserCache}.
@ -77,11 +77,10 @@ public class EhCacheBasedUserCacheTests {
assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull(); assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void startupDetectsMissingCache() throws Exception { public void startupDetectsMissingCache() throws Exception {
EhCacheBasedUserCache cache = new EhCacheBasedUserCache(); EhCacheBasedUserCache cache = new EhCacheBasedUserCache();
cache.afterPropertiesSet(); assertThatIllegalArgumentException().isThrownBy(cache::afterPropertiesSet);
fail("Should have thrown IllegalArgumentException");
Ehcache myCache = getCache(); Ehcache myCache = getCache();
cache.setCache(myCache); cache.setCache(myCache);
assertThat(cache.getCache()).isEqualTo(myCache); assertThat(cache.getCache()).isEqualTo(myCache);

View File

@ -27,6 +27,7 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests * Tests
@ -75,9 +76,9 @@ public class SpringCacheBasedUserCacheTests {
assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull(); assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void startupDetectsMissingCache() throws Exception { public void startupDetectsMissingCache() throws Exception {
new SpringCacheBasedUserCache(null); assertThatIllegalArgumentException().isThrownBy(() -> new SpringCacheBasedUserCache(null));
} }
} }

View File

@ -156,10 +156,10 @@ public class JdbcDaoImplTests {
}); });
} }
@Test(expected = IllegalArgumentException.class) @Test
public void setMessageSourceWhenNullThenThrowsException() { public void setMessageSourceWhenNullThenThrowsException() {
JdbcDaoImpl dao = new JdbcDaoImpl(); JdbcDaoImpl dao = new JdbcDaoImpl();
dao.setMessageSource(null); assertThatIllegalArgumentException().isThrownBy(() -> dao.setMessageSource(null));
} }
@Test @Test

View File

@ -29,6 +29,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Jitendra Singh * @author Jitendra Singh
@ -64,12 +65,13 @@ public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
assertThat(token.getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER")); assertThat(token.getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
} }
@Test(expected = JsonMappingException.class) @Test
public void deserializeAnonymousAuthenticationTokenWithoutAuthoritiesTest() throws IOException { public void deserializeAnonymousAuthenticationTokenWithoutAuthoritiesTest() throws IOException {
String jsonString = "{\"@class\": \"org.springframework.security.authentication.AnonymousAuthenticationToken\", \"details\": null," String jsonString = "{\"@class\": \"org.springframework.security.authentication.AnonymousAuthenticationToken\", \"details\": null,"
+ "\"principal\": \"user\", \"authenticated\": true, \"keyHash\": " + HASH_KEY.hashCode() + "," + "\"principal\": \"user\", \"authenticated\": true, \"keyHash\": " + HASH_KEY.hashCode() + ","
+ "\"authorities\": [\"java.util.ArrayList\", []]}"; + "\"authorities\": [\"java.util.ArrayList\", []]}";
this.mapper.readValue(jsonString, AnonymousAuthenticationToken.class); assertThatExceptionOfType(JsonMappingException.class)
.isThrownBy(() -> this.mapper.readValue(jsonString, AnonymousAuthenticationToken.class));
} }
@Test @Test

View File

@ -30,6 +30,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Jitendra Singh * @author Jitendra Singh
@ -48,6 +49,7 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON + "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
+ "}"; + "}";
// @formatter:on // @formatter:on
// @formatter:off // @formatter:off
private static final String REMEMBERME_AUTH_STRINGPRINCIPAL_JSON = "{" private static final String REMEMBERME_AUTH_STRINGPRINCIPAL_JSON = "{"
+ "\"@class\": \"org.springframework.security.authentication.RememberMeAuthenticationToken\"," + "\"@class\": \"org.springframework.security.authentication.RememberMeAuthenticationToken\","
@ -58,14 +60,17 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
+ "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON + "\"authorities\": " + SimpleGrantedAuthorityMixinTests.AUTHORITIES_ARRAYLIST_JSON
+ "}"; + "}";
// @formatter:on // @formatter:on
@Test(expected = IllegalArgumentException.class)
@Test
public void testWithNullPrincipal() { public void testWithNullPrincipal() {
new RememberMeAuthenticationToken("key", null, Collections.<GrantedAuthority>emptyList()); assertThatIllegalArgumentException().isThrownBy(
() -> new RememberMeAuthenticationToken("key", null, Collections.<GrantedAuthority>emptyList()));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testWithNullKey() { public void testWithNullKey() {
new RememberMeAuthenticationToken(null, "principal", Collections.<GrantedAuthority>emptyList()); assertThatIllegalArgumentException().isThrownBy(
() -> new RememberMeAuthenticationToken(null, "principal", Collections.<GrantedAuthority>emptyList()));
} }
@Test @Test

View File

@ -27,6 +27,7 @@ import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Jitendra Singh * @author Jitendra Singh
@ -56,10 +57,11 @@ public class SimpleGrantedAuthorityMixinTests extends AbstractMixinTests {
assertThat(authority.getAuthority()).isNotNull().isEqualTo("ROLE_USER"); assertThat(authority.getAuthority()).isNotNull().isEqualTo("ROLE_USER");
} }
@Test(expected = JsonMappingException.class) @Test
public void deserializeGrantedAuthorityWithoutRoleTest() throws IOException { public void deserializeGrantedAuthorityWithoutRoleTest() throws IOException {
String json = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"}"; String json = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"}";
this.mapper.readValue(json, SimpleGrantedAuthority.class); assertThatExceptionOfType(JsonMappingException.class)
.isThrownBy(() -> this.mapper.readValue(json, SimpleGrantedAuthority.class));
} }
} }

View File

@ -32,6 +32,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Jitendra Singh * @author Jitendra Singh
@ -67,11 +68,12 @@ public class UserDeserializerTests extends AbstractMixinTests {
JSONAssert.assertEquals(userWithNoAuthoritiesJson(), userJson, true); JSONAssert.assertEquals(userWithNoAuthoritiesJson(), userJson, true);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void deserializeUserWithNullPasswordEmptyAuthorityTest() throws IOException { public void deserializeUserWithNullPasswordEmptyAuthorityTest() throws IOException {
String userJsonWithoutPasswordString = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON, String userJsonWithoutPasswordString = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON,
"[]"); "[]");
this.mapper.readValue(userJsonWithoutPasswordString, User.class); assertThatIllegalArgumentException()
.isThrownBy(() -> this.mapper.readValue(userJsonWithoutPasswordString, User.class));
} }
@Test @Test
@ -85,11 +87,11 @@ public class UserDeserializerTests extends AbstractMixinTests {
assertThat(user.isEnabled()).isEqualTo(true); assertThat(user.isEnabled()).isEqualTo(true);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void deserializeUserWithNoClassIdInAuthoritiesTest() throws Exception { public void deserializeUserWithNoClassIdInAuthoritiesTest() throws Exception {
String userJson = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON, String userJson = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON,
"[{\"authority\": \"ROLE_USER\"}]"); "[{\"authority\": \"ROLE_USER\"}]");
this.mapper.readValue(userJson, User.class); assertThatIllegalArgumentException().isThrownBy(() -> this.mapper.readValue(userJson, User.class));
} }
@Test @Test

View File

@ -189,9 +189,10 @@ public class JdbcUserDetailsManagerTests {
assertThat(this.cache.getUserMap().containsKey("joe")).isTrue(); assertThat(this.cache.getUserMap().containsKey("joe")).isTrue();
} }
@Test(expected = AccessDeniedException.class) @Test
public void changePasswordFailsForUnauthenticatedUser() { public void changePasswordFailsForUnauthenticatedUser() {
this.manager.changePassword("password", "newPassword"); assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.manager.changePassword("password", "newPassword"));
} }
@Test @Test

View File

@ -29,6 +29,7 @@ import org.mockito.MockitoAnnotations;
import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger; import org.springframework.scheduling.Trigger;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isA;
@ -65,9 +66,9 @@ public class DelegatingSecurityContextTaskSchedulerTests {
this.delegatingSecurityContextTaskScheduler = null; this.delegatingSecurityContextTaskScheduler = null;
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testSchedulerIsNotNull() { public void testSchedulerIsNotNull() {
this.delegatingSecurityContextTaskScheduler = new DelegatingSecurityContextTaskScheduler(null); assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingSecurityContextTaskScheduler(null));
} }
@Test @Test

View File

@ -25,6 +25,7 @@ import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.security.access.annotation.BusinessServiceImpl; import org.springframework.security.access.annotation.BusinessServiceImpl;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Luke Taylor * @author Luke Taylor
@ -44,9 +45,10 @@ public class MethodInvocationUtilsTests {
assertThat(mi).isNotNull(); assertThat(mi).isNotNull();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void exceptionIsRaisedIfArgInfoOmittedAndMethodNameIsNotUnique() { public void exceptionIsRaisedIfArgInfoOmittedAndMethodNameIsNotUnique() {
MethodInvocationUtils.createFromClass(BusinessServiceImpl.class, "methodReturningAList"); assertThatIllegalArgumentException().isThrownBy(
() -> MethodInvocationUtils.createFromClass(BusinessServiceImpl.class, "methodReturningAList"));
} }
@Test @Test

View File

@ -22,6 +22,7 @@ import org.bouncycastle.crypto.params.Argon2Parameters;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Simeon Macke * @author Simeon Macke
@ -66,69 +67,70 @@ public class Argon2EncodingUtilsTests {
this.testDataEntry2.decoded.getParameters())).isEqualTo(this.testDataEntry2.encoded); this.testDataEntry2.decoded.getParameters())).isEqualTo(this.testDataEntry2.encoded);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void encodeWhenNonexistingAlgorithmThenThrowException() { public void encodeWhenNonexistingAlgorithmThenThrowException() {
Argon2EncodingUtils.encode(new byte[] { 0, 1, 2, 3 }, (new Argon2Parameters.Builder(3)).withVersion(19) assertThatIllegalArgumentException().isThrownBy(
.withMemoryAsKB(333).withIterations(5).withParallelism(2).build()); () -> Argon2EncodingUtils.encode(new byte[] { 0, 1, 2, 3 }, (new Argon2Parameters.Builder(3))
.withVersion(19).withMemoryAsKB(333).withIterations(5).withParallelism(2).build()));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeWhenNotAnArgon2HashThenThrowException() { public void decodeWhenNotAnArgon2HashThenThrowException() {
Argon2EncodingUtils.decode("notahash"); assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode("notahash"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeWhenNonexistingAlgorithmThenThrowException() { public void decodeWhenNonexistingAlgorithmThenThrowException() {
Argon2EncodingUtils.decode( assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode(
"$argon2x$v=19$m=1024,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"); "$argon2x$v=19$m=1024,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeWhenIllegalVersionParameterThenThrowException() { public void decodeWhenIllegalVersionParameterThenThrowException() {
Argon2EncodingUtils.decode( assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode(
"$argon2i$v=x$m=1024,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"); "$argon2i$v=x$m=1024,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeWhenIllegalMemoryParameterThenThrowException() { public void decodeWhenIllegalMemoryParameterThenThrowException() {
Argon2EncodingUtils assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode(
.decode("$argon2i$v=19$m=x,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"); "$argon2i$v=19$m=x,t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeWhenIllegalIterationsParameterThenThrowException() { public void decodeWhenIllegalIterationsParameterThenThrowException() {
Argon2EncodingUtils.decode( assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode(
"$argon2i$v=19$m=1024,t=x,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"); "$argon2i$v=19$m=1024,t=x,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeWhenIllegalParallelityParameterThenThrowException() { public void decodeWhenIllegalParallelityParameterThenThrowException() {
Argon2EncodingUtils.decode( assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils.decode(
"$argon2i$v=19$m=1024,t=3,p=x$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"); "$argon2i$v=19$m=1024,t=3,p=x$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeWhenMissingVersionParameterThenThrowException() { public void decodeWhenMissingVersionParameterThenThrowException() {
Argon2EncodingUtils assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils
.decode("$argon2i$m=1024,t=3,p=x$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"); .decode("$argon2i$m=1024,t=3,p=x$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeWhenMissingMemoryParameterThenThrowException() { public void decodeWhenMissingMemoryParameterThenThrowException() {
Argon2EncodingUtils assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils
.decode("$argon2i$v=19$t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"); .decode("$argon2i$v=19$t=3,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeWhenMissingIterationsParameterThenThrowException() { public void decodeWhenMissingIterationsParameterThenThrowException() {
Argon2EncodingUtils assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils
.decode("$argon2i$v=19$m=1024,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"); .decode("$argon2i$v=19$m=1024,p=2$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodeWhenMissingParallelityParameterThenThrowException() { public void decodeWhenMissingParallelityParameterThenThrowException() {
Argon2EncodingUtils assertThatIllegalArgumentException().isThrownBy(() -> Argon2EncodingUtils
.decode("$argon2i$v=19$m=1024,t=3$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"); .decode("$argon2i$v=19$m=1024,t=3$Y1JkRmJDdzIzZ3oyTWx4aw$cGE5Cbd/cx7micVhXVBdH5qTr66JI1iUyuNNVAnErXs"));
} }
private void assertArgon2HashEquals(Argon2EncodingUtils.Argon2Hash expected, private void assertArgon2HashEquals(Argon2EncodingUtils.Argon2Hash expected,

View File

@ -28,6 +28,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.crypto.keygen.BytesKeyGenerator; import org.springframework.security.crypto.keygen.BytesKeyGenerator;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Simeon Macke * @author Simeon Macke
@ -181,9 +182,9 @@ public class Argon2PasswordEncoderTests {
assertThat(this.encoder.upgradeEncoding("")).isFalse(); assertThat(this.encoder.upgradeEncoding("")).isFalse();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void upgradeEncodingWhenEncodedPassIsBogusThenThrowException() { public void upgradeEncodingWhenEncodedPassIsBogusThenThrowException() {
this.encoder.upgradeEncoding("thisIsNoValidHash"); assertThatIllegalArgumentException().isThrownBy(() -> this.encoder.upgradeEncoding("thisIsNoValidHash"));
} }
private void injectPredictableSaltGen() throws Exception { private void injectPredictableSaltGen() throws Exception {

View File

@ -21,6 +21,7 @@ import java.security.SecureRandom;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Dave Syer * @author Dave Syer
@ -129,14 +130,14 @@ public class BCryptPasswordEncoderTests {
assertThat(encoder.matches("password", result)).isTrue(); assertThat(encoder.matches("password", result)).isTrue();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void badLowCustomStrength() { public void badLowCustomStrength() {
new BCryptPasswordEncoder(3); assertThatIllegalArgumentException().isThrownBy(() -> new BCryptPasswordEncoder(3));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void badHighCustomStrength() { public void badHighCustomStrength() {
new BCryptPasswordEncoder(32); assertThatIllegalArgumentException().isThrownBy(() -> new BCryptPasswordEncoder(32));
} }
@Test @Test
@ -189,22 +190,22 @@ public class BCryptPasswordEncoderTests {
* @see <a href= * @see <a href=
* "https://github.com/spring-projects/spring-security/pull/7042#issuecomment-506755496">https://github.com/spring-projects/spring-security/pull/7042#issuecomment-506755496</a> * "https://github.com/spring-projects/spring-security/pull/7042#issuecomment-506755496">https://github.com/spring-projects/spring-security/pull/7042#issuecomment-506755496</a>
*/ */
@Test(expected = IllegalArgumentException.class) @Test
public void upgradeFromNonBCrypt() { public void upgradeFromNonBCrypt() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
encoder.upgradeEncoding("not-a-bcrypt-password"); assertThatIllegalArgumentException().isThrownBy(() -> encoder.upgradeEncoding("not-a-bcrypt-password"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void encodeNullRawPassword() { public void encodeNullRawPassword() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
encoder.encode(null); assertThatIllegalArgumentException().isThrownBy(() -> encoder.encode(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void matchNullRawPassword() { public void matchNullRawPassword() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
encoder.matches(null, "does-not-matter"); assertThatIllegalArgumentException().isThrownBy(() -> encoder.matches(null, "does-not-matter"));
} }
} }

View File

@ -21,6 +21,7 @@ import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* JUnit unit tests for BCrypt routines * JUnit unit tests for BCrypt routines
@ -328,19 +329,21 @@ public class BCryptTests {
assertThat(BCrypt.roundsForLogRounds(31)).isEqualTo(0x80000000L); assertThat(BCrypt.roundsForLogRounds(31)).isEqualTo(0x80000000L);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void emptyByteArrayCannotBeEncoded() { public void emptyByteArrayCannotBeEncoded() {
BCrypt.encode_base64(new byte[0], 0, new StringBuilder()); assertThatIllegalArgumentException()
.isThrownBy(() -> BCrypt.encode_base64(new byte[0], 0, new StringBuilder()));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void moreBytesThanInTheArrayCannotBeEncoded() { public void moreBytesThanInTheArrayCannotBeEncoded() {
BCrypt.encode_base64(new byte[1], 2, new StringBuilder()); assertThatIllegalArgumentException()
.isThrownBy(() -> BCrypt.encode_base64(new byte[1], 2, new StringBuilder()));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void decodingMustRequestMoreThanZeroBytes() { public void decodingMustRequestMoreThanZeroBytes() {
BCrypt.decode_base64("", 0); assertThatIllegalArgumentException().isThrownBy(() -> BCrypt.decode_base64("", 0));
} }
private static String encode_base64(byte d[], int len) throws IllegalArgumentException { private static String encode_base64(byte d[], int len) throws IllegalArgumentException {
@ -394,14 +397,14 @@ public class BCryptTests {
} }
} }
@Test(expected = IllegalArgumentException.class) @Test
public void genSaltFailsWithTooFewRounds() { public void genSaltFailsWithTooFewRounds() {
BCrypt.gensalt(3); assertThatIllegalArgumentException().isThrownBy(() -> BCrypt.gensalt(3));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void genSaltFailsWithTooManyRounds() { public void genSaltFailsWithTooManyRounds() {
BCrypt.gensalt(32); assertThatIllegalArgumentException().isThrownBy(() -> BCrypt.gensalt(32));
} }
@Test @Test
@ -410,24 +413,26 @@ public class BCryptTests {
assertThat(BCrypt.gensalt(31)).startsWith("$2a$31$"); assertThat(BCrypt.gensalt(31)).startsWith("$2a$31$");
} }
@Test(expected = IllegalArgumentException.class) @Test
public void hashpwFailsWhenSaltIsNull() { public void hashpwFailsWhenSaltIsNull() {
BCrypt.hashpw("password", null); assertThatIllegalArgumentException().isThrownBy(() -> BCrypt.hashpw("password", null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void hashpwFailsWhenSaltSpecifiesTooFewRounds() { public void hashpwFailsWhenSaltSpecifiesTooFewRounds() {
BCrypt.hashpw("password", "$2a$03$......................"); assertThatIllegalArgumentException()
.isThrownBy(() -> BCrypt.hashpw("password", "$2a$03$......................"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void hashpwFailsWhenSaltSpecifiesTooManyRounds() { public void hashpwFailsWhenSaltSpecifiesTooManyRounds() {
BCrypt.hashpw("password", "$2a$32$......................"); assertThatIllegalArgumentException()
.isThrownBy(() -> BCrypt.hashpw("password", "$2a$32$......................"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void saltLengthIsChecked() { public void saltLengthIsChecked() {
BCrypt.hashpw("", ""); assertThatIllegalArgumentException().isThrownBy(() -> BCrypt.hashpw("", ""));
} }
@Test @Test
@ -436,9 +441,10 @@ public class BCryptTests {
.isEqualTo("$2$05$......................bvpG2UfzdyW/S0ny/4YyEZrmczoJfVm"); .isEqualTo("$2$05$......................bvpG2UfzdyW/S0ny/4YyEZrmczoJfVm");
} }
@Test(expected = IllegalArgumentException.class) @Test
public void hashpwFailsWhenSaltIsTooShort() { public void hashpwFailsWhenSaltIsTooShort() {
BCrypt.hashpw("password", "$2a$10$123456789012345678901"); assertThatIllegalArgumentException()
.isThrownBy(() -> BCrypt.hashpw("password", "$2a$10$123456789012345678901"));
} }
@Test @Test

View File

@ -19,6 +19,8 @@ package org.springframework.security.crypto.codec;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Luke Taylor * @author Luke Taylor
@ -37,14 +39,14 @@ public class Base64Tests {
assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C', (byte) '`' })).isFalse(); assertThat(Base64.isBase64(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C', (byte) '`' })).isFalse();
} }
@Test(expected = NullPointerException.class) @Test
public void isBase64RejectsNull() { public void isBase64RejectsNull() {
Base64.isBase64(null); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> Base64.isBase64(null));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void isBase64RejectsInvalidLength() { public void isBase64RejectsInvalidLength() {
Base64.isBase64(new byte[] { (byte) 'A' }); assertThatIllegalArgumentException().isThrownBy(() -> Base64.isBase64(new byte[] { (byte) 'A' }));
} }
} }

View File

@ -27,6 +27,8 @@ import org.junit.Test;
import org.springframework.security.crypto.codec.Hex; import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.keygen.KeyGenerators; import org.springframework.security.crypto.keygen.KeyGenerators;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class BouncyCastleAesBytesEncryptorTests { public class BouncyCastleAesBytesEncryptorTests {
private byte[] testData; private byte[] testData;
@ -69,14 +71,16 @@ public class BouncyCastleAesBytesEncryptorTests {
Assert.assertArrayEquals(this.testData, decrypted2); Assert.assertArrayEquals(this.testData, decrypted2);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void bcCbcWithWrongLengthIv() { public void bcCbcWithWrongLengthIv() {
new BouncyCastleAesCbcBytesEncryptor(this.password, this.salt, KeyGenerators.secureRandom(8)); assertThatIllegalArgumentException().isThrownBy(
() -> new BouncyCastleAesCbcBytesEncryptor(this.password, this.salt, KeyGenerators.secureRandom(8)));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void bcGcmWithWrongLengthIv() { public void bcGcmWithWrongLengthIv() {
new BouncyCastleAesGcmBytesEncryptor(this.password, this.salt, KeyGenerators.secureRandom(8)); assertThatIllegalArgumentException().isThrownBy(
() -> new BouncyCastleAesGcmBytesEncryptor(this.password, this.salt, KeyGenerators.secureRandom(8)));
} }
} }

View File

@ -21,6 +21,7 @@ import java.util.Base64;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Rob Winch * @author Rob Winch
@ -28,15 +29,14 @@ import static org.assertj.core.api.Assertions.assertThat;
*/ */
public class Base64StringKeyGeneratorTests { public class Base64StringKeyGeneratorTests {
@Test(expected = IllegalArgumentException.class) @Test
public void constructorIntWhenLessThan32ThenIllegalArgumentException() { public void constructorIntWhenLessThan32ThenIllegalArgumentException() {
new Base64StringKeyGenerator(31); assertThatIllegalArgumentException().isThrownBy(() -> new Base64StringKeyGenerator(31));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorEncoderWhenEncoderNullThenThrowsIllegalArgumentException() { public void constructorEncoderWhenEncoderNullThenThrowsIllegalArgumentException() {
Base64.Encoder encoder = null; assertThatIllegalArgumentException().isThrownBy(() -> new Base64StringKeyGenerator(null));
new Base64StringKeyGenerator(null);
} }
@Test @Test

View File

@ -72,19 +72,21 @@ public class DelegatingPasswordEncoderTests {
this.passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates); this.passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorWhenIdForEncodeNullThenIllegalArgumentException() { public void constructorWhenIdForEncodeNullThenIllegalArgumentException() {
new DelegatingPasswordEncoder(null, this.delegates); assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingPasswordEncoder(null, this.delegates));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorWhenIdForEncodeDoesNotExistThenIllegalArgumentException() { public void constructorWhenIdForEncodeDoesNotExistThenIllegalArgumentException() {
new DelegatingPasswordEncoder(this.bcryptId + "INVALID", this.delegates); assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingPasswordEncoder(this.bcryptId + "INVALID", this.delegates));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void setDefaultPasswordEncoderForMatchesWhenNullThenIllegalArgumentException() { public void setDefaultPasswordEncoderForMatchesWhenNullThenIllegalArgumentException() {
this.passwordEncoder.setDefaultPasswordEncoderForMatches(null); assertThatIllegalArgumentException()
.isThrownBy(() -> this.passwordEncoder.setDefaultPasswordEncoderForMatches(null));
} }
@Test @Test
@ -180,9 +182,9 @@ public class DelegatingPasswordEncoderTests {
verifyZeroInteractions(this.bcrypt, this.noop); verifyZeroInteractions(this.bcrypt, this.noop);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void matchesWhenRawPasswordNotNullAndEncodedPasswordNullThenThrowsIllegalArgumentException() { public void matchesWhenRawPasswordNotNullAndEncodedPasswordNullThenThrowsIllegalArgumentException() {
this.passwordEncoder.matches(this.rawPassword, null); assertThatIllegalArgumentException().isThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, null));
} }
@Test @Test

View File

@ -21,6 +21,7 @@ import org.junit.Test;
import org.springframework.security.crypto.keygen.KeyGenerators; import org.springframework.security.crypto.keygen.KeyGenerators;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link LdapShaPasswordEncoder}. * Tests {@link LdapShaPasswordEncoder}.
@ -92,15 +93,16 @@ public class LdapShaPasswordEncoderTests {
assertThat(this.sha.encode("somepassword").startsWith("{SSHA}")); assertThat(this.sha.encode("somepassword").startsWith("{SSHA}"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void invalidPrefixIsRejected() { public void invalidPrefixIsRejected() {
this.sha.matches("somepassword", "{MD9}xxxxxxxxxx"); assertThatIllegalArgumentException().isThrownBy(() -> this.sha.matches("somepassword", "{MD9}xxxxxxxxxx"));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void malformedPrefixIsRejected() { public void malformedPrefixIsRejected() {
// No right brace // No right brace
this.sha.matches("somepassword", "{SSHA25ro4PKC8jhQZ26jVsozhX/xaP0suHgX"); assertThatIllegalArgumentException()
.isThrownBy(() -> this.sha.matches("somepassword", "{SSHA25ro4PKC8jhQZ26jVsozhX/xaP0suHgX"));
} }
} }

View File

@ -19,6 +19,7 @@ package org.springframework.security.crypto.password;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/** /**
* <p> * <p>
@ -112,9 +113,9 @@ public class MessageDigestPasswordEncoderTests {
assertThat(pe.matches(raw, "{THIS_IS_A_SALT}4b79b7de23eb23b78cc5ede227d532b8a51f89b2ec166f808af76b0dbedc47d7")); assertThat(pe.matches(raw, "{THIS_IS_A_SALT}4b79b7de23eb23b78cc5ede227d532b8a51f89b2ec166f808af76b0dbedc47d7"));
} }
@Test(expected = IllegalStateException.class) @Test
public void testInvalidStrength() { public void testInvalidStrength() {
new MessageDigestPasswordEncoder("SHA-666"); assertThatIllegalStateException().isThrownBy(() -> new MessageDigestPasswordEncoder("SHA-666"));
} }
} }

View File

@ -19,6 +19,7 @@ package org.springframework.security.crypto.scrypt;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Shazin Sadakath * @author Shazin Sadakath
@ -91,29 +92,32 @@ public class SCryptPasswordEncoderTests {
assertThat(encoder.matches("password", "012345678901234567890123456789")).isFalse(); assertThat(encoder.matches("password", "012345678901234567890123456789")).isFalse();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void invalidCpuCostParameter() { public void invalidCpuCostParameter() {
new SCryptPasswordEncoder(Integer.MIN_VALUE, 16, 2, 32, 16); assertThatIllegalArgumentException()
.isThrownBy(() -> new SCryptPasswordEncoder(Integer.MIN_VALUE, 16, 2, 32, 16));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void invalidMemoryCostParameter() { public void invalidMemoryCostParameter() {
new SCryptPasswordEncoder(2, Integer.MAX_VALUE, 2, 32, 16); assertThatIllegalArgumentException()
.isThrownBy(() -> new SCryptPasswordEncoder(2, Integer.MAX_VALUE, 2, 32, 16));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void invalidParallelizationParameter() { public void invalidParallelizationParameter() {
new SCryptPasswordEncoder(2, 8, Integer.MAX_VALUE, 32, 16); assertThatIllegalArgumentException()
.isThrownBy(() -> new SCryptPasswordEncoder(2, 8, Integer.MAX_VALUE, 32, 16));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void invalidSaltLengthParameter() { public void invalidSaltLengthParameter() {
new SCryptPasswordEncoder(2, 8, 1, 16, -1); assertThatIllegalArgumentException().isThrownBy(() -> new SCryptPasswordEncoder(2, 8, 1, 16, -1));
} }
@Test(expected = IllegalArgumentException.class) @Test
public void invalidKeyLengthParameter() { public void invalidKeyLengthParameter() {
new SCryptPasswordEncoder(2, 8, 1, -1, 16); assertThatIllegalArgumentException().isThrownBy(() -> new SCryptPasswordEncoder(2, 8, 1, -1, 16));
} }
@Test @Test
@ -153,9 +157,10 @@ public class SCryptPasswordEncoderTests {
assertThat(strongEncoder.upgradeEncoding(weakPassword)).isTrue(); assertThat(strongEncoder.upgradeEncoding(weakPassword)).isTrue();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void upgradeEncodingWhenInvalidInputThenException() { public void upgradeEncodingWhenInvalidInputThenException() {
new SCryptPasswordEncoder().upgradeEncoding("not-a-scrypt-password"); assertThatIllegalArgumentException()
.isThrownBy(() -> new SCryptPasswordEncoder().upgradeEncoding("not-a-scrypt-password"));
} }
} }

View File

@ -25,6 +25,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class SecurityEvaluationContextExtensionTests { public class SecurityEvaluationContextExtensionTests {
@ -40,9 +41,9 @@ public class SecurityEvaluationContextExtensionTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void getRootObjectSecurityContextHolderAuthenticationNull() { public void getRootObjectSecurityContextHolderAuthenticationNull() {
getRoot().getAuthentication(); assertThatIllegalArgumentException().isThrownBy(() -> getRoot().getAuthentication());
} }
@Test @Test

View File

@ -34,7 +34,7 @@ import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@ContextConfiguration(locations = { "/http-path-param-stripping-app-context.xml" }) @ContextConfiguration(locations = { "/http-path-param-stripping-app-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ -43,33 +43,35 @@ public class HttpPathParameterStrippingTests {
@Autowired @Autowired
private FilterChainProxy fcp; private FilterChainProxy fcp;
@Test(expected = RequestRejectedException.class) @Test
public void securedFilterChainCannotBeBypassedByAddingPathParameters() throws Exception { public void securedFilterChainCannotBeBypassedByAddingPathParameters() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.setPathInfo("/secured;x=y/admin.html"); request.setPathInfo("/secured;x=y/admin.html");
request.setSession(createAuthenticatedSession("ROLE_USER")); request.setSession(createAuthenticatedSession("ROLE_USER"));
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
this.fcp.doFilter(request, response, new MockFilterChain()); assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.fcp.doFilter(request, response, new MockFilterChain()));
} }
@Test(expected = RequestRejectedException.class) @Test
public void adminFilePatternCannotBeBypassedByAddingPathParameters() throws Exception { public void adminFilePatternCannotBeBypassedByAddingPathParameters() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/secured/admin.html;x=user.html"); request.setServletPath("/secured/admin.html;x=user.html");
request.setSession(createAuthenticatedSession("ROLE_USER")); request.setSession(createAuthenticatedSession("ROLE_USER"));
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
this.fcp.doFilter(request, response, new MockFilterChain()); assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.fcp.doFilter(request, response, new MockFilterChain()));
} }
@Test(expected = RequestRejectedException.class) @Test
public void adminFilePatternCannotBeBypassedByAddingPathParametersWithPathInfo() throws Exception { public void adminFilePatternCannotBeBypassedByAddingPathParametersWithPathInfo() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/secured"); request.setServletPath("/secured");
request.setPathInfo("/admin.html;x=user.html"); request.setPathInfo("/admin.html;x=user.html");
request.setSession(createAuthenticatedSession("ROLE_USER")); request.setSession(createAuthenticatedSession("ROLE_USER"));
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
this.fcp.doFilter(request, response, new MockFilterChain()); assertThatExceptionOfType(RequestRejectedException.class)
assertThat(response.getStatus()).isEqualTo(403); .isThrownBy(() -> this.fcp.doFilter(request, response, new MockFilterChain()));
} }
public HttpSession createAuthenticatedSession(String... roles) { public HttpSession createAuthenticatedSession(String... roles) {

View File

@ -31,6 +31,8 @@ import org.springframework.security.integration.multiannotation.SecuredService;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Luke Taylor * @author Luke Taylor
*/ */
@ -57,16 +59,16 @@ public class MultiAnnotationTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = AccessDeniedException.class) @Test
public void preAuthorizeDeniedIsDenied() { public void preAuthorizeDeniedIsDenied() {
SecurityContextHolder.getContext().setAuthentication(this.joe_a); SecurityContextHolder.getContext().setAuthentication(this.joe_a);
this.service.preAuthorizeDenyAllMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.service::preAuthorizeDenyAllMethod);
} }
@Test(expected = AccessDeniedException.class) @Test
public void preAuthorizeRoleAIsDeniedIfRoleMissing() { public void preAuthorizeRoleAIsDeniedIfRoleMissing() {
SecurityContextHolder.getContext().setAuthentication(this.joe_b); SecurityContextHolder.getContext().setAuthentication(this.joe_b);
this.service.preAuthorizeHasRoleAMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.service::preAuthorizeHasRoleAMethod);
} }
@Test @Test
@ -81,10 +83,10 @@ public class MultiAnnotationTests {
this.service.securedAnonymousMethod(); this.service.securedAnonymousMethod();
} }
@Test(expected = AccessDeniedException.class) @Test
public void securedRoleAIsDeniedIfRoleMissing() { public void securedRoleAIsDeniedIfRoleMissing() {
SecurityContextHolder.getContext().setAuthentication(this.joe_b); SecurityContextHolder.getContext().setAuthentication(this.joe_b);
this.service.securedRoleAMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.service::securedRoleAMethod);
} }
@Test @Test
@ -93,16 +95,16 @@ public class MultiAnnotationTests {
this.service.securedRoleAMethod(); this.service.securedRoleAMethod();
} }
@Test(expected = AccessDeniedException.class) @Test
public void preAuthorizedOnlyServiceDeniesIfRoleMissing() { public void preAuthorizedOnlyServiceDeniesIfRoleMissing() {
SecurityContextHolder.getContext().setAuthentication(this.joe_b); SecurityContextHolder.getContext().setAuthentication(this.joe_b);
this.preService.preAuthorizedMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.preService::preAuthorizedMethod);
} }
@Test(expected = AccessDeniedException.class) @Test
public void securedOnlyRoleAServiceDeniesIfRoleMissing() { public void securedOnlyRoleAServiceDeniesIfRoleMissing() {
SecurityContextHolder.getContext().setAuthentication(this.joe_b); SecurityContextHolder.getContext().setAuthentication(this.joe_b);
this.secService.securedMethod(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.secService::securedMethod);
} }
} }

View File

@ -27,6 +27,8 @@ import org.springframework.security.core.session.SessionRegistry;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Luke Taylor * @author Luke Taylor
* @since 2.0 * @since 2.0
@ -35,17 +37,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
public class SEC936ApplicationContextTests { public class SEC936ApplicationContextTests {
@Autowired
/** /**
* SessionRegistry is used as the test service interface (nothing to do with the test) * SessionRegistry is used as the test service interface (nothing to do with the test)
*/ */
@Autowired
private SessionRegistry sessionRegistry; private SessionRegistry sessionRegistry;
@Test(expected = AccessDeniedException.class) @Test
public void securityInterceptorHandlesCallWithNoTargetObject() { public void securityInterceptorHandlesCallWithNoTargetObject() {
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("bob", "bobspassword")); .setAuthentication(new UsernamePasswordAuthenticationToken("bob", "bobspassword"));
this.sessionRegistry.getAllPrincipals(); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.sessionRegistry::getAllPrincipals);
} }
} }

View File

@ -20,8 +20,6 @@ import java.util.ArrayList;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List; import java.util.List;
import javax.naming.directory.DirContext;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -32,6 +30,8 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author Luke Taylor * @author Luke Taylor
@ -80,21 +80,14 @@ public class DefaultSpringSecurityContextSourceTests {
} }
// SEC-1145. Confirms that there is no issue here with pooling. // SEC-1145. Confirms that there is no issue here with pooling.
@Test(expected = AuthenticationException.class) @Test
public void cantBindWithWrongPasswordImmediatelyAfterSuccessfulBind() throws Exception { public void cantBindWithWrongPasswordImmediatelyAfterSuccessfulBind() throws Exception {
DirContext ctx = null; this.contextSource.getContext("uid=Bob,ou=people,dc=springframework,dc=org", "bobspassword").close();
try {
ctx = this.contextSource.getContext("uid=Bob,ou=people,dc=springframework,dc=org", "bobspassword");
}
catch (Exception ex) {
}
assertThat(ctx).isNotNull();
// com.sun.jndi.ldap.LdapPoolManager.showStats(System.out); // com.sun.jndi.ldap.LdapPoolManager.showStats(System.out);
ctx.close();
// com.sun.jndi.ldap.LdapPoolManager.showStats(System.out); // com.sun.jndi.ldap.LdapPoolManager.showStats(System.out);
// Now get it gain, with wrong password. Should fail. // Now get it gain, with wrong password. Should fail.
ctx = this.contextSource.getContext("uid=Bob,ou=people,dc=springframework,dc=org", "wrongpassword"); assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.contextSource
ctx.close(); .getContext("uid=Bob,ou=people,dc=springframework,dc=org", "wrongpassword").close());
} }
@Test @Test
@ -105,12 +98,14 @@ public class DefaultSpringSecurityContextSourceTests {
contextSource.getContext("uid=space cadet,ou=space cadets,dc=springframework,dc=org", "spacecadetspassword"); contextSource.getContext("uid=space cadet,ou=space cadets,dc=springframework,dc=org", "spacecadetspassword");
} }
@Test(expected = IllegalArgumentException.class) @Test
public void instantiationFailsWithEmptyServerList() { public void instantiationFailsWithEmptyServerList() {
List<String> serverUrls = new ArrayList<>(); List<String> serverUrls = new ArrayList<>();
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(serverUrls, assertThatIllegalArgumentException().isThrownBy(() -> {
"dc=springframework,dc=org"); DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(serverUrls,
ctxSrc.afterPropertiesSet(); "dc=springframework,dc=org");
ctxSrc.afterPropertiesSet();
});
} }
@Test @Test
@ -140,15 +135,15 @@ public class DefaultSpringSecurityContextSourceTests {
assertThat(ctxSrc.isPooled()).isTrue(); assertThat(ctxSrc.isPooled()).isTrue();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void instantiationFailsWithIncorrectServerUrl() { public void instantiationFailsWithIncorrectServerUrl() {
List<String> serverUrls = new ArrayList<>(); List<String> serverUrls = new ArrayList<>();
// a simple trailing slash should be ok // a simple trailing slash should be ok
serverUrls.add("ldaps://blah:636/"); serverUrls.add("ldaps://blah:636/");
// this url should be rejected because the root DN goes into a separate parameter // this url should be rejected because the root DN goes into a separate parameter
serverUrls.add("ldap://bar:389/dc=foobar,dc=org"); serverUrls.add("ldap://bar:389/dc=foobar,dc=org");
DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(serverUrls, assertThatIllegalArgumentException()
"dc=springframework,dc=org"); .isThrownBy(() -> new DefaultSpringSecurityContextSource(serverUrls, "dc=springframework,dc=org"));
} }
static class EnvExposingDefaultSpringSecurityContextSource extends DefaultSpringSecurityContextSource { static class EnvExposingDefaultSpringSecurityContextSource extends DefaultSpringSecurityContextSource {

View File

@ -60,9 +60,10 @@ public class BindAuthenticatorTests {
} }
@Test(expected = BadCredentialsException.class) @Test
public void emptyPasswordIsRejected() { public void emptyPasswordIsRejected() {
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("jen", "")); assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("jen", "")));
} }
@Test @Test

View File

@ -37,6 +37,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests for {@link PasswordComparisonAuthenticator}. * Tests for {@link PasswordComparisonAuthenticator}.
@ -84,11 +85,12 @@ public class PasswordComparisonAuthenticatorTests {
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass"))); () -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass")));
} }
@Test(expected = BadCredentialsException.class) @Test
public void testLdapPasswordCompareFailsWithWrongPassword() { public void testLdapPasswordCompareFailsWithWrongPassword() {
// Don't retrieve the password // Don't retrieve the password
this.authenticator.setUserAttributes(new String[] { "uid", "cn", "sn" }); this.authenticator.setUserAttributes(new String[] { "uid", "cn", "sn" });
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpass")); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpass")));
} }
@Test @Test
@ -121,9 +123,9 @@ public class PasswordComparisonAuthenticatorTests {
this.authenticator.authenticate(this.ben); this.authenticator.authenticate(this.ben);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void testPasswordEncoderCantBeNull() { public void testPasswordEncoderCantBeNull() {
this.authenticator.setPasswordEncoder(null); assertThatIllegalArgumentException().isThrownBy(() -> this.authenticator.setPasswordEncoder(null));
} }
@Test @Test

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