diff --git a/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java b/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java index 6f09d718904..0bbcdcf5064 100644 --- a/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java +++ b/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java @@ -22,7 +22,8 @@ import org.springframework.security.acls.model.Permission; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatNoException; /** * Tests for {@link AclFormattingUtils}. @@ -33,30 +34,11 @@ public class AclFormattingUtilsTests { @Test public final void testDemergePatternsParametersConstraints() { - try { - AclFormattingUtils.demergePatterns(null, "SOME STRING"); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - AclFormattingUtils.demergePatterns("SOME STRING", null); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING"); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH"); - } - catch (IllegalArgumentException notExpected) { - fail("It shouldn't have thrown IllegalArgumentException"); - } + assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns(null, "SOME STRING")); + assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", null)); + assertThatIllegalArgumentException() + .isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING")); + assertThatNoException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH")); } @Test @@ -71,29 +53,11 @@ public final void testDemergePatterns() { @Test public final void testMergePatternsParametersConstraints() { - try { - AclFormattingUtils.mergePatterns(null, "SOME STRING"); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - AclFormattingUtils.mergePatterns("SOME STRING", null); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING"); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH"); - } - catch (IllegalArgumentException notExpected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns(null, "SOME STRING")); + assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", null)); + assertThatIllegalArgumentException() + .isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING")); + assertThatNoException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH")); } @Test @@ -108,18 +72,10 @@ public final void testMergePatterns() { @Test public final void testBinaryPrints() { assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****"); - try { - AclFormattingUtils.printBinary(15, Permission.RESERVED_ON); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException notExpected) { - } - try { - AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException notExpected) { - } + assertThatIllegalArgumentException() + .isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_ON)); + assertThatIllegalArgumentException() + .isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF)); assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo("............................xxxx"); } diff --git a/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java b/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java index b044f89c3a3..4d2c04eee40 100644 --- a/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java +++ b/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java @@ -36,7 +36,8 @@ import org.springframework.security.core.SpringSecurityMessageSource; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +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.anyBoolean; import static org.mockito.BDDMockito.given; @@ -50,15 +51,12 @@ @SuppressWarnings({ "unchecked" }) public class AclEntryAfterInvocationProviderTests { - @Test(expected = IllegalArgumentException.class) + @Test public void rejectsMissingPermissions() { - try { - new AclEntryAfterInvocationProvider(mock(AclService.class), null); - fail("Exception expected"); - } - catch (IllegalArgumentException expected) { - } - new AclEntryAfterInvocationProvider(mock(AclService.class), Collections.emptyList()); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AclEntryAfterInvocationProvider(mock(AclService.class), null)); + assertThatIllegalArgumentException().isThrownBy( + () -> new AclEntryAfterInvocationProvider(mock(AclService.class), Collections.emptyList())); } @Test @@ -98,7 +96,7 @@ public void accessIsGrantedIfObjectTypeNotSupported() { SecurityConfig.createList("AFTER_ACL_READ"), returned)); } - @Test(expected = AccessDeniedException.class) + @Test public void accessIsDeniedIfPermissionIsNotGranted() { AclService service = mock(AclService.class); Acl acl = mock(Acl.class); @@ -113,16 +111,13 @@ public void accessIsDeniedIfPermissionIsNotGranted() { provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class)); provider.setProcessDomainObjectClass(Object.class); provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class)); - try { - provider.decide(mock(Authentication.class), new Object(), - SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()); - fail("Expected Exception"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), + SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object())); // Second scenario with no acls found - provider.decide(mock(Authentication.class), new Object(), - SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()); + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), + SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object())); } @Test diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java index 743f8ee3b8e..e8155e76e36 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java @@ -25,7 +25,7 @@ import org.springframework.security.acls.model.Sid; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -39,27 +39,14 @@ public class AccessControlImplEntryTests { @Test public void testConstructorRequiredFields() { // Check Acl field is present - try { - new AccessControlEntryImpl(null, null, new PrincipalSid("johndoe"), BasePermission.ADMINISTRATION, true, - true, true); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, null, + new PrincipalSid("johndoe"), BasePermission.ADMINISTRATION, true, true, true)); // Check Sid field is present - try { - new AccessControlEntryImpl(null, mock(Acl.class), null, BasePermission.ADMINISTRATION, true, true, true); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, mock(Acl.class), null, + BasePermission.ADMINISTRATION, true, true, true)); // Check Permission field is present - try { - new AccessControlEntryImpl(null, mock(Acl.class), new PrincipalSid("johndoe"), null, true, true, true); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, mock(Acl.class), + new PrincipalSid("johndoe"), null, true, true, true)); } @Test diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java index c86776a9c77..9040547d6ad 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java @@ -46,7 +46,8 @@ import org.springframework.security.util.FieldUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -97,58 +98,38 @@ public void tearDown() { SecurityContextHolder.clearContext(); } - @Test(expected = IllegalArgumentException.class) + @Test public void constructorsRejectNullObjectIdentity() { - try { - new AclImpl(null, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - new AclImpl(null, 1, this.authzStrategy, this.mockAuditLogger); + assertThatIllegalArgumentException().isThrownBy( + () -> new AclImpl(null, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe"))); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AclImpl(null, 1, this.authzStrategy, this.mockAuditLogger)); } - @Test(expected = IllegalArgumentException.class) + @Test public void constructorsRejectNullId() { - try { - new AclImpl(this.objectIdentity, null, this.authzStrategy, this.pgs, null, null, true, - new PrincipalSid("joe")); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - new AclImpl(this.objectIdentity, null, this.authzStrategy, this.mockAuditLogger); + assertThatIllegalArgumentException().isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy, + this.pgs, null, null, true, new PrincipalSid("joe"))); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy, this.mockAuditLogger)); } - @SuppressWarnings("deprecation") - @Test(expected = IllegalArgumentException.class) + @Test public void constructorsRejectNullAclAuthzStrategy() { - try { - new AclImpl(this.objectIdentity, 1, null, new DefaultPermissionGrantingStrategy(this.mockAuditLogger), null, - null, true, new PrincipalSid("joe")); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - new AclImpl(this.objectIdentity, 1, null, this.mockAuditLogger); + assertThatIllegalArgumentException().isThrownBy(() -> new AclImpl(this.objectIdentity, 1, null, + new DefaultPermissionGrantingStrategy(this.mockAuditLogger), null, null, true, + new PrincipalSid("joe"))); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AclImpl(this.objectIdentity, 1, null, this.mockAuditLogger)); } @Test public void insertAceRejectsNullParameters() { MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); - try { - acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - acl.insertAce(0, BasePermission.READ, null, true); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException() + .isThrownBy(() -> acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true)); + assertThatIllegalArgumentException().isThrownBy(() -> acl.insertAce(0, BasePermission.READ, null, true)); } @Test @@ -232,12 +213,7 @@ public void deleteAceFailsForNonExistentElement() { new SimpleGrantedAuthority("ROLE_GENERAL")); MutableAcl acl = new AclImpl(this.objectIdentity, (1), strategy, this.pgs, null, null, true, new PrincipalSid("joe")); - try { - acl.deleteAce(99); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } + assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> acl.deleteAce(99)); } @Test @@ -245,18 +221,9 @@ public void isGrantingRejectsEmptyParameters() { MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); Sid ben = new PrincipalSid("ben"); - try { - acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - acl.isGranted(READ, new ArrayList<>(0), false); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException() + .isThrownBy(() -> acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false)); + assertThatIllegalArgumentException().isThrownBy(() -> acl.isGranted(READ, new ArrayList<>(0), false)); } @Test @@ -277,25 +244,16 @@ public void isGrantingGrantsAccessForAclWithNoParent() { List permissions = Arrays.asList(BasePermission.READ, BasePermission.CREATE); List sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST")); assertThat(rootAcl.isGranted(permissions, sids, false)).isFalse(); - try { - rootAcl.isGranted(permissions, SCOTT, false); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } + assertThatExceptionOfType(NotFoundException.class) + .isThrownBy(() -> rootAcl.isGranted(permissions, SCOTT, false)); assertThat(rootAcl.isGranted(WRITE, SCOTT, false)).isTrue(); assertThat(rootAcl.isGranted(WRITE, Arrays.asList(new PrincipalSid("rod"), new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false)).isFalse(); assertThat(rootAcl.isGranted(WRITE, Arrays.asList(new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false)).isTrue(); - try { - // Change the type of the Sid and check the granting process - rootAcl.isGranted(WRITE, - Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } + // Change the type of the Sid and check the granting process + assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> rootAcl.isGranted(WRITE, + Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false)); } @Test @@ -348,18 +306,9 @@ public void isGrantingGrantsAccessForInheritableAcls() { assertThat(childAcl1.isGranted(DELETE, BEN, false)).isFalse(); // Check granting process for child2 (doesn't inherit the permissions from its // parent) - try { - assertThat(childAcl2.isGranted(CREATE, SCOTT, false)).isTrue(); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } - try { - childAcl2.isGranted(CREATE, Arrays.asList((Sid) new PrincipalSid("joe")), false); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } + assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> childAcl2.isGranted(CREATE, SCOTT, false)); + assertThatExceptionOfType(NotFoundException.class) + .isThrownBy(() -> childAcl2.isGranted(CREATE, Arrays.asList((Sid) new PrincipalSid("joe")), false)); } @Test diff --git a/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java b/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java index 9a121f71abf..844f2d10e3e 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java @@ -30,7 +30,8 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatNoException; /** * Test class for {@link AclAuthorizationStrategyImpl} and {@link AclImpl} security @@ -72,24 +73,12 @@ public void testSecurityCheckNoACEs() { new SimpleGrantedAuthority("ROLE_THREE")); Acl acl2 = new AclImpl(identity, 1L, aclAuthorizationStrategy2, new ConsoleAuditLogger()); // Check access in case the principal has no authorization rights - try { - aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } - try { - aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } - try { - aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } + assertThatExceptionOfType(NotFoundException.class).isThrownBy( + () -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL)); + assertThatExceptionOfType(NotFoundException.class).isThrownBy( + () -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING)); + assertThatExceptionOfType(NotFoundException.class).isThrownBy( + () -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); } @Test @@ -112,28 +101,16 @@ public void testSecurityCheckWithMultipleACEs() { // The CHANGE_AUDITING and CHANGE_OWNERSHIP should fail since the // principal doesn't have these authorities, // nor granting access - try { - aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING); - fail("It should have thrown AccessDeniedException"); - } - catch (AccessDeniedException expected) { - } - try { - aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_OWNERSHIP); - fail("It should have thrown AccessDeniedException"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING)); + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); // Add granting access to this principal aclFirstDeny.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true); // and try again for CHANGE_AUDITING - the first ACE's granting flag // (false) will deny this access - try { - aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING); - fail("It should have thrown AccessDeniedException"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING)); // Create another ACL and give the principal the ADMINISTRATION // permission, with granting access MutableAcl aclFirstAllow = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger()); @@ -143,27 +120,15 @@ public void testSecurityCheckWithMultipleACEs() { aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING); // Add a deny ACE and test again for CHANGE_AUDITING aclFirstAllow.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false); - try { - aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING); - } - catch (AccessDeniedException notExpected) { - fail("It shouldn't have thrown AccessDeniedException"); - } + assertThatNoException().isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING)); // Create an ACL with no ACE MutableAcl aclNoACE = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger()); - try { - aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_AUDITING); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } + assertThatExceptionOfType(NotFoundException.class).isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_AUDITING)); // and still grant access for CHANGE_GENERAL - try { - aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL); - } - catch (NotFoundException expected) { - fail("It shouldn't have thrown NotFoundException"); - } + assertThatNoException().isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL)); } @Test @@ -184,22 +149,14 @@ public void testSecurityCheckWithInheritableACEs() { MutableAcl childAcl = new AclImpl(identity, 2, aclAuthorizationStrategy, new ConsoleAuditLogger()); // Check against the 'child' acl, which doesn't offer any authorization // rights on CHANGE_OWNERSHIP - try { - aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } + assertThatExceptionOfType(NotFoundException.class).isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); // Link the child with its parent and test again against the // CHANGE_OWNERSHIP right childAcl.setParent(parentAcl); childAcl.setEntriesInheriting(true); - try { - aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP); - } - catch (NotFoundException expected) { - fail("It shouldn't have thrown NotFoundException"); - } + assertThatNoException().isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); // Create a root parent and link it to the middle parent MutableAcl rootParentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger()); parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger()); @@ -207,12 +164,8 @@ public void testSecurityCheckWithInheritableACEs() { parentAcl.setEntriesInheriting(true); parentAcl.setParent(rootParentAcl); childAcl.setParent(parentAcl); - try { - aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP); - } - catch (NotFoundException expected) { - fail("It shouldn't have thrown NotFoundException"); - } + assertThatNoException().isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); } @Test @@ -227,24 +180,12 @@ public void testSecurityCheckPrincipalOwner() { Acl acl = new AclImpl(identity, 1, aclAuthorizationStrategy, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null, null, false, new PrincipalSid(auth)); - try { - aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL); - } - catch (AccessDeniedException notExpected) { - fail("It shouldn't have thrown AccessDeniedException"); - } - try { - aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING); - fail("It shouldn't have thrown AccessDeniedException"); - } - catch (NotFoundException expected) { - } - try { - aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP); - } - catch (AccessDeniedException notExpected) { - fail("It shouldn't have thrown AccessDeniedException"); - } + assertThatNoException() + .isThrownBy(() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL)); + assertThatExceptionOfType(NotFoundException.class).isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING)); + assertThatNoException().isThrownBy( + () -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); } } diff --git a/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityImplTests.java b/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityImplTests.java index 309dc8776f9..ca94695ac19 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityImplTests.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityImplTests.java @@ -21,7 +21,9 @@ import org.springframework.security.acls.model.ObjectIdentity; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatNoException; /** * Tests for {@link ObjectIdentityImpl}. @@ -36,40 +38,15 @@ public class ObjectIdentityImplTests { @Test public void constructorsRespectRequiredFields() { // Check one-argument constructor required field - try { - new ObjectIdentityImpl(null); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(null)); // Check String-Serializable constructor required field - try { - new ObjectIdentityImpl("", 1L); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl("", 1L)); // Check Serializable parameter is not null - try { - new ObjectIdentityImpl(DOMAIN_CLASS, null); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(DOMAIN_CLASS, null)); // The correct way of using String-Serializable constructor - try { - new ObjectIdentityImpl(DOMAIN_CLASS, 1L); - } - catch (IllegalArgumentException notExpected) { - fail("It shouldn't have thrown IllegalArgumentException"); - } + assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(DOMAIN_CLASS, 1L)); // Check the Class-Serializable constructor - try { - new ObjectIdentityImpl(MockIdDomainObject.class, null); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(MockIdDomainObject.class, null)); } @Test @@ -82,35 +59,17 @@ public void gettersReturnExpectedValues() { @Test public void testGetIdMethodConstraints() { // Check the getId() method is present - try { - new ObjectIdentityImpl("A_STRING_OBJECT"); - fail("It should have thrown IdentityUnavailableException"); - } - catch (IdentityUnavailableException expected) { - } + assertThatExceptionOfType(IdentityUnavailableException.class) + .isThrownBy(() -> new ObjectIdentityImpl("A_STRING_OBJECT")); // getId() should return a non-null value MockIdDomainObject mockId = new MockIdDomainObject(); - try { - new ObjectIdentityImpl(mockId); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(mockId)); // getId() should return a Serializable object mockId.setId(new MockIdDomainObject()); - try { - new ObjectIdentityImpl(mockId); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(mockId)); // getId() should return a Serializable object mockId.setId(100L); - try { - new ObjectIdentityImpl(mockId); - } - catch (IllegalArgumentException expected) { - } + assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(mockId)); } @Test(expected = IllegalArgumentException.class) diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java index 6000bab5962..7a7e2f196d0 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java @@ -48,14 +48,12 @@ import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AuditableAccessControlEntry; import org.springframework.security.acls.model.MutableAcl; -import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Sid; import org.springframework.security.core.authority.SimpleGrantedAuthority; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; /** * Tests {@link BasicLookupStrategy} @@ -290,12 +288,7 @@ public void testReadAllObjectIdentitiesWhenLastElementIsAlreadyCached() { // is already in cache and the element before it must not be stored in // cache List allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid); - try { - foundAcls = this.strategy.readAclsById(allOids, sids); - } - catch (NotFoundException notExpected) { - fail("It shouldn't have thrown NotFoundException"); - } + foundAcls = this.strategy.readAclsById(allOids, sids); Acl foundParent2Acl = foundAcls.get(parent2Oid); assertThat(foundParent2Acl).isNotNull(); assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue(); diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java index d293b500844..397a72cfcd8 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java @@ -52,7 +52,7 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -102,41 +102,11 @@ public void constructorRejectsNullParameters() { @Test public void methodsRejectNullParameters() { - try { - Serializable id = null; - this.myCache.evictFromCache(id); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - ObjectIdentity obj = null; - this.myCache.evictFromCache(obj); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - Serializable id = null; - this.myCache.getFromCache(id); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - ObjectIdentity obj = null; - this.myCache.getFromCache(obj); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - MutableAcl acl = null; - this.myCache.putInCache(acl); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.evictFromCache((Serializable) null)); + assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.evictFromCache((ObjectIdentity) null)); + assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.getFromCache((Serializable) null)); + assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.getFromCache((ObjectIdentity) null)); + assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.putInCache(null)); } // SEC-527 diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java index fe447325408..4b4e3b0fa9d 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java @@ -55,7 +55,8 @@ import org.springframework.transaction.annotation.Transactional; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.spy; @@ -161,91 +162,80 @@ public void testLifecycle() { Map map = this.jdbcMutableAclService .readAclsById(Arrays.asList(getTopParentOid(), getMiddleParentOid(), getChildOid())); assertThat(map).hasSize(3); - // Replace our current objects with their retrieved versions - topParent = (MutableAcl) map.get(getTopParentOid()); - middleParent = (MutableAcl) map.get(getMiddleParentOid()); - child = (MutableAcl) map.get(getChildOid()); + // Get the retrieved versions + MutableAcl retrievedTopParent = (MutableAcl) map.get(getTopParentOid()); + MutableAcl retrievedMiddleParent = (MutableAcl) map.get(getMiddleParentOid()); + MutableAcl retrievedChild = (MutableAcl) map.get(getChildOid()); // Check the retrieved versions has IDs - assertThat(topParent.getId()).isNotNull(); - assertThat(middleParent.getId()).isNotNull(); - assertThat(child.getId()).isNotNull(); + assertThat(retrievedTopParent.getId()).isNotNull(); + assertThat(retrievedMiddleParent.getId()).isNotNull(); + assertThat(retrievedChild.getId()).isNotNull(); // Check their parents were correctly persisted - assertThat(topParent.getParentAcl()).isNull(); - assertThat(middleParent.getParentAcl().getObjectIdentity()).isEqualTo(getTopParentOid()); - assertThat(child.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid()); + assertThat(retrievedTopParent.getParentAcl()).isNull(); + assertThat(retrievedMiddleParent.getParentAcl().getObjectIdentity()).isEqualTo(getTopParentOid()); + assertThat(retrievedChild.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid()); // Check their ACEs were correctly persisted - assertThat(topParent.getEntries()).hasSize(2); - assertThat(middleParent.getEntries()).hasSize(1); - assertThat(child.getEntries()).hasSize(1); + assertThat(retrievedTopParent.getEntries()).hasSize(2); + assertThat(retrievedMiddleParent.getEntries()).hasSize(1); + assertThat(retrievedChild.getEntries()).hasSize(1); // Check the retrieved rights are correct List read = Arrays.asList(BasePermission.READ); List write = Arrays.asList(BasePermission.WRITE); List delete = Arrays.asList(BasePermission.DELETE); List pSid = Arrays.asList((Sid) new PrincipalSid(this.auth)); - assertThat(topParent.isGranted(read, pSid, false)).isTrue(); - assertThat(topParent.isGranted(write, pSid, false)).isFalse(); - assertThat(middleParent.isGranted(delete, pSid, false)).isTrue(); - assertThat(child.isGranted(delete, pSid, false)).isFalse(); - try { - child.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false); - fail("Should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } + assertThat(retrievedTopParent.isGranted(read, pSid, false)).isTrue(); + assertThat(retrievedTopParent.isGranted(write, pSid, false)).isFalse(); + assertThat(retrievedMiddleParent.isGranted(delete, pSid, false)).isTrue(); + assertThat(retrievedChild.isGranted(delete, pSid, false)).isFalse(); + assertThatExceptionOfType(NotFoundException.class) + .isThrownBy(() -> retrievedChild.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false)); // Now check the inherited rights (when not explicitly overridden) also look OK - assertThat(child.isGranted(read, pSid, false)).isTrue(); - assertThat(child.isGranted(write, pSid, false)).isFalse(); - assertThat(child.isGranted(delete, pSid, false)).isFalse(); + assertThat(retrievedChild.isGranted(read, pSid, false)).isTrue(); + assertThat(retrievedChild.isGranted(write, pSid, false)).isFalse(); + assertThat(retrievedChild.isGranted(delete, pSid, false)).isFalse(); // Next change the child so it doesn't inherit permissions from above - child.setEntriesInheriting(false); - this.jdbcMutableAclService.updateAcl(child); - child = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid()); - assertThat(child.isEntriesInheriting()).isFalse(); + retrievedChild.setEntriesInheriting(false); + this.jdbcMutableAclService.updateAcl(retrievedChild); + MutableAcl nonInheritingChild = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid()); + assertThat(nonInheritingChild.isEntriesInheriting()).isFalse(); // Check the child permissions no longer inherit - assertThat(child.isGranted(delete, pSid, true)).isFalse(); - try { - child.isGranted(read, pSid, true); - fail("Should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } - try { - child.isGranted(write, pSid, true); - fail("Should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } + assertThat(nonInheritingChild.isGranted(delete, pSid, true)).isFalse(); + assertThatExceptionOfType(NotFoundException.class) + .isThrownBy(() -> nonInheritingChild.isGranted(read, pSid, true)); + assertThatExceptionOfType(NotFoundException.class) + .isThrownBy(() -> nonInheritingChild.isGranted(write, pSid, true)); // Let's add an identical permission to the child, but it'll appear AFTER the // current permission, so has no impact - child.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true); + nonInheritingChild.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true); // Let's also add another permission to the child - child.insertAce(2, BasePermission.CREATE, new PrincipalSid(this.auth), true); + nonInheritingChild.insertAce(2, BasePermission.CREATE, new PrincipalSid(this.auth), true); // Save the changed child - this.jdbcMutableAclService.updateAcl(child); - child = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid()); - assertThat(child.getEntries()).hasSize(3); + this.jdbcMutableAclService.updateAcl(nonInheritingChild); + MutableAcl retrievedNonInheritingChild = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid()); + assertThat(retrievedNonInheritingChild.getEntries()).hasSize(3); // Output permissions - for (int i = 0; i < child.getEntries().size(); i++) { - System.out.println(child.getEntries().get(i)); + for (int i = 0; i < retrievedNonInheritingChild.getEntries().size(); i++) { + System.out.println(retrievedNonInheritingChild.getEntries().get(i)); } // Check the permissions are as they should be - assertThat(child.isGranted(delete, pSid, true)).isFalse(); // as earlier - // permission + assertThat(retrievedNonInheritingChild.isGranted(delete, pSid, true)).isFalse(); // as + // earlier + // permission // overrode - assertThat(child.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true)).isTrue(); + assertThat(retrievedNonInheritingChild.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true)).isTrue(); // Now check the first ACE (index 0) really is DELETE for our Sid and is // non-granting - AccessControlEntry entry = child.getEntries().get(0); + AccessControlEntry entry = retrievedNonInheritingChild.getEntries().get(0); assertThat(entry.getPermission().getMask()).isEqualTo(BasePermission.DELETE.getMask()); assertThat(entry.getSid()).isEqualTo(new PrincipalSid(this.auth)); assertThat(entry.isGranting()).isFalse(); assertThat(entry.getId()).isNotNull(); // Now delete that first ACE - child.deleteAce(0); + retrievedNonInheritingChild.deleteAce(0); // Save and check it worked - child = this.jdbcMutableAclService.updateAcl(child); - assertThat(child.getEntries()).hasSize(2); - assertThat(child.isGranted(delete, pSid, false)).isTrue(); + MutableAcl savedChild = this.jdbcMutableAclService.updateAcl(retrievedNonInheritingChild); + assertThat(savedChild.getEntries()).hasSize(2); + assertThat(savedChild.isGranted(delete, pSid, false)).isTrue(); SecurityContextHolder.clearContext(); } @@ -267,18 +257,10 @@ public void deleteAclAlsoDeletesChildren() { assertThat(childAcl.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid()); // Delete the mid-parent and test if the child was deleted, as well this.jdbcMutableAclService.deleteAcl(getMiddleParentOid(), true); - try { - this.jdbcMutableAclService.readAclById(getMiddleParentOid()); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } - try { - this.jdbcMutableAclService.readAclById(getChildOid()); - fail("It should have thrown NotFoundException"); - } - catch (NotFoundException expected) { - } + assertThatExceptionOfType(NotFoundException.class) + .isThrownBy(() -> this.jdbcMutableAclService.readAclById(getMiddleParentOid())); + assertThatExceptionOfType(NotFoundException.class) + .isThrownBy(() -> this.jdbcMutableAclService.readAclById(getChildOid())); Acl acl = this.jdbcMutableAclService.readAclById(getTopParentOid()); assertThat(acl).isNotNull(); assertThat(getTopParentOid()).isEqualTo(acl.getObjectIdentity()); @@ -286,34 +268,17 @@ public void deleteAclAlsoDeletesChildren() { @Test public void constructorRejectsNullParameters() { - try { - new JdbcMutableAclService(null, this.lookupStrategy, this.aclCache); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new JdbcMutableAclService(this.dataSource, null, this.aclCache); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException() + .isThrownBy(() -> new JdbcMutableAclService(null, this.lookupStrategy, this.aclCache)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JdbcMutableAclService(this.dataSource, null, this.aclCache)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null)); } @Test public void createAclRejectsNullParameter() { - try { - this.jdbcMutableAclService.createAcl(null); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> this.jdbcMutableAclService.createAcl(null)); } @Test @@ -323,23 +288,14 @@ public void createAclForADuplicateDomainObject() { ObjectIdentity duplicateOid = new ObjectIdentityImpl(TARGET_CLASS, 100L); this.jdbcMutableAclService.createAcl(duplicateOid); // Try to add the same object second time - try { - this.jdbcMutableAclService.createAcl(duplicateOid); - fail("It should have thrown AlreadyExistsException"); - } - catch (AlreadyExistsException expected) { - } + assertThatExceptionOfType(AlreadyExistsException.class) + .isThrownBy(() -> this.jdbcMutableAclService.createAcl(duplicateOid)); } @Test @Transactional public void deleteAclRejectsNullParameters() { - try { - this.jdbcMutableAclService.deleteAcl(null, true); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> this.jdbcMutableAclService.deleteAcl(null, true)); } @Test @@ -351,18 +307,16 @@ public void deleteAclWithChildrenThrowsException() { // Specify the inheritance hierarchy child.setParent(parent); this.jdbcMutableAclService.updateAcl(child); + // switch on FK + this.jdbcMutableAclService.setForeignKeysInDatabase(false); try { - this.jdbcMutableAclService.setForeignKeysInDatabase(false); // switch on FK - // checking in the - // class, not database - this.jdbcMutableAclService.deleteAcl(getTopParentOid(), false); - fail("It should have thrown ChildrenExistException"); - } - catch (ChildrenExistException expected) { + // checking in the class, not database + assertThatExceptionOfType(ChildrenExistException.class) + .isThrownBy(() -> this.jdbcMutableAclService.deleteAcl(getTopParentOid(), false)); } finally { - this.jdbcMutableAclService.setForeignKeysInDatabase(true); // restore to the - // default + // restore to the default + this.jdbcMutableAclService.setForeignKeysInDatabase(true); } } diff --git a/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java b/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java index 3b566e8c920..ad6f8665a6e 100644 --- a/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java +++ b/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java @@ -32,92 +32,36 @@ import org.springframework.security.core.userdetails.User; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatNoException; public class SidTests { @Test public void testPrincipalSidConstructorsRequiredFields() { // Check one String-argument constructor - try { - String string = null; - new PrincipalSid(string); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new PrincipalSid(""); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - new PrincipalSid("johndoe"); - // throws no exception + assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid((String) null)); + assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid("")); + assertThatNoException().isThrownBy(() -> new PrincipalSid("johndoe")); // Check one Authentication-argument constructor - try { - Authentication authentication = null; - new PrincipalSid(authentication); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - Authentication authentication = new TestingAuthenticationToken(null, "password"); - new PrincipalSid(authentication); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - Authentication authentication = new TestingAuthenticationToken("johndoe", "password"); - new PrincipalSid(authentication); - // throws no exception + assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid((Authentication) null)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken(null, "password"))); + assertThatNoException() + .isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken("johndoe", "password"))); } @Test public void testGrantedAuthoritySidConstructorsRequiredFields() { // Check one String-argument constructor - try { - String string = null; - new GrantedAuthoritySid(string); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new GrantedAuthoritySid(""); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new GrantedAuthoritySid("ROLE_TEST"); - } - catch (IllegalArgumentException notExpected) { - fail("It shouldn't have thrown IllegalArgumentException"); - } + assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid((String) null)); + assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid("")); + assertThatNoException().isThrownBy(() -> new GrantedAuthoritySid("ROLE_TEST")); // Check one GrantedAuthority-argument constructor - try { - GrantedAuthority ga = null; - new GrantedAuthoritySid(ga); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - GrantedAuthority ga = new SimpleGrantedAuthority(null); - new GrantedAuthoritySid(ga); - fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST"); - new GrantedAuthoritySid(ga); - } - catch (IllegalArgumentException notExpected) { - fail("It shouldn't have thrown IllegalArgumentException"); - } + assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid((GrantedAuthority) null)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority(null))); + assertThatNoException().isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST"))); } @Test diff --git a/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java b/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java index 4296c72ceca..2bda2d7fac9 100644 --- a/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java +++ b/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java @@ -49,7 +49,7 @@ import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor @@ -112,12 +112,7 @@ public void securedClassMethodAllowsAccessToRoleA() { @Test(expected = AccessDeniedException.class) public void internalPrivateCallIsIntercepted() { SecurityContextHolder.getContext().setAuthentication(this.anne); - try { - this.secured.publicCallsPrivate(); - fail("Expected AccessDeniedException"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.publicCallsPrivate()); this.securedSub.publicCallsPrivate(); } diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java index d5bef694f18..682aa886768 100644 --- a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java +++ b/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java @@ -41,6 +41,7 @@ import org.springframework.security.web.authentication.WebAuthenticationDetails; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -192,20 +193,10 @@ public void authenticateAllAuthenticationIsSuccessful() throws Exception { result = cap.authenticate(token); verify(validator, times(2)).validate(ticket, serviceUrl); token.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); - try { - cap.authenticate(token); - fail("Expected Exception"); - } - catch (IllegalStateException success) { - } + assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token)); cap.setServiceProperties(null); cap.afterPropertiesSet(); - try { - cap.authenticate(token); - fail("Expected Exception"); - } - catch (IllegalStateException success) { - } + assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token)); } @Test(expected = BadCredentialsException.class) diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java index 21278296c5e..9102af096ea 100644 --- a/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java +++ b/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java @@ -31,7 +31,8 @@ import org.springframework.security.core.userdetails.UserDetails; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link CasAuthenticationToken}. @@ -52,44 +53,19 @@ private UserDetails makeUserDetails(final String name) { @Test public void testConstructorRejectsNulls() { - final Assertion assertion = new AssertionImpl("test"); - try { - new CasAuthenticationToken(null, makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new CasAuthenticationToken("key", null, "Password", this.ROLES, makeUserDetails(), assertion); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new CasAuthenticationToken("key", makeUserDetails(), null, this.ROLES, makeUserDetails(), assertion); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, null, assertion); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new CasAuthenticationToken("key", makeUserDetails(), "Password", - AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + Assertion assertion = new AssertionImpl("test"); + assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken(null, makeUserDetails(), + "Password", this.ROLES, makeUserDetails(), assertion)); + assertThatIllegalArgumentException().isThrownBy( + () -> new CasAuthenticationToken("key", null, "Password", this.ROLES, makeUserDetails(), assertion)); + assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), null, + this.ROLES, makeUserDetails(), assertion)); + assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), + "Password", this.ROLES, makeUserDetails(), null)); + assertThatIllegalArgumentException().isThrownBy( + () -> new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, null, assertion)); + assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), + "Password", AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion)); } @Test(expected = IllegalArgumentException.class) @@ -125,12 +101,8 @@ public void testGetters() { @Test public void testNoArgConstructorDoesntExist() { - try { - CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null); - fail("Should have thrown NoSuchMethodException"); - } - catch (NoSuchMethodException expected) { - } + assertThatExceptionOfType(NoSuchMethodException.class) + .isThrownBy(() -> CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null)); } @Test diff --git a/cas/src/test/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCacheTests.java b/cas/src/test/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCacheTests.java index 513158a479d..c4e8b0602ce 100644 --- a/cas/src/test/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCacheTests.java +++ b/cas/src/test/java/org/springframework/security/cas/authentication/EhCacheBasedTicketCacheTests.java @@ -24,7 +24,7 @@ import org.junit.Test; 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 EhCacheBasedTicketCache}. @@ -67,12 +67,7 @@ public void testCacheOperation() throws Exception { @Test public void testStartupDetectsMissingCache() throws Exception { EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache(); - try { - cache.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(cache::afterPropertiesSet); Ehcache myCache = cacheManager.getCache("castickets"); cache.setCache(myCache); assertThat(cache.getCache()).isEqualTo(myCache); diff --git a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java index 825542cb795..c61d372944d 100644 --- a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java +++ b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java @@ -25,7 +25,7 @@ import org.springframework.security.cas.ServiceProperties; 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 CasAuthenticationEntryPoint}. @@ -38,26 +38,16 @@ public class CasAuthenticationEntryPointTests { public void testDetectsMissingLoginFormUrl() throws Exception { CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); ep.setServiceProperties(new ServiceProperties()); - try { - ep.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("loginUrl must be specified"); - } + assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) + .withMessage("loginUrl must be specified"); } @Test public void testDetectsMissingServiceProperties() throws Exception { CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); ep.setLoginUrl("https://cas/login"); - try { - ep.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("serviceProperties must be specified"); - } + assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) + .withMessage("serviceProperties must be specified"); } @Test diff --git a/cas/src/test/java/org/springframework/security/cas/web/ServicePropertiesTests.java b/cas/src/test/java/org/springframework/security/cas/web/ServicePropertiesTests.java index cc61ac93be3..8ec0b40af13 100644 --- a/cas/src/test/java/org/springframework/security/cas/web/ServicePropertiesTests.java +++ b/cas/src/test/java/org/springframework/security/cas/web/ServicePropertiesTests.java @@ -22,7 +22,7 @@ import org.springframework.security.cas.ServiceProperties; 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 ServiceProperties}. @@ -41,19 +41,9 @@ public void detectsMissingService() throws Exception { public void nullServiceWhenAuthenticateAllTokens() throws Exception { ServiceProperties sp = new ServiceProperties(); sp.setAuthenticateAllArtifacts(true); - try { - sp.afterPropertiesSet(); - fail("Expected Exception"); - } - catch (IllegalArgumentException success) { - } + assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet); sp.setAuthenticateAllArtifacts(false); - try { - sp.afterPropertiesSet(); - fail("Expected Exception"); - } - catch (IllegalArgumentException success) { - } + assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet); } @Test diff --git a/config/src/test/java/org/springframework/security/config/InvalidConfigurationTests.java b/config/src/test/java/org/springframework/security/config/InvalidConfigurationTests.java index 7d6134f7f38..63fa324a885 100644 --- a/config/src/test/java/org/springframework/security/config/InvalidConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/InvalidConfigurationTests.java @@ -26,7 +26,7 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests which make sure invalid configurations are rejected by the namespace. In @@ -59,17 +59,14 @@ public void authenticationProviderCannotAppearAtTopLevel() { @Test public void missingAuthenticationManagerGivesSensibleErrorMessage() { - try { - setContext(""); - fail(); - } - catch (BeanCreationException ex) { - Throwable cause = ultimateCause(ex); - assertThat(cause instanceof NoSuchBeanDefinitionException).isTrue(); - NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause; - assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER); - assertThat(nsbe.getMessage()).endsWith(AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE); - } + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> setContext("")).satisfies((ex) -> { + Throwable cause = ultimateCause(ex); + assertThat(cause).isInstanceOf(NoSuchBeanDefinitionException.class); + NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause; + assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER); + assertThat(nsbe.getMessage()).endsWith(AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE); + }); } private Throwable ultimateCause(Throwable ex) { diff --git a/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java b/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java index c80bcc308c6..318bcd90f3a 100644 --- a/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java +++ b/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java @@ -32,8 +32,7 @@ import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.ClassUtils; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -78,15 +77,11 @@ public void constructionSucceeds() { @Test public void pre32SchemaAreNotSupported() { - try { - new InMemoryXmlApplicationContext("" - + " " + "", "3.0.3", - null); - fail("Expected BeanDefinitionParsingException"); - } - catch (BeanDefinitionParsingException expected) { - assertThat(expected.getMessage().contains("You cannot use a spring-security-2.0.xsd")); - } + assertThatExceptionOfType(BeanDefinitionParsingException.class) + .isThrownBy(() -> new InMemoryXmlApplicationContext( + "", + "3.0.3", null)) + .withMessageContaining("You cannot use a spring-security-2.0.xsd"); } // SEC-1868 diff --git a/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java b/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java index 80aeefbd7e3..14044109ec8 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/authentication/AuthenticationManagerBuilderTests.java @@ -54,6 +54,7 @@ import org.springframework.test.web.servlet.MockMvc; 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.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -91,11 +92,8 @@ public void customAuthenticationEventPublisherWithWeb() throws Exception { given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0)); AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep) .inMemoryAuthentication().and().build(); - try { - am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); - } - catch (AuthenticationException success) { - } + assertThatExceptionOfType(AuthenticationException.class) + .isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"))); verify(aep).publishAuthenticationFailure(any(), any()); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java index 5b4ce0106ed..db95afd135e 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfigurationTests.java @@ -110,11 +110,8 @@ public void configureWhenGlobalMethodSecurityHasCustomMetadataSourceThenNoEnabli @Test public void methodSecurityAuthenticationManagerPublishesEvent() { this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire(); - try { - this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar")); - } - catch (AuthenticationException ex) { - } + assertThatExceptionOfType(AuthenticationException.class).isThrownBy( + () -> this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar"))); assertThat(this.events.getEvents()).extracting(Object::getClass) .containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java index de09d8ec07d..60d86e7ec90 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java @@ -45,8 +45,7 @@ import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests { @@ -76,13 +75,9 @@ public void cleanup() { public void securityMappings() { loadConfig(WebSocketSecurityConfig.class); clientInboundChannel().send(message("/user/queue/errors", SimpMessageType.SUBSCRIBE)); - try { - clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE)); - fail("Expected Exception"); - } - catch (MessageDeliveryException expected) { - assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class); - } + assertThatExceptionOfType(MessageDeliveryException.class) + .isThrownBy(() -> clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE))) + .withCauseInstanceOf(AccessDeniedException.class); } private void loadConfig(Class... configs) { diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerTests.java index c44063c2362..98cd855d536 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerTests.java @@ -78,7 +78,7 @@ import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class AbstractSecurityWebSocketMessageBrokerConfigurerTests { @@ -108,13 +108,9 @@ public void cleanup() { public void simpleRegistryMappings() { loadConfig(SockJsSecurityConfig.class); clientInboundChannel().send(message("/permitAll")); - try { - clientInboundChannel().send(message("/denyAll")); - fail("Expected Exception"); - } - catch (MessageDeliveryException expected) { - assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class); - } + assertThatExceptionOfType(MessageDeliveryException.class) + .isThrownBy(() -> clientInboundChannel().send(message("/denyAll"))) + .withCauseInstanceOf(AccessDeniedException.class); } @Test @@ -158,13 +154,8 @@ public void addsCsrfProtectionWhenNoAuthorization() { SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT); Message message = message(headers, "/authentication"); MessageChannel messageChannel = clientInboundChannel(); - try { - messageChannel.send(message); - fail("Expected Exception"); - } - catch (MessageDeliveryException success) { - assertThat(success.getCause()).isInstanceOf(MissingCsrfTokenException.class); - } + assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message)) + .withCauseInstanceOf(MissingCsrfTokenException.class); } @Test @@ -173,13 +164,8 @@ public void csrfProtectionForConnect() { SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT); Message message = message(headers, "/authentication"); MessageChannel messageChannel = clientInboundChannel(); - try { - messageChannel.send(message); - fail("Expected Exception"); - } - catch (MessageDeliveryException success) { - assertThat(success.getCause()).isInstanceOf(MissingCsrfTokenException.class); - } + assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message)) + .withCauseInstanceOf(MissingCsrfTokenException.class); } @Test @@ -236,39 +222,27 @@ public void messagesConnectWebSocketUseCsrfTokenHandshakeInterceptor() throws Ex public void msmsRegistryCustomPatternMatcher() { loadConfig(MsmsRegistryCustomPatternMatcherConfig.class); clientInboundChannel().send(message("/app/a.b")); - try { - clientInboundChannel().send(message("/app/a.b.c")); - fail("Expected Exception"); - } - catch (MessageDeliveryException expected) { - assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class); - } + assertThatExceptionOfType(MessageDeliveryException.class) + .isThrownBy(() -> clientInboundChannel().send(message("/app/a.b.c"))) + .withCauseInstanceOf(AccessDeniedException.class); } @Test public void overrideMsmsRegistryCustomPatternMatcher() { loadConfig(OverrideMsmsRegistryCustomPatternMatcherConfig.class); clientInboundChannel().send(message("/app/a/b")); - try { - clientInboundChannel().send(message("/app/a/b/c")); - fail("Expected Exception"); - } - catch (MessageDeliveryException expected) { - assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class); - } + assertThatExceptionOfType(MessageDeliveryException.class) + .isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c"))) + .withCauseInstanceOf(AccessDeniedException.class); } @Test public void defaultPatternMatcher() { loadConfig(DefaultPatternMatcherConfig.class); clientInboundChannel().send(message("/app/a/b")); - try { - clientInboundChannel().send(message("/app/a/b/c")); - fail("Expected Exception"); - } - catch (MessageDeliveryException expected) { - assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class); - } + assertThatExceptionOfType(MessageDeliveryException.class) + .isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c"))) + .withCauseInstanceOf(AccessDeniedException.class); } @Test @@ -276,13 +250,9 @@ public void customExpression() { loadConfig(CustomExpressionConfig.class); clientInboundChannel().send(message("/denyRob")); this.messageUser = new TestingAuthenticationToken("rob", "password", "ROLE_USER"); - try { - clientInboundChannel().send(message("/denyRob")); - fail("Expected Exception"); - } - catch (MessageDeliveryException expected) { - assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class); - } + assertThatExceptionOfType(MessageDeliveryException.class) + .isThrownBy(() -> clientInboundChannel().send(message("/denyRob"))) + .withCauseInstanceOf(AccessDeniedException.class); } @Test diff --git a/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java index 0165eeb32c2..87263447e1b 100644 --- a/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java @@ -59,7 +59,7 @@ import org.springframework.security.util.FieldUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Ben Alex @@ -174,13 +174,8 @@ public void supportsMethodArgumentsInPointcut() { // someOther(int) should not be matched by someOther(String), but should require // ROLE_USER this.target.someOther(0); - try { - // String version should required admin role - this.target.someOther("somestring"); - fail("Expected AccessDeniedException"); - } - catch (AccessDeniedException expected) { - } + // String version should required admin role + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.target.someOther("somestring")); } @Test @@ -199,12 +194,8 @@ public void supportsBooleanPointcutExpressions() { // String method should not be protected this.target.someOther("somestring"); // All others should require ROLE_USER - try { - this.target.someOther(0); - fail("Expected AuthenticationCredentialsNotFoundException"); - } - catch (AuthenticationCredentialsNotFoundException expected) { - } + assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) + .isThrownBy(() -> this.target.someOther(0)); SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken("user", "password")); this.target.someOther(0); @@ -389,12 +380,7 @@ public void supportsExternalMetadataSource() { // External MDS should take precedence over PreAuthorize SecurityContextHolder.getContext().setAuthentication(this.bob); Foo foo = (Foo) this.appContext.getBean("target"); - try { - foo.foo(new SecurityConfig("A")); - fail("Bob can't invoke admin methods"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A"))); SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password")); foo.foo(new SecurityConfig("A")); @@ -415,12 +401,7 @@ public void supportsCustomAuthenticationManager() { // @formatter:on SecurityContextHolder.getContext().setAuthentication(this.bob); Foo foo = (Foo) this.appContext.getBean("target"); - try { - foo.foo(new SecurityConfig("A")); - fail("Bob can't invoke admin methods"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A"))); SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password")); foo.foo(new SecurityConfig("A")); diff --git a/config/src/test/java/org/springframework/security/config/method/SecuredAnnotationDrivenBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/method/SecuredAnnotationDrivenBeanDefinitionParserTests.java index c7f1cc54a2c..75961648ddd 100644 --- a/config/src/test/java/org/springframework/security/config/method/SecuredAnnotationDrivenBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/method/SecuredAnnotationDrivenBeanDefinitionParserTests.java @@ -36,6 +36,8 @@ import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + /** * @author Ben Alex */ @@ -93,11 +95,8 @@ public void targetIsSerializableBeforeUse() throws Exception { @Test(expected = AccessDeniedException.class) public void targetIsSerializableAfterUse() throws Exception { - try { - this.target.someAdminMethod(); - } - catch (AuthenticationCredentialsNotFoundException expected) { - } + assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) + .isThrownBy(this.target::someAdminMethod); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("u", "p", "ROLE_A")); BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target); chompedTarget.someAdminMethod(); diff --git a/config/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java b/config/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java index 309386fb821..b4992795abf 100644 --- a/config/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java +++ b/config/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java @@ -26,7 +26,7 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext; import org.springframework.security.core.context.SecurityContextHolder; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for SEC-428 (and SEC-1204). @@ -97,12 +97,8 @@ public void securityInterceptorIsAppliedWhenUsedWithAopConfig() { // @formatter:on ITargetObject target = (ITargetObject) this.appContext.getBean("target"); // Check both against interface and class - try { - target.makeLowerCase("TEST"); - fail("AuthenticationCredentialsNotFoundException expected"); - } - catch (AuthenticationCredentialsNotFoundException expected) { - } + assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) + .isThrownBy(() -> target.makeLowerCase("TEST")); target.makeUpperCase("test"); } @@ -128,12 +124,8 @@ public void securityInterceptorIsAppliedWhenUsedWithBeanNameAutoProxyCreator() { // @formatter:on ITargetObject target = (ITargetObject) this.appContext.getBean("target"); - try { - target.makeLowerCase("TEST"); - fail("AuthenticationCredentialsNotFoundException expected"); - } - catch (AuthenticationCredentialsNotFoundException expected) { - } + assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) + .isThrownBy(() -> target.makeLowerCase("TEST")); target.makeUpperCase("test"); } diff --git a/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImplTests.java b/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImplTests.java index 0bd68d19554..fb39ec87e47 100644 --- a/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImplTests.java +++ b/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImplTests.java @@ -25,7 +25,8 @@ import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatNoException; /** * Tests for {@link RoleHierarchyImpl}. @@ -102,48 +103,23 @@ public void testComplexRoleHierarchy() { @Test public void testCyclesInRoleHierarchy() { RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); - try { - roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_A"); - fail("Cycle in role hierarchy was not detected!"); - } - catch (CycleInRoleHierarchyException ex) { - } - try { - roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_A"); - fail("Cycle in role hierarchy was not detected!"); - } - catch (CycleInRoleHierarchyException ex) { - } - try { - roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A"); - fail("Cycle in role hierarchy was not detected!"); - } - catch (CycleInRoleHierarchyException ex) { - } - try { - roleHierarchyImpl.setHierarchy( - "ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B"); - fail("Cycle in role hierarchy was not detected!"); - } - catch (CycleInRoleHierarchyException ex) { - } - try { - roleHierarchyImpl.setHierarchy("ROLE_C > ROLE_B\nROLE_B > ROLE_A\nROLE_A > ROLE_B"); - fail("Cycle in role hierarchy was not detected!"); - } - catch (CycleInRoleHierarchyException ex) { - } + assertThatExceptionOfType(CycleInRoleHierarchyException.class) + .isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_A")); + assertThatExceptionOfType(CycleInRoleHierarchyException.class) + .isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_A")); + assertThatExceptionOfType(CycleInRoleHierarchyException.class) + .isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A")); + assertThatExceptionOfType(CycleInRoleHierarchyException.class).isThrownBy(() -> roleHierarchyImpl + .setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B")); + assertThatExceptionOfType(CycleInRoleHierarchyException.class) + .isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_C > ROLE_B\nROLE_B > ROLE_A\nROLE_A > ROLE_B")); } @Test public void testNoCyclesInRoleHierarchy() { RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); - try { - roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D"); - } - catch (CycleInRoleHierarchyException ex) { - fail("A cycle in role hierarchy was incorrectly detected!"); - } + assertThatNoException().isThrownBy(() -> roleHierarchyImpl + .setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D")); } // SEC-863 diff --git a/core/src/test/java/org/springframework/security/access/intercept/AfterInvocationProviderManagerTests.java b/core/src/test/java/org/springframework/security/access/intercept/AfterInvocationProviderManagerTests.java index f6fc8ec9222..e2e3f0a25a8 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/AfterInvocationProviderManagerTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/AfterInvocationProviderManagerTests.java @@ -31,7 +31,7 @@ import org.springframework.security.util.SimpleMethodInvocation; 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 AfterInvocationProviderManager}. @@ -72,13 +72,7 @@ public void testCorrectOperation() throws Exception { public void testRejectsEmptyProvidersList() { AfterInvocationProviderManager manager = new AfterInvocationProviderManager(); List list = new Vector(); - try { - manager.setProviders(list); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } + assertThatIllegalArgumentException().isThrownBy(() -> manager.setProviders(list)); } @Test @@ -88,25 +82,13 @@ public void testRejectsNonAfterInvocationProviders() { list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1"))); list.add(45); list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3"))); - try { - manager.setProviders(list); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } + assertThatIllegalArgumentException().isThrownBy(() -> manager.setProviders(list)); } @Test public void testRejectsNullProvidersList() throws Exception { AfterInvocationProviderManager manager = new AfterInvocationProviderManager(); - try { - manager.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } + assertThatIllegalArgumentException().isThrownBy(manager::afterPropertiesSet); } @Test diff --git a/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java b/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java index 31503300c38..36050c0e1ac 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/RunAsManagerImplTests.java @@ -26,6 +26,7 @@ import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.fail; /** @@ -96,12 +97,7 @@ public void testReturnsAdditionalGrantedAuthorities() { @Test public void testStartupDetectsMissingKey() throws Exception { RunAsManagerImpl runAs = new RunAsManagerImpl(); - try { - runAs.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(runAs::afterPropertiesSet); } @Test diff --git a/core/src/test/java/org/springframework/security/access/intercept/RunAsUserTokenTests.java b/core/src/test/java/org/springframework/security/access/intercept/RunAsUserTokenTests.java index b8b151b27a4..2836038433e 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/RunAsUserTokenTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/RunAsUserTokenTests.java @@ -22,7 +22,7 @@ import org.springframework.security.core.authority.AuthorityUtils; 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 RunAsUserToken}. @@ -52,14 +52,8 @@ public void testGetters() { @Test public void testNoArgConstructorDoesntExist() { - Class clazz = RunAsUserToken.class; - try { - clazz.getDeclaredConstructor((Class[]) null); - fail("Should have thrown NoSuchMethodException"); - } - catch (NoSuchMethodException expected) { - assertThat(true).isTrue(); - } + assertThatExceptionOfType(NoSuchMethodException.class) + .isThrownBy(() -> RunAsUserToken.class.getDeclaredConstructor((Class[]) null)); } @Test diff --git a/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptorTests.java b/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptorTests.java index aa8ff613592..01ae098bda3 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptorTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptorTests.java @@ -47,7 +47,7 @@ import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -251,12 +251,8 @@ public void callIsntMadeWhenAccessDecisionManagerRejectsAccess() { given(this.authman.authenticate(this.token)).willReturn(this.token); willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(any(Authentication.class), any(MethodInvocation.class), any(List.class)); - try { - this.advisedTarget.makeUpperCase("HELLO"); - fail("Expected Exception"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> this.advisedTarget.makeUpperCase("HELLO")); verify(this.eventPublisher).publishEvent(any(AuthorizationFailureEvent.class)); } @@ -297,12 +293,7 @@ public void runAsReplacementCleansAfterException() { this.interceptor.setRunAsManager(runAs); mdsReturnsUserRole(); given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken); - try { - this.advisedTarget.makeUpperCase("hello"); - fail("Expected Exception"); - } - catch (RuntimeException success) { - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.advisedTarget.makeUpperCase("hello")); // Check we've changed back assertThat(SecurityContextHolder.getContext()).isSameAs(ctx); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token); @@ -323,12 +314,7 @@ public void afterInvocationManagerIsNotInvokedIfExceptionIsRaised() throws Throw AfterInvocationManager aim = mock(AfterInvocationManager.class); this.interceptor.setAfterInvocationManager(aim); given(mi.proceed()).willThrow(new Throwable()); - try { - this.interceptor.invoke(mi); - fail("Expected exception"); - } - catch (Throwable expected) { - } + assertThatExceptionOfType(Throwable.class).isThrownBy(() -> this.interceptor.invoke(mi)); verifyZeroInteractions(aim); } diff --git a/core/src/test/java/org/springframework/security/access/intercept/aspectj/AspectJMethodSecurityInterceptorTests.java b/core/src/test/java/org/springframework/security/access/intercept/aspectj/AspectJMethodSecurityInterceptorTests.java index 08ef48c501e..10f4179554a 100644 --- a/core/src/test/java/org/springframework/security/access/intercept/aspectj/AspectJMethodSecurityInterceptorTests.java +++ b/core/src/test/java/org/springframework/security/access/intercept/aspectj/AspectJMethodSecurityInterceptorTests.java @@ -45,7 +45,7 @@ import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -127,12 +127,8 @@ public void callbackIsInvokedWhenPermissionGranted() throws Throwable { public void callbackIsNotInvokedWhenPermissionDenied() { willThrow(new AccessDeniedException("denied")).given(this.adm).decide(any(), any(), any()); SecurityContextHolder.getContext().setAuthentication(this.token); - try { - this.interceptor.invoke(this.joinPoint, this.aspectJCallback); - fail("Expected AccessDeniedException"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class) + .isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback)); verify(this.aspectJCallback, never()).proceedWithObject(); } @@ -156,12 +152,8 @@ public void afterInvocationManagerIsNotInvokedIfExceptionIsRaised() { AfterInvocationManager aim = mock(AfterInvocationManager.class); this.interceptor.setAfterInvocationManager(aim); given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException()); - try { - this.interceptor.invoke(this.joinPoint, this.aspectJCallback); - fail("Expected exception"); - } - catch (RuntimeException expected) { - } + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback)); verifyZeroInteractions(aim); } @@ -178,12 +170,8 @@ public void invokeWithAspectJCallbackRunAsReplacementCleansAfterException() { this.interceptor.setRunAsManager(runAs); given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken); given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException()); - try { - this.interceptor.invoke(this.joinPoint, this.aspectJCallback); - fail("Expected Exception"); - } - catch (RuntimeException success) { - } + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback)); // Check we've changed back assertThat(SecurityContextHolder.getContext()).isSameAs(ctx); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token); @@ -202,12 +190,7 @@ public void invokeRunAsReplacementCleansAfterException() throws Throwable { this.interceptor.setRunAsManager(runAs); given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken); given(this.joinPoint.proceed()).willThrow(new RuntimeException()); - try { - this.interceptor.invoke(this.joinPoint); - fail("Expected Exception"); - } - catch (RuntimeException success) { - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(this.joinPoint)); // Check we've changed back assertThat(SecurityContextHolder.getContext()).isSameAs(ctx); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token); diff --git a/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java b/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java index b0cfe45d608..2445afffa7a 100644 --- a/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java @@ -17,6 +17,7 @@ package org.springframework.security.access.vote; import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.Vector; @@ -28,7 +29,7 @@ import org.springframework.security.core.Authentication; 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 AbstractAccessDecisionManager}. @@ -86,23 +87,12 @@ public void testProperlyStoresListOfVoters() { @Test public void testRejectsEmptyList() { - List list = new Vector(); - try { - new MockDecisionManagerImpl(list); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(Collections.emptyList())); } @Test public void testRejectsNullVotersList() { - try { - new MockDecisionManagerImpl(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(null)); } @Test @@ -113,12 +103,7 @@ public void testRoleVoterAlwaysReturnsTrueToSupports() { @Test public void testWillNotStartIfDecisionVotersNotSet() { - try { - new MockDecisionManagerImpl(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(null)); } private class MockDecisionManagerImpl extends AbstractAccessDecisionManager { diff --git a/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java b/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java index 595bd55fc9a..052f9a282ef 100644 --- a/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/AuthenticatedVoterTests.java @@ -30,7 +30,7 @@ import org.springframework.security.core.authority.AuthorityUtils; 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 AuthenticatedVoter}. @@ -82,12 +82,7 @@ public void testRememberMeWorks() { @Test public void testSetterRejectsNull() { AuthenticatedVoter voter = new AuthenticatedVoter(); - try { - voter.setAuthenticationTrustResolver(null); - fail("Expected IAE"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> voter.setAuthenticationTrustResolver(null)); } @Test diff --git a/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java b/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java index 943d31da0af..81e7b5c2f42 100644 --- a/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java +++ b/core/src/test/java/org/springframework/security/access/vote/UnanimousBasedTests.java @@ -28,7 +28,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken; 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 UnanimousBased}. @@ -73,12 +73,7 @@ public void testOneAffirmativeVoteOneDenyVoteOneAbstainVoteDeniesAccess() { TestingAuthenticationToken auth = makeTestToken(); UnanimousBased mgr = makeDecisionManager(); List config = SecurityConfig.createList(new String[] { "ROLE_1", "DENY_FOR_SURE" }); - try { - mgr.decide(auth, new Object(), config); - fail("Should have thrown AccessDeniedException"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config)); } @Test @@ -94,12 +89,7 @@ public void testOneDenyVoteTwoAbstainVotesDeniesAccess() { TestingAuthenticationToken auth = makeTestToken(); UnanimousBased mgr = makeDecisionManager(); List config = SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE"); - try { - mgr.decide(auth, new Object(), config); - fail("Should have thrown AccessDeniedException"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config)); } @Test @@ -116,12 +106,7 @@ public void testThreeAbstainVotesDeniesAccessWithDefault() { UnanimousBased mgr = makeDecisionManager(); assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default List config = SecurityConfig.createList("IGNORED_BY_ALL"); - try { - mgr.decide(auth, new Object(), config); - fail("Should have thrown AccessDeniedException"); - } - catch (AccessDeniedException expected) { - } + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config)); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java b/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java index b75f9dcf8cb..987dc5b63ac 100644 --- a/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java +++ b/core/src/test/java/org/springframework/security/authentication/ProviderManagerTests.java @@ -28,7 +28,7 @@ import org.springframework.security.core.AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -171,12 +171,8 @@ public void authenticationExceptionIsIgnoredIfLaterProviderAuthenticates() { public void authenticationExceptionIsRethrownIfNoLaterProviderAuthenticates() { ProviderManager mgr = new ProviderManager(Arrays .asList(createProviderWhichThrows(new BadCredentialsException("")), createProviderWhichReturns(null))); - try { - mgr.authenticate(mock(Authentication.class)); - fail("Expected BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class) + .isThrownBy(() -> mgr.authenticate(mock(Authentication.class))); } // SEC-546 @@ -186,12 +182,8 @@ public void accountStatusExceptionPreventsCallsToSubsequentProviders() { }); AuthenticationProvider otherProvider = mock(AuthenticationProvider.class); ProviderManager authMgr = new ProviderManager(Arrays.asList(iThrowAccountStatusException, otherProvider)); - try { - authMgr.authenticate(mock(Authentication.class)); - fail("Expected AccountStatusException"); - } - catch (AccountStatusException expected) { - } + assertThatExceptionOfType(AccountStatusException.class) + .isThrownBy(() -> authMgr.authenticate(mock(Authentication.class))); verifyNoInteractions(otherProvider); } @@ -212,12 +204,8 @@ public void parentIsNotCalledIfAccountStatusExceptionIsThrown() { }); AuthenticationManager parent = mock(AuthenticationManager.class); ProviderManager mgr = new ProviderManager(Collections.singletonList(iThrowAccountStatusException), parent); - try { - mgr.authenticate(mock(Authentication.class)); - fail("Expected exception"); - } - catch (AccountStatusException expected) { - } + assertThatExceptionOfType(AccountStatusException.class) + .isThrownBy(() -> mgr.authenticate(mock(Authentication.class))); verifyNoInteractions(parent); } @@ -232,13 +220,8 @@ public void providerNotFoundFromParentIsIgnored() { ProviderManager mgr = new ProviderManager( Collections.singletonList(createProviderWhichThrows(new BadCredentialsException(""))), parent); mgr.setAuthenticationEventPublisher(publisher); - try { - mgr.authenticate(authReq); - fail("Expected exception"); - } - catch (BadCredentialsException expected) { - verify(publisher).publishAuthenticationFailure(expected, authReq); - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq)) + .satisfies((ex) -> verify(publisher).publishAuthenticationFailure(ex, authReq)); } @Test @@ -251,15 +234,10 @@ public void authenticationExceptionFromParentOverridesPreviousOnes() { mgr.setAuthenticationEventPublisher(publisher); // Set a provider that throws an exception - this is the exception we expect to be // propagated - final BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent"); + BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent"); given(parent.authenticate(authReq)).willThrow(expected); - try { - mgr.authenticate(authReq); - fail("Expected exception"); - } - catch (BadCredentialsException ex) { - assertThat(ex).isSameAs(expected); - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq)) + .isSameAs(expected); } @Test @@ -271,13 +249,7 @@ public void statusExceptionIsPublished() { final Authentication authReq = mock(Authentication.class); AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class); mgr.setAuthenticationEventPublisher(publisher); - try { - mgr.authenticate(authReq); - fail("Expected exception"); - } - catch (LockedException ex) { - assertThat(ex).isSameAs(expected); - } + assertThatExceptionOfType(LockedException.class).isThrownBy(() -> mgr.authenticate(authReq)); verify(publisher).publishAuthenticationFailure(expected, authReq); } @@ -287,13 +259,9 @@ public void providerThrowsInternalAuthenticationServiceException() { InternalAuthenticationServiceException expected = new InternalAuthenticationServiceException("Expected"); ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(expected), createProviderWhichThrows(new BadCredentialsException("Oops"))), null); - final Authentication authReq = mock(Authentication.class); - try { - mgr.authenticate(authReq); - fail("Expected Exception"); - } - catch (InternalAuthenticationServiceException success) { - } + Authentication authReq = mock(Authentication.class); + assertThatExceptionOfType(InternalAuthenticationServiceException.class) + .isThrownBy(() -> mgr.authenticate(authReq)); } // gh-6281 @@ -307,13 +275,8 @@ public void authenticateWhenFailsInParentAndPublishesThenChildDoesNotPublish() { parentMgr.setAuthenticationEventPublisher(publisher); childMgr.setAuthenticationEventPublisher(publisher); final Authentication authReq = mock(Authentication.class); - try { - childMgr.authenticate(authReq); - fail("Expected exception"); - } - catch (BadCredentialsException ex) { - assertThat(ex).isSameAs(badCredentialsExParent); - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> childMgr.authenticate(authReq)) + .isSameAs(badCredentialsExParent); verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq); // Parent // publishes verifyNoMoreInteractions(publisher); // Child should not publish (duplicate event) diff --git a/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java index 61cd51ecef0..5f1b830fee6 100644 --- a/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/authentication/UsernamePasswordAuthenticationTokenTests.java @@ -21,7 +21,7 @@ import org.springframework.security.core.authority.AuthorityUtils; 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 UsernamePasswordAuthenticationToken}. @@ -32,29 +32,25 @@ public class UsernamePasswordAuthenticationTokenTests { @Test public void authenticatedPropertyContractIsSatisfied() { - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", + UsernamePasswordAuthenticationToken grantedToken = new UsernamePasswordAuthenticationToken("Test", "Password", AuthorityUtils.NO_AUTHORITIES); // check default given we passed some GrantedAuthorty[]s (well, we passed empty // list) - assertThat(token.isAuthenticated()).isTrue(); + assertThat(grantedToken.isAuthenticated()).isTrue(); // check explicit set to untrusted (we can safely go from trusted to untrusted, // but not the reverse) - token.setAuthenticated(false); - assertThat(!token.isAuthenticated()).isTrue(); + grantedToken.setAuthenticated(false); + assertThat(!grantedToken.isAuthenticated()).isTrue(); // Now let's create a UsernamePasswordAuthenticationToken without any // GrantedAuthorty[]s (different constructor) - token = new UsernamePasswordAuthenticationToken("Test", "Password"); - assertThat(!token.isAuthenticated()).isTrue(); + UsernamePasswordAuthenticationToken noneGrantedToken = new UsernamePasswordAuthenticationToken("Test", + "Password"); + assertThat(!noneGrantedToken.isAuthenticated()).isTrue(); // check we're allowed to still set it to untrusted - token.setAuthenticated(false); - assertThat(!token.isAuthenticated()).isTrue(); + noneGrantedToken.setAuthenticated(false); + assertThat(!noneGrantedToken.isAuthenticated()).isTrue(); // check denied changing it to trusted - try { - token.setAuthenticated(true); - fail("Should have prohibited setAuthenticated(true)"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> noneGrantedToken.setAuthenticated(true)); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationProviderTests.java index 808cb363479..9259559c2a1 100644 --- a/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationProviderTests.java @@ -26,7 +26,8 @@ import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link AnonymousAuthenticationProvider}. @@ -40,22 +41,12 @@ public void testDetectsAnInvalidKey() { AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty"); AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("WRONG_KEY", "Test", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); - try { - aap.authenticate(token); - fail("Should have thrown BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> aap.authenticate(token)); } @Test public void testDetectsMissingKey() { - try { - new AnonymousAuthenticationProvider(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationProvider(null)); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java index 298a43e633d..1debbc4981c 100644 --- a/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/authentication/anonymous/AnonymousAuthenticationTokenTests.java @@ -27,7 +27,8 @@ import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link AnonymousAuthenticationToken}. @@ -40,30 +41,11 @@ public class AnonymousAuthenticationTokenTests { @Test public void testConstructorRejectsNulls() { - try { - new AnonymousAuthenticationToken(null, "Test", ROLES_12); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new AnonymousAuthenticationToken("key", null, ROLES_12); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new AnonymousAuthenticationToken("key", "Test", null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken(null, "Test", ROLES_12)); + assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken("key", null, ROLES_12)); + assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken("key", "Test", null)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES)); } @Test @@ -85,13 +67,8 @@ public void testGetters() { @Test public void testNoArgConstructorDoesntExist() { - Class clazz = AnonymousAuthenticationToken.class; - try { - clazz.getDeclaredConstructor((Class[]) null); - fail("Should have thrown NoSuchMethodException"); - } - catch (NoSuchMethodException expected) { - } + assertThatExceptionOfType(NoSuchMethodException.class) + .isThrownBy(() -> AnonymousAuthenticationToken.class.getDeclaredConstructor((Class[]) null)); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java index b045b798bb2..37263d90f25 100644 --- a/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/dao/DaoAuthenticationProviderTests.java @@ -50,6 +50,7 @@ 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.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -77,12 +78,7 @@ public void testAuthenticateFailsForIncorrectPasswordCase() { DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token)); } @Test @@ -92,12 +88,8 @@ public void testReceivedBadCredentialsWhenCredentialsNotProvided() { provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null); - try { - provider.authenticate(authenticationToken); - fail("Expected BadCredenialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class) + .isThrownBy(() -> provider.authenticate(authenticationToken)); } @Test @@ -106,12 +98,7 @@ public void testAuthenticateFailsIfAccountExpired() { DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountExpired()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown AccountExpiredException"); - } - catch (AccountExpiredException expected) { - } + assertThatExceptionOfType(AccountExpiredException.class).isThrownBy(() -> provider.authenticate(token)); } @Test @@ -120,35 +107,20 @@ public void testAuthenticateFailsIfAccountLocked() { DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountLocked()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown LockedException"); - } - catch (LockedException expected) { - } + assertThatExceptionOfType(LockedException.class).isThrownBy(() -> provider.authenticate(token)); } @Test public void testAuthenticateFailsIfCredentialsExpired() { - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal"); DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserPeterCredentialsExpired()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown CredentialsExpiredException"); - } - catch (CredentialsExpiredException expected) { - } + assertThatExceptionOfType(CredentialsExpiredException.class) + .isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("peter", "opal"))); // Check that wrong password causes BadCredentialsException, rather than // CredentialsExpiredException - token = new UsernamePasswordAuthenticationToken("peter", "wrong_password"); - try { - provider.authenticate(token); - fail("Should have thrown BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy( + () -> provider.authenticate(new UsernamePasswordAuthenticationToken("peter", "wrong_password"))); } @Test @@ -157,12 +129,7 @@ public void testAuthenticateFailsIfUserDisabled() { DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserPeter()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown DisabledException"); - } - catch (DisabledException expected) { - } + assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> provider.authenticate(token)); } @Test @@ -171,12 +138,8 @@ public void testAuthenticateFailsWhenAuthenticationDaoHasBackendFailure() { DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceSimulateBackendError()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown InternalAuthenticationServiceException"); - } - catch (InternalAuthenticationServiceException expected) { - } + assertThatExceptionOfType(InternalAuthenticationServiceException.class) + .isThrownBy(() -> provider.authenticate(token)); } @Test @@ -185,12 +148,7 @@ public void testAuthenticateFailsWithEmptyUsername() { DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token)); } @Test @@ -199,12 +157,7 @@ public void testAuthenticateFailsWithInvalidPassword() { DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token)); } @Test @@ -215,12 +168,7 @@ public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundException // UsernameNotFoundExceptions provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown UsernameNotFoundException"); - } - catch (UsernameNotFoundException expected) { - } + assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token)); } @Test @@ -230,12 +178,7 @@ public void testAuthenticateFailsWithInvalidUsernameAndHideUserNotFoundException assertThat(provider.isHideUserNotFoundExceptions()).isTrue(); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token)); } @Test @@ -245,19 +188,9 @@ public void testAuthenticateFailsWithInvalidUsernameAndChangePasswordEncoder() { assertThat(provider.isHideUserNotFoundExceptions()).isTrue(); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token)); provider.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()); - try { - provider.authenticate(token); - fail("Should have thrown BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token)); } @Test @@ -266,12 +199,7 @@ public void testAuthenticateFailsWithMixedCaseUsernameIfDefaultChanged() { DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); - try { - provider.authenticate(token); - fail("Should have thrown BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token)); } @Test @@ -389,14 +317,8 @@ public void testDetectsNullBeingReturnedFromAuthenticationDao() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala"); DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceReturnsNull()); - try { - provider.authenticate(token); - fail("Should have thrown AuthenticationServiceException"); - } - catch (AuthenticationServiceException expected) { - assertThat("UserDetailsService returned null, which is an interface contract violation") - .isEqualTo(expected.getMessage()); - } + assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(token)) + .withMessage("UserDetailsService returned null, which is an interface contract violation"); } @Test @@ -436,12 +358,7 @@ public void testGoesBackToAuthenticationDaoToObtainLatestPasswordIfCachedPasswor @Test public void testStartupFailsIfNoAuthenticationDao() throws Exception { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); - try { - provider.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet); } @Test @@ -450,12 +367,7 @@ public void testStartupFailsIfNoUserCacheSet() throws Exception { provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); assertThat(provider.getUserCache().getClass()).isEqualTo(NullUserCache.class); provider.setUserCache(null); - try { - provider.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet); } @Test @@ -486,12 +398,7 @@ public void testUserNotFoundEncodesPassword() throws Exception { provider.setPasswordEncoder(encoder); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.afterPropertiesSet(); - try { - provider.authenticate(token); - fail("Expected Exception"); - } - catch (UsernameNotFoundException success) { - } + assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token)); // ensure encoder invoked w/ non-null strings since PasswordEncoder impls may fail // if encoded password is null verify(encoder).matches(isA(String.class), isA(String.class)); @@ -507,12 +414,7 @@ public void testUserNotFoundBCryptPasswordEncoder() { MockUserDetailsServiceUserRod userDetailsService = new MockUserDetailsServiceUserRod(); userDetailsService.password = encoder.encode((CharSequence) token.getCredentials()); provider.setUserDetailsService(userDetailsService); - try { - provider.authenticate(token); - fail("Expected Exception"); - } - catch (UsernameNotFoundException success) { - } + assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token)); } @Test @@ -521,12 +423,7 @@ public void testUserNotFoundDefaultEncoder() { DaoAuthenticationProvider provider = createProvider(); provider.setHideUserNotFoundExceptions(false); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); - try { - provider.authenticate(token); - fail("Expected Exception"); - } - catch (UsernameNotFoundException success) { - } + assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token)); } /** @@ -554,12 +451,8 @@ public void IGNOREtestSec2056() { List userNotFoundTimes = new ArrayList<>(sampleSize); for (int i = 0; i < sampleSize; i++) { long start = System.currentTimeMillis(); - try { - provider.authenticate(notFoundUser); - fail("Expected Exception"); - } - catch (UsernameNotFoundException success) { - } + assertThatExceptionOfType(UsernameNotFoundException.class) + .isThrownBy(() -> provider.authenticate(notFoundUser)); userNotFoundTimes.add(System.currentTimeMillis() - start); } double userFoundAvg = avg(userFoundTimes); @@ -584,12 +477,7 @@ public void testUserNotFoundNullCredentials() { provider.setHideUserNotFoundExceptions(false); provider.setPasswordEncoder(encoder); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); - try { - provider.authenticate(token); - fail("Expected Exception"); - } - catch (UsernameNotFoundException success) { - } + assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token)); verify(encoder, times(0)).matches(anyString(), anyString()); } diff --git a/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java b/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java index d843593f5c5..3671f53ca47 100644 --- a/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java +++ b/core/src/test/java/org/springframework/security/authentication/event/AuthenticationEventTests.java @@ -24,7 +24,7 @@ import org.springframework.security.core.AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link AbstractAuthenticationEvent} and its subclasses. @@ -59,22 +59,13 @@ public void testAbstractAuthenticationFailureEvent() { @Test public void testRejectsNullAuthentication() { AuthenticationException exception = new DisabledException("TEST"); - try { - new AuthenticationFailureDisabledEvent(null, exception); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new AuthenticationFailureDisabledEvent(null, exception)); } @Test public void testRejectsNullAuthenticationException() { - try { - new AuthenticationFailureDisabledEvent(getAuthentication(), null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException() + .isThrownBy(() -> new AuthenticationFailureDisabledEvent(getAuthentication(), null)); } } diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java index e075c6184d2..217daa7d530 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.java @@ -44,7 +44,7 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; @@ -112,23 +112,15 @@ public void authenticateSuccess() { @Test public void authenticateBadPassword() { - try { - this.provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf")); - fail("LoginException should have been thrown for the bad password"); - } - catch (AuthenticationException success) { - } + assertThatExceptionOfType(AuthenticationException.class) + .isThrownBy(() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"))); verifyFailedLogin(); } @Test public void authenticateBadUser() { - try { - this.provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password")); - fail("LoginException should have been thrown for the bad user"); - } - catch (AuthenticationException success) { - } + assertThatExceptionOfType(AuthenticationException.class).isThrownBy( + () -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"))); verifyFailedLogin(); } diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java index 6f59331bbf5..01ce3ef9f8b 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java @@ -46,6 +46,8 @@ import org.springframework.security.core.session.SessionDestroyedEvent; 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.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -73,12 +75,8 @@ public void setUp() { @Test public void testBadPassword() { - try { - this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf")); - fail("LoginException should have been thrown for the bad password"); - } - catch (AuthenticationException ex) { - } + assertThatExceptionOfType(AuthenticationException.class).isThrownBy( + () -> this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"))); assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull(); assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null") .isNotNull(); @@ -87,12 +85,8 @@ public void testBadPassword() { @Test public void testBadUser() { - try { - this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password")); - fail("LoginException should have been thrown for the bad user"); - } - catch (AuthenticationException ex) { - } + assertThatExceptionOfType(AuthenticationException.class).isThrownBy( + () -> this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"))); assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull(); assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null") .isNotNull(); @@ -115,13 +109,8 @@ public void detectsMissingLoginConfig() throws Exception { myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters()); myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers()); myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName()); - try { - myJaasProvider.afterPropertiesSet(); - fail("Should have thrown ApplicationContextException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage().startsWith("loginConfig must be set on")).isTrue(); - } + assertThatIllegalArgumentException().isThrownBy(() -> myJaasProvider.afterPropertiesSet()) + .withMessageStartingWith("loginConfig must be set on"); } // SEC-1239 @@ -160,21 +149,11 @@ public void detectsMissingLoginContextName() throws Exception { myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers()); myJaasProvider.setLoginConfig(this.jaasProvider.getLoginConfig()); myJaasProvider.setLoginContextName(null); - try { - myJaasProvider.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).startsWith("loginContextName must be set on"); - } + assertThatIllegalArgumentException().isThrownBy(myJaasProvider::afterPropertiesSet) + .withMessageStartingWith("loginContextName must be set on"); myJaasProvider.setLoginContextName(""); - try { - myJaasProvider.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage().startsWith("loginContextName must be set on")); - } + assertThatIllegalArgumentException().isThrownBy(myJaasProvider::afterPropertiesSet) + .withMessageStartingWith("loginContextName must be set on"); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java index 8090324520b..fbe3c9e792e 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/SecurityContextLoginModuleTests.java @@ -31,7 +31,7 @@ import org.springframework.security.core.context.SecurityContextHolder; 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 SecurityContextLoginModule @@ -71,12 +71,7 @@ public void testAbort() throws Exception { @Test public void testLoginException() { - try { - this.module.login(); - fail("LoginException expected, there is no Authentication in the SecurityContext"); - } - catch (LoginException ex) { - } + assertThatExceptionOfType(LoginException.class).isThrownBy(this.module::login); } @Test @@ -101,13 +96,8 @@ public void testLogout() throws Exception { @Test public void testNullAuthenticationInSecurityContext() { - try { - SecurityContextHolder.getContext().setAuthentication(null); - this.module.login(); - fail("LoginException expected, the authentication is null in the SecurityContext"); - } - catch (Exception ex) { - } + SecurityContextHolder.getContext().setAuthentication(null); + assertThatExceptionOfType(Exception.class).isThrownBy(this.module::login); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java b/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java index a52f73ace00..d279a30e074 100644 --- a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java +++ b/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationManagerImplTests.java @@ -23,7 +23,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -47,12 +47,7 @@ public void testFailedAuthenticationReturnsRemoteAuthenticationException() { @Test public void testStartupChecksAuthenticationManagerSet() throws Exception { RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl(); - try { - manager.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(manager::afterPropertiesSet); manager.setAuthenticationManager(mock(AuthenticationManager.class)); manager.afterPropertiesSet(); } diff --git a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java index 42b37a73c85..2d7cdd19951 100644 --- a/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/rcp/RemoteAuthenticationProviderTests.java @@ -26,7 +26,8 @@ import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link RemoteAuthenticationProvider}. @@ -39,12 +40,8 @@ public class RemoteAuthenticationProviderTests { public void testExceptionsGetPassedBackToCaller() { RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false)); - try { - provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password")); - fail("Should have thrown RemoteAuthenticationException"); - } - catch (RemoteAuthenticationException expected) { - } + assertThatExceptionOfType(RemoteAuthenticationException.class) + .isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"))); } @Test @@ -57,12 +54,7 @@ public void testGettersSetters() { @Test public void testStartupChecksAuthenticationManagerSet() throws Exception { RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); - try { - provider.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet); provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true)); provider.afterPropertiesSet(); } @@ -81,12 +73,8 @@ public void testSuccessfulAuthenticationCreatesObject() { public void testNullCredentialsDoesNotCauseNullPointerException() { RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false)); - try { - provider.authenticate(new UsernamePasswordAuthenticationToken("rod", null)); - fail("Expected Exception"); - } - catch (RemoteAuthenticationException success) { - } + assertThatExceptionOfType(RemoteAuthenticationException.class) + .isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("rod", null))); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java index 169e9802cdc..428fe348bb0 100644 --- a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationProviderTests.java @@ -26,7 +26,8 @@ import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link RememberMeAuthenticationProvider}. @@ -40,22 +41,12 @@ public void testDetectsAnInvalidKey() { RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty"); RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("WRONG_KEY", "Test", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); - try { - aap.authenticate(token); - fail("Should have thrown BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> aap.authenticate(token)); } @Test public void testDetectsMissingKey() { - try { - new RememberMeAuthenticationProvider(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new RememberMeAuthenticationProvider(null)); } @Test diff --git a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java index 6bdf73bd5d8..4e2bd6c5988 100644 --- a/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/authentication/rememberme/RememberMeAuthenticationTokenTests.java @@ -16,7 +16,7 @@ package org.springframework.security.authentication.rememberme; -import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.junit.Test; @@ -27,7 +27,7 @@ import org.springframework.security.core.authority.AuthorityUtils; 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 RememberMeAuthenticationToken}. @@ -40,26 +40,11 @@ public class RememberMeAuthenticationTokenTests { @Test public void testConstructorRejectsNulls() { - try { - new RememberMeAuthenticationToken(null, "Test", ROLES_12); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new RememberMeAuthenticationToken("key", null, ROLES_12); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - List authsContainingNull = new ArrayList<>(); - authsContainingNull.add(null); - new RememberMeAuthenticationToken("key", "Test", authsContainingNull); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException() + .isThrownBy(() -> new RememberMeAuthenticationToken(null, "Test", ROLES_12)); + assertThatIllegalArgumentException().isThrownBy(() -> new RememberMeAuthenticationToken("key", null, ROLES_12)); + assertThatIllegalArgumentException().isThrownBy( + () -> new RememberMeAuthenticationToken("key", "Test", Arrays.asList((GrantedAuthority) null))); } @Test diff --git a/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleRoles2GrantedAuthoritiesMapperTests.java b/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleRoles2GrantedAuthoritiesMapperTests.java index da948dd54e4..24ba61759f9 100644 --- a/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleRoles2GrantedAuthoritiesMapperTests.java +++ b/core/src/test/java/org/springframework/security/core/authority/mapping/SimpleRoles2GrantedAuthoritiesMapperTests.java @@ -26,7 +26,8 @@ import org.springframework.security.core.GrantedAuthority; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatNoException; /** * @author TSARDD @@ -39,26 +40,13 @@ public final void testAfterPropertiesSetConvertToUpperAndLowerCase() { SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper(); mapper.setConvertAttributeToLowerCase(true); mapper.setConvertAttributeToUpperCase(true); - try { - mapper.afterPropertiesSet(); - fail("Expected exception not thrown"); - } - catch (IllegalArgumentException expected) { - } - catch (Exception unexpected) { - fail("Unexpected exception: " + unexpected); - } + assertThatIllegalArgumentException().isThrownBy(mapper::afterPropertiesSet); } @Test public final void testAfterPropertiesSet() { SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper(); - try { - mapper.afterPropertiesSet(); - } - catch (Exception unexpected) { - fail("Unexpected exception: " + unexpected); - } + assertThatNoException().isThrownBy(mapper::afterPropertiesSet); } @Test diff --git a/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java b/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java index 7ea8a2eca80..910a8cdd824 100644 --- a/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java +++ b/core/src/test/java/org/springframework/security/core/context/SecurityContextHolderTests.java @@ -22,7 +22,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 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 SecurityContextHolder}. @@ -55,12 +55,7 @@ public void testNeverReturnsNull() { @Test public void testRejectsNulls() { - try { - SecurityContextHolder.setContext(null); - fail("Should have rejected null"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> SecurityContextHolder.setContext(null)); } } diff --git a/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java b/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java index 8364a1f3602..f23125d2b78 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java @@ -22,7 +22,7 @@ import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author TSARDD @@ -34,15 +34,7 @@ public class UserDetailsByNameServiceWrapperTests { @Test public final void testAfterPropertiesSet() { UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper(); - try { - svc.afterPropertiesSet(); - fail("AfterPropertiesSet didn't throw expected exception"); - } - catch (IllegalArgumentException expected) { - } - catch (Exception unexpected) { - fail("AfterPropertiesSet throws unexpected exception"); - } + assertThatIllegalArgumentException().isThrownBy(svc::afterPropertiesSet); } @Test diff --git a/core/src/test/java/org/springframework/security/core/userdetails/UserTests.java b/core/src/test/java/org/springframework/security/core/userdetails/UserTests.java index 4ac32d65ba5..d56d39c3137 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/UserTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/UserTests.java @@ -30,7 +30,8 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link User}. @@ -63,50 +64,25 @@ public void hashLookupOnlyDependsOnUsername() { @Test public void testNoArgConstructorDoesntExist() { - Class clazz = User.class; - try { - clazz.getDeclaredConstructor((Class[]) null); - fail("Should have thrown NoSuchMethodException"); - } - catch (NoSuchMethodException expected) { - } + assertThatExceptionOfType(NoSuchMethodException.class) + .isThrownBy(() -> User.class.getDeclaredConstructor((Class[]) null)); } @Test public void testNullValuesRejected() { - try { - new User(null, "koala", true, true, true, true, ROLE_12); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - new User("rod", null, true, true, true, true, ROLE_12); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - List auths = AuthorityUtils.createAuthorityList("ROLE_ONE"); - auths.add(null); - new User("rod", "koala", true, true, true, true, auths); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> new User(null, "koala", true, true, true, true, ROLE_12)); + assertThatIllegalArgumentException().isThrownBy(() -> new User("rod", null, true, true, true, true, ROLE_12)); + List auths = AuthorityUtils.createAuthorityList("ROLE_ONE"); + auths.add(null); + assertThatIllegalArgumentException().isThrownBy(() -> new User("rod", "koala", true, true, true, true, auths)); } @Test public void testNullWithinGrantedAuthorityElementIsRejected() { - try { - List auths = AuthorityUtils.createAuthorityList("ROLE_ONE"); - auths.add(null); - auths.add(new SimpleGrantedAuthority("ROLE_THREE")); - new User(null, "koala", true, true, true, true, auths); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + List auths = AuthorityUtils.createAuthorityList("ROLE_ONE"); + auths.add(null); + auths.add(new SimpleGrantedAuthority("ROLE_THREE")); + assertThatIllegalArgumentException().isThrownBy(() -> new User(null, "koala", true, true, true, true, auths)); } @Test diff --git a/core/src/test/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImplTests.java b/core/src/test/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImplTests.java index 90f45656b4d..f933024e337 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImplTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImplTests.java @@ -25,7 +25,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +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.eq; import static org.mockito.Mockito.mock; @@ -92,23 +93,14 @@ public void testGettersSetters() { @Test public void testLookupFailsIfUserHasNoGrantedAuthorities() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDao(); - try { - dao.loadUserByUsername("cooper"); - fail("Should have thrown UsernameNotFoundException"); - } - catch (UsernameNotFoundException expected) { - } + assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> dao.loadUserByUsername("cooper")); } @Test public void testLookupFailsWithWrongUsername() throws Exception { JdbcDaoImpl dao = makePopulatedJdbcDao(); - try { - dao.loadUserByUsername("UNKNOWN_USER"); - fail("Should have thrown UsernameNotFoundException"); - } - catch (UsernameNotFoundException expected) { - } + assertThatExceptionOfType(UsernameNotFoundException.class) + .isThrownBy(() -> dao.loadUserByUsername("UNKNOWN_USER")); } @Test @@ -152,24 +144,16 @@ public void testDuplicateGroupAuthoritiesAreRemoved() throws Exception { @Test public void testStartupFailsIfDataSourceNotSet() { JdbcDaoImpl dao = new JdbcDaoImpl(); - try { - dao.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(dao::afterPropertiesSet); } @Test public void testStartupFailsIfUserMapSetToNull() { JdbcDaoImpl dao = new JdbcDaoImpl(); - try { + assertThatIllegalArgumentException().isThrownBy(() -> { dao.setDataSource(null); dao.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + }); } @Test(expected = IllegalArgumentException.class) diff --git a/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java b/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java index ddb9a46d7ef..54a24a39bc3 100644 --- a/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java +++ b/core/src/test/java/org/springframework/security/provisioning/JdbcUserDetailsManagerTests.java @@ -44,7 +44,7 @@ import org.springframework.security.core.userdetails.UserDetails; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -229,12 +229,8 @@ public void changePasswordFailsIfReAuthenticationFails() { AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); this.manager.setAuthenticationManager(am); - try { - this.manager.changePassword("password", "newPassword"); - fail("Expected BadCredentialsException"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class) + .isThrownBy(() -> this.manager.changePassword("password", "newPassword")); // Check password hasn't changed. UserDetails newJoe = this.manager.loadUserByUsername("joe"); assertThat(newJoe.getPassword()).isEqualTo("password"); diff --git a/core/src/test/java/org/springframework/security/util/FieldUtilsTests.java b/core/src/test/java/org/springframework/security/util/FieldUtilsTests.java index 2d7317b7a15..9369b93ecac 100644 --- a/core/src/test/java/org/springframework/security/util/FieldUtilsTests.java +++ b/core/src/test/java/org/springframework/security/util/FieldUtilsTests.java @@ -19,6 +19,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * @author Luke Taylor @@ -32,11 +33,7 @@ public void gettingAndSettingProtectedFieldIsSuccessful() throws Exception { assertThat(FieldUtils.getFieldValue(tc, "nested.protectedField")).isEqualTo("z"); FieldUtils.setProtectedFieldValue("protectedField", tc, "y"); assertThat(FieldUtils.getProtectedFieldValue("protectedField", tc)).isEqualTo("y"); - try { - FieldUtils.getProtectedFieldValue("nonExistentField", tc); - } - catch (IllegalStateException expected) { - } + assertThatIllegalStateException().isThrownBy(() -> FieldUtils.getProtectedFieldValue("nonExistentField", tc)); } @SuppressWarnings("unused") diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java index aadb2faaf95..405b1296670 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java @@ -38,7 +38,7 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor @@ -90,14 +90,10 @@ public void compareOfWrongValueFails() { @Test public void namingExceptionIsTranslatedCorrectly() { - try { - this.template.executeReadOnly((ContextExecutor) (dirContext) -> { - throw new NamingException(); - }); - fail("Expected UncategorizedLdapException on NamingException"); - } - catch (UncategorizedLdapException expected) { - } + assertThatExceptionOfType(UncategorizedLdapException.class) + .isThrownBy(() -> this.template.executeReadOnly((ContextExecutor) (dirContext) -> { + throw new NamingException(); + })); } @Test diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/BindAuthenticatorTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/BindAuthenticatorTests.java index e574a396f57..577fb9a1696 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/BindAuthenticatorTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/BindAuthenticatorTests.java @@ -33,7 +33,7 @@ import org.springframework.test.context.junit4.SpringRunner; 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 for {@link BindAuthenticator}. @@ -77,13 +77,8 @@ public void testAuthenticationWithCorrectPasswordSucceeds() { @Test public void testAuthenticationWithInvalidUserNameFails() { this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" }); - - try { - this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("nonexistentsuser", "password")); - fail("Shouldn't be able to bind with invalid username"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticator + .authenticate(new UsernamePasswordAuthenticationToken("nonexistentsuser", "password"))); } @Test @@ -131,13 +126,8 @@ public void testAuthenticationWithUserSearch() throws Exception { @Test public void testAuthenticationWithWrongPasswordFails() { this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" }); - - try { - this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpassword")); - fail("Shouldn't be able to bind with wrong password"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy( + () -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpassword"))); } @Test diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java index 54ddd40d8c4..44c9311fdef 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java @@ -36,7 +36,7 @@ import org.springframework.test.context.junit4.SpringRunner; 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 for {@link PasswordComparisonAuthenticator}. @@ -80,13 +80,8 @@ public void testFailedSearchGivesUserNotFoundException() throws Exception { .isEmpty(); this.authenticator.setUserSearch(new MockUserSearch(null)); this.authenticator.afterPropertiesSet(); - - try { - this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass")); - fail("Expected exception on failed user search"); - } - catch (UsernameNotFoundException expected) { - } + assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy( + () -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass"))); } @Test(expected = BadCredentialsException.class) diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java index 8a14656709f..7085abef65b 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/server/ApacheDSContainerTests.java @@ -33,6 +33,7 @@ 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.fail; /** @@ -112,14 +113,8 @@ public void startWithLdapOverSslWithoutCertificate() throws Exception { List ports = getDefaultPorts(1); server.setPort(ports.get(0)); server.setLdapOverSslEnabled(true); - - try { - server.afterPropertiesSet(); - fail("Expected an IllegalArgumentException to be thrown."); - } - catch (IllegalArgumentException ex) { - assertThat(ex).hasMessage("When LdapOverSsl is enabled, the keyStoreFile property must be set."); - } + assertThatIllegalArgumentException().isThrownBy(server::afterPropertiesSet) + .withMessage("When LdapOverSsl is enabled, the keyStoreFile property must be set."); } @Test diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/server/UnboundIdContainerLdifTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/server/UnboundIdContainerLdifTests.java index 645da24654c..1aeead97a3b 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/server/UnboundIdContainerLdifTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/server/UnboundIdContainerLdifTests.java @@ -29,7 +29,7 @@ import org.springframework.security.ldap.SpringSecurityLdapTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link UnboundIdContainer}, specifically relating to LDIF file detection. @@ -72,26 +72,18 @@ public void unboundIdContainerWhenWildcardLdifNameThenLdifLoaded() { @Test public void unboundIdContainerWhenMalformedLdifThenException() { - try { - this.appCtx = new AnnotationConfigApplicationContext(MalformedLdifConfig.class); - failBecauseExceptionWasNotThrown(IllegalStateException.class); - } - catch (Exception ex) { - assertThat(ex.getCause()).isInstanceOf(IllegalStateException.class); - assertThat(ex.getMessage()).contains("Unable to load LDIF classpath:test-server-malformed.txt"); - } + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> this.appCtx = new AnnotationConfigApplicationContext(MalformedLdifConfig.class)) + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("Unable to load LDIF classpath:test-server-malformed.txt"); } @Test public void unboundIdContainerWhenMissingLdifThenException() { - try { - this.appCtx = new AnnotationConfigApplicationContext(MissingLdifConfig.class); - failBecauseExceptionWasNotThrown(IllegalStateException.class); - } - catch (Exception ex) { - assertThat(ex.getCause()).isInstanceOf(IllegalStateException.class); - assertThat(ex.getMessage()).contains("Unable to load LDIF classpath:does-not-exist.ldif"); - } + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> this.appCtx = new AnnotationConfigApplicationContext(MissingLdifConfig.class)) + .withCauseInstanceOf(IllegalStateException.class) + .withMessageContaining("Unable to load LDIF classpath:does-not-exist.ldif"); } @Test diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java index c02d3c3564c..fdcbf7ba8e2 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManagerTests.java @@ -39,7 +39,7 @@ import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor @@ -174,14 +174,7 @@ public void testDeleteUserSucceeds() { assertThat(don.getAuthorities()).hasSize(2); this.mgr.deleteUser("don"); - - try { - this.mgr.loadUserByUsername("don"); - fail("Expected UsernameNotFoundException after deleting user"); - } - catch (UsernameNotFoundException expected) { - // expected - } + assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.mgr.loadUserByUsername("don")); // Check that no authorities are left assertThat(this.mgr.getUserAuthorities(this.mgr.usernameMapper.buildDn("don"), "don")).hasSize(0); diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java index cf6b6eefcc2..7b083051aa5 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java @@ -36,7 +36,7 @@ import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -67,18 +67,10 @@ public void testDefaultMapperIsSet() { public void testEmptyOrNullUserNameThrowsException() { LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(new MockAuthenticator(), new MockAuthoritiesPopulator()); - try { - ldapProvider.authenticate(new UsernamePasswordAuthenticationToken(null, "password")); - fail("Expected BadCredentialsException for empty username"); - } - catch (BadCredentialsException expected) { - } - try { - ldapProvider.authenticate(new UsernamePasswordAuthenticationToken("", "bobspassword")); - fail("Expected BadCredentialsException for null username"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class) + .isThrownBy(() -> ldapProvider.authenticate(new UsernamePasswordAuthenticationToken(null, "password"))); + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy( + () -> ldapProvider.authenticate(new UsernamePasswordAuthenticationToken("", "bobspassword"))); } @Test(expected = BadCredentialsException.class) @@ -156,13 +148,8 @@ public void authenticateWithNamingException() { CommunicationException expectedCause = new CommunicationException(new javax.naming.CommunicationException()); given(mockAuthenticator.authenticate(authRequest)).willThrow(expectedCause); LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(mockAuthenticator); - try { - ldapProvider.authenticate(authRequest); - fail("Expected Exception"); - } - catch (InternalAuthenticationServiceException success) { - assertThat(success.getCause()).isSameAs(expectedCause); - } + assertThatExceptionOfType(InternalAuthenticationServiceException.class) + .isThrownBy(() -> ldapProvider.authenticate(authRequest)).havingCause().isSameAs(expectedCause); } class MockAuthenticator implements LdapAuthenticator { diff --git a/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java b/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java index 8272ec247f1..1c4422344fa 100644 --- a/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java +++ b/ldap/src/test/java/org/springframework/security/ldap/authentication/ad/ActiveDirectoryLdapAuthenticationProviderTests.java @@ -54,7 +54,7 @@ import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.ContextFactory; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -169,12 +169,7 @@ public void nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal() throws given(ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class), any(SearchControls.class))).willReturn(new MockNamingEnumeration(sr)); this.provider.contextFactory = createContextFactoryReturning(ctx); - try { - this.provider.authenticate(this.joe); - fail("Expected BadCredentialsException for user with no domain information"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe)); this.provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password")); } @@ -278,12 +273,7 @@ public void describeTo(Description desc) { @Test(expected = CredentialsExpiredException.class) public void expiredPasswordIsCorrectlyMapped() { this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "532, xxxx]")); - try { - this.provider.authenticate(this.joe); - fail("BadCredentialsException should had been thrown"); - } - catch (BadCredentialsException expected) { - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe)); this.provider.setConvertSubErrorCodesToExceptions(true); this.provider.authenticate(this.joe); } @@ -323,18 +313,12 @@ public void errorWithNoSubcodeIsHandledCleanly() { this.provider.authenticate(this.joe); } - @Test(expected = org.springframework.ldap.CommunicationException.class) + @Test public void nonAuthenticationExceptionIsConvertedToSpringLdapException() throws Throwable { - try { + assertThatExceptionOfType(InternalAuthenticationServiceException.class).isThrownBy(() -> { this.provider.contextFactory = createContextFactoryThrowing(new CommunicationException(msg)); this.provider.authenticate(this.joe); - } - catch (InternalAuthenticationServiceException ex) { - // Since GH-8418 ldap communication exception is wrapped into - // InternalAuthenticationServiceException. - // This test is about the wrapped exception, so we throw it. - throw ex.getCause(); - } + }).withCauseInstanceOf(org.springframework.ldap.CommunicationException.class); } @Test(expected = org.springframework.security.authentication.InternalAuthenticationServiceException.class) @@ -368,16 +352,10 @@ public void contextEnvironmentPropertiesUsed() { Hashtable env = new Hashtable<>(); env.put("java.naming.ldap.factory.socket", "unknown.package.NonExistingSocketFactory"); this.provider.setContextEnvironmentProperties(env); - try { - this.provider.authenticate(this.joe); - fail("CommunicationException was expected with a root cause of ClassNotFoundException"); - } - catch (InternalAuthenticationServiceException expected) { - assertThat(expected.getCause()).isInstanceOf(org.springframework.ldap.CommunicationException.class); - org.springframework.ldap.CommunicationException cause = (org.springframework.ldap.CommunicationException) expected - .getCause(); - assertThat(cause.getRootCause()).isInstanceOf(ClassNotFoundException.class); - } + assertThatExceptionOfType(InternalAuthenticationServiceException.class) + .isThrownBy(() -> this.provider.authenticate(this.joe)) + .withCauseInstanceOf(org.springframework.ldap.CommunicationException.class) + .withRootCauseInstanceOf(ClassNotFoundException.class); } ContextFactory createContextFactoryThrowing(final NamingException ex) { diff --git a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java index 2b9887d8e79..554807ce193 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java @@ -38,7 +38,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -90,18 +90,10 @@ public void messageOrConsumerAuthenticationExceptionRaisesOpenIDException() thro OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); given(mgr.authenticate(ArgumentMatchers.any(), any(), any())) .willThrow(new MessageException("msg"), new ConsumerException("msg")); - try { - consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); - fail("OpenIDConsumerException was not thrown"); - } - catch (OpenIDConsumerException expected) { - } - try { - consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); - fail("OpenIDConsumerException was not thrown"); - } - catch (OpenIDConsumerException expected) { - } + assertThatExceptionOfType(OpenIDConsumerException.class) + .isThrownBy(() -> consumer.beginConsumption(new MockHttpServletRequest(), "", "", "")); + assertThatExceptionOfType(OpenIDConsumerException.class) + .isThrownBy(() -> consumer.beginConsumption(new MockHttpServletRequest(), "", "", "")); } @Test @@ -125,24 +117,9 @@ public void verificationExceptionsRaiseOpenIDException() throws Exception { .willThrow(new MessageException(""), new AssociationException(""), new DiscoveryException("")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("x=5"); - try { - consumer.endConsumption(request); - fail("OpenIDConsumerException was not thrown"); - } - catch (OpenIDConsumerException expected) { - } - try { - consumer.endConsumption(request); - fail("OpenIDConsumerException was not thrown"); - } - catch (OpenIDConsumerException expected) { - } - try { - consumer.endConsumption(request); - fail("OpenIDConsumerException was not thrown"); - } - catch (OpenIDConsumerException expected) { - } + assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request)); + assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request)); + assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request)); } @SuppressWarnings("serial") diff --git a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java index 65ad76bf72d..af5adadd13c 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationProviderTests.java @@ -31,7 +31,8 @@ import org.springframework.security.core.userdetails.UserDetailsService; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link OpenIDAuthenticationProvider} @@ -60,13 +61,8 @@ public void testAuthenticateCancel() { Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.CANCELLED, USERNAME, "", null); assertThat(preAuth.isAuthenticated()).isFalse(); - try { - provider.authenticate(preAuth); - fail("Should throw an AuthenticationException"); - } - catch (AuthenticationCancelledException expected) { - assertThat(expected.getMessage()).isEqualTo("Log in cancelled"); - } + assertThatExceptionOfType(AuthenticationCancelledException.class) + .isThrownBy(() -> provider.authenticate(preAuth)).withMessage("Log in cancelled"); } /* @@ -80,13 +76,8 @@ public void testAuthenticateError() { provider.setUserDetailsService(new MockUserDetailsService()); Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.ERROR, USERNAME, "", null); assertThat(preAuth.isAuthenticated()).isFalse(); - try { - provider.authenticate(preAuth); - fail("Should throw an AuthenticationException"); - } - catch (AuthenticationServiceException expected) { - assertThat(expected.getMessage()).isEqualTo("Error message from server: "); - } + assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(preAuth)) + .withMessage("Error message from server: "); } /* @@ -101,13 +92,8 @@ public void testAuthenticateFailure() { new UserDetailsByNameServiceWrapper<>(new MockUserDetailsService())); Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE, USERNAME, "", null); assertThat(preAuth.isAuthenticated()).isFalse(); - try { - provider.authenticate(preAuth); - fail("Should throw an AuthenticationException"); - } - catch (BadCredentialsException expected) { - assertThat("Log in failed - identity could not be verified").isEqualTo(expected.getMessage()); - } + assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(preAuth)) + .withMessage("Log in failed - identity could not be verified"); } /* @@ -122,14 +108,8 @@ public void testAuthenticateSetupNeeded() { Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SETUP_NEEDED, USERNAME, "", null); assertThat(preAuth.isAuthenticated()).isFalse(); - try { - provider.authenticate(preAuth); - fail("Should throw an AuthenticationException"); - } - catch (AuthenticationServiceException expected) { - assertThat("The server responded setup was needed, which shouldn't happen") - .isEqualTo(expected.getMessage()); - } + assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(preAuth)) + .withMessage("The server responded setup was needed, which shouldn't happen"); } /* @@ -158,13 +138,7 @@ public void testAuthenticateSuccess() { @Test public void testDetectsMissingAuthoritiesPopulator() throws Exception { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - try { - provider.afterPropertiesSet(); - fail("Should have thrown Exception"); - } - catch (IllegalArgumentException expected) { - // ignored - } + assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet); } /* @@ -207,13 +181,7 @@ public void testSupports() { @Test public void testValidation() throws Exception { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); - try { - provider.afterPropertiesSet(); - fail("IllegalArgumentException expected, ssoAuthoritiesPopulator is null"); - } - catch (IllegalArgumentException ex) { - // expected - } + assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet); provider = new OpenIDAuthenticationProvider(); provider.setUserDetailsService(new MockUserDetailsService()); provider.afterPropertiesSet(); diff --git a/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java b/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java index b7512c245e6..4810a2ba988 100644 --- a/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java +++ b/remoting/src/test/java/org/springframework/security/remoting/rmi/ContextPropagatingRemoteInvocationTests.java @@ -30,7 +30,7 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link ContextPropagatingRemoteInvocation} and @@ -59,15 +59,10 @@ public void testContextIsResetEvenIfExceptionOccurs() throws Exception { Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("rod", "koala"); SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication); ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation(); - try { - // Set up the wrong arguments. - remoteInvocation.setArguments(new Object[] {}); - remoteInvocation.invoke(TargetObject.class.newInstance()); - fail("Expected IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + // Set up the wrong arguments. + remoteInvocation.setArguments(new Object[] {}); + assertThatIllegalArgumentException() + .isThrownBy(() -> remoteInvocation.invoke(TargetObject.class.newInstance())); assertThat(SecurityContextHolder.getContext().getAuthentication()) .withFailMessage("Authentication must be null").isNull(); } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java index 6ebb014b51a..826b04fa227 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilterTests.java @@ -29,8 +29,7 @@ import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -85,14 +84,9 @@ public void attemptAuthenticationWhenRegistrationIdDoesNotExistThenThrowsExcepti this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/some/other/path/{registrationId}"); this.request.setPathInfo("/some/other/path/non-existent-id"); this.request.setParameter("SAMLResponse", "response"); - try { - this.filter.attemptAuthentication(this.request, this.response); - failBecauseExceptionWasNotThrown(Saml2AuthenticationException.class); - } - catch (Exception ex) { - assertThat(ex).isInstanceOf(Saml2AuthenticationException.class); - assertThat(ex.getMessage()).isEqualTo("No relying party registration found"); - } + assertThatExceptionOfType(Saml2AuthenticationException.class) + .isThrownBy(() -> this.filter.attemptAuthentication(this.request, this.response)) + .withMessage("No relying party registration found"); } } diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthenticationTagTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthenticationTagTests.java index 555052ff367..84fcdda6948 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthenticationTagTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthenticationTagTests.java @@ -29,7 +29,7 @@ import org.springframework.security.core.userdetails.User; 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 AuthenticationTag}. @@ -106,13 +106,10 @@ public void testSkipsBodyIfNullOrEmptyOperation() throws Exception { public void testThrowsExceptionForUnrecognisedProperty() { SecurityContextHolder.getContext().setAuthentication(this.auth); this.authenticationTag.setProperty("qsq"); - try { + assertThatExceptionOfType(JspException.class).isThrownBy(() -> { this.authenticationTag.doStartTag(); this.authenticationTag.doEndTag(); - fail("Should have throwns JspException"); - } - catch (JspException expected) { - } + }); } @Test diff --git a/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java b/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java index c5586308dcc..6495b2c5bb1 100644 --- a/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java +++ b/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java @@ -43,7 +43,7 @@ import org.springframework.security.web.util.matcher.RequestMatcher; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -206,12 +206,8 @@ public void doFilterClearsSecurityContextHolderWithException() throws Exception throw new ServletException("oops"); }).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class)); - try { - this.fcp.doFilter(this.request, this.response, this.chain); - fail("Expected Exception"); - } - catch (ServletException success) { - } + assertThatExceptionOfType(ServletException.class) + .isThrownBy(() -> this.fcp.doFilter(this.request, this.response, this.chain)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } diff --git a/web/src/test/java/org/springframework/security/web/PortMapperImplTests.java b/web/src/test/java/org/springframework/security/web/PortMapperImplTests.java index aad10c3947e..eff5866af93 100644 --- a/web/src/test/java/org/springframework/security/web/PortMapperImplTests.java +++ b/web/src/test/java/org/springframework/security/web/PortMapperImplTests.java @@ -22,7 +22,7 @@ import org.junit.Test; 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 PortMapperImpl}. @@ -43,23 +43,13 @@ public void testDefaultMappingsAreKnown() { @Test public void testDetectsEmptyMap() { PortMapperImpl portMapper = new PortMapperImpl(); - try { - portMapper.setPortMappings(new HashMap<>()); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(new HashMap<>())); } @Test public void testDetectsNullMap() { PortMapperImpl portMapper = new PortMapperImpl(); - try { - portMapper.setPortMappings(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(null)); } @Test @@ -73,12 +63,7 @@ public void testRejectsOutOfRangeMappings() { PortMapperImpl portMapper = new PortMapperImpl(); Map map = new HashMap<>(); map.put("79", "80559"); - try { - portMapper.setPortMappings(map); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(map)); } @Test diff --git a/web/src/test/java/org/springframework/security/web/PortResolverImplTests.java b/web/src/test/java/org/springframework/security/web/PortResolverImplTests.java index db99268419f..6d46e35ef67 100644 --- a/web/src/test/java/org/springframework/security/web/PortResolverImplTests.java +++ b/web/src/test/java/org/springframework/security/web/PortResolverImplTests.java @@ -21,7 +21,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link PortResolverImpl}. @@ -51,12 +51,7 @@ public void testDetectsBuggyIeHttpsRequest() { @Test public void testDetectsEmptyPortMapper() { PortResolverImpl pr = new PortResolverImpl(); - try { - pr.setPortMapper(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> pr.setPortMapper(null)); } @Test diff --git a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java index 29fa3d9447e..a0b7f8db426 100644 --- a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java @@ -48,7 +48,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -258,16 +257,12 @@ public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown() t ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint); filter.afterPropertiesSet(); Exception[] exceptions = { new IOException(), new ServletException(), new RuntimeException() }; - for (Exception e : exceptions) { + for (Exception exception : exceptions) { FilterChain fc = mock(FilterChain.class); - willThrow(e).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); - try { - filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc); - fail("Should have thrown Exception"); - } - catch (Exception expected) { - assertThat(expected).isSameAs(e); - } + willThrow(exception).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc)) + .isSameAs(exception); } } diff --git a/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java b/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java index b31987dec30..e180b9b0fda 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/ChannelDecisionManagerImplTests.java @@ -33,6 +33,7 @@ import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; @@ -47,14 +48,10 @@ public class ChannelDecisionManagerImplTests { @Test public void testCannotSetEmptyChannelProcessorsList() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); - try { + assertThatIllegalArgumentException().isThrownBy(() -> { cdm.setChannelProcessors(new Vector()); cdm.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required"); - } + }).withMessage("A list of ChannelProcessors is required"); } @Test @@ -62,25 +59,16 @@ public void testCannotSetIncorrectObjectTypesIntoChannelProcessorsList() { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); List list = new Vector(); list.add("THIS IS NOT A CHANNELPROCESSOR"); - try { - cdm.setChannelProcessors(list); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> cdm.setChannelProcessors(list)); } @Test public void testCannotSetNullChannelProcessorsList() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); - try { + assertThatIllegalArgumentException().isThrownBy(() -> { cdm.setChannelProcessors(null); cdm.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required"); - } + }).withMessage("A list of ChannelProcessors is required"); } @Test @@ -164,13 +152,8 @@ public void testGettersSetters() { @Test public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception { ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); - try { - cdm.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required"); - } + assertThatIllegalArgumentException().isThrownBy(cdm::afterPropertiesSet) + .withMessage("A list of ChannelProcessors is required"); } private class MockChannelProcessor implements ChannelProcessor { diff --git a/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java b/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java index 487e1a5cf9a..a27b459db98 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/InsecureChannelProcessorTests.java @@ -26,7 +26,7 @@ import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -74,12 +74,7 @@ public void testDecideDetectsUnacceptableChannel() throws Exception { public void testDecideRejectsNulls() throws Exception { InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.afterPropertiesSet(); - try { - processor.decide(null, null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> processor.decide(null, null)); } @Test @@ -97,34 +92,19 @@ public void testGettersSetters() { public void testMissingEntryPoint() throws Exception { InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.setEntryPoint(null); - try { - processor.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("entryPoint required"); - } + assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet) + .withMessage("entryPoint required"); } @Test public void testMissingSecureChannelKeyword() throws Exception { InsecureChannelProcessor processor = new InsecureChannelProcessor(); processor.setInsecureKeyword(null); - try { - processor.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("insecureKeyword required"); - } + assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet) + .withMessage("insecureKeyword required"); processor.setInsecureKeyword(""); - try { - processor.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("insecureKeyword required"); - } + assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet) + .withMessage("insecureKeyword required"); } @Test diff --git a/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpEntryPointTests.java b/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpEntryPointTests.java index f858d11c5b6..b2114ef85b0 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpEntryPointTests.java @@ -30,7 +30,7 @@ import org.springframework.security.web.RedirectStrategy; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -43,23 +43,13 @@ public class RetryWithHttpEntryPointTests { @Test public void testDetectsMissingPortMapper() { RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); - try { - ep.setPortMapper(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null)); } @Test public void testDetectsMissingPortResolver() { RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); - try { - ep.setPortResolver(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null)); } @Test diff --git a/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpsEntryPointTests.java b/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpsEntryPointTests.java index 29274cb3ea1..d65f9a980d5 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpsEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/RetryWithHttpsEntryPointTests.java @@ -27,7 +27,7 @@ import org.springframework.security.web.PortMapperImpl; 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 RetryWithHttpsEntryPoint}. @@ -39,23 +39,13 @@ public class RetryWithHttpsEntryPointTests { @Test public void testDetectsMissingPortMapper() { RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); - try { - ep.setPortMapper(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null)); } @Test public void testDetectsMissingPortResolver() { RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); - try { - ep.setPortResolver(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null)); } @Test diff --git a/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java b/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java index e66b411c55b..ffc35f0bdfc 100644 --- a/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/channel/SecureChannelProcessorTests.java @@ -26,7 +26,7 @@ import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -74,12 +74,7 @@ public void testDecideDetectsUnacceptableChannel() throws Exception { public void testDecideRejectsNulls() throws Exception { SecureChannelProcessor processor = new SecureChannelProcessor(); processor.afterPropertiesSet(); - try { - processor.decide(null, null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> processor.decide(null, null)); } @Test @@ -97,34 +92,19 @@ public void testGettersSetters() { public void testMissingEntryPoint() throws Exception { SecureChannelProcessor processor = new SecureChannelProcessor(); processor.setEntryPoint(null); - try { - processor.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("entryPoint required"); - } + assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet) + .withMessage("entryPoint required"); } @Test public void testMissingSecureChannelKeyword() throws Exception { SecureChannelProcessor processor = new SecureChannelProcessor(); processor.setSecureKeyword(null); - try { - processor.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("secureKeyword required"); - } + assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet) + .withMessage("secureKeyword required"); processor.setSecureKeyword(""); - try { - processor.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("secureKeyword required"); - } + assertThatIllegalArgumentException().isThrownBy(() -> processor.afterPropertiesSet()) + .withMessage("secureKeyword required"); } @Test diff --git a/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java b/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java index dcd759048a1..2fc0f1269da 100644 --- a/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java +++ b/web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java @@ -42,7 +42,7 @@ import org.springframework.security.web.FilterInvocation; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.eq; @@ -135,12 +135,7 @@ public void afterInvocationIsNotInvokedIfExceptionThrown() throws Exception { given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); AfterInvocationManager aim = mock(AfterInvocationManager.class); this.interceptor.setAfterInvocationManager(aim); - try { - this.interceptor.invoke(fi); - fail("Expected exception"); - } - catch (RuntimeException expected) { - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(fi)); verifyZeroInteractions(aim); } @@ -163,12 +158,7 @@ public void finallyInvocationIsInvokedIfExceptionThrown() throws Exception { given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); AfterInvocationManager aim = mock(AfterInvocationManager.class); this.interceptor.setAfterInvocationManager(aim); - try { - this.interceptor.invoke(fi); - fail("Expected exception"); - } - catch (RuntimeException expected) { - } + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(fi)); // Check we've changed back assertThat(SecurityContextHolder.getContext()).isSameAs(ctx); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token); diff --git a/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java index 0cdee2f548f..d72b04cc08e 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilterTests.java @@ -48,6 +48,7 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -251,13 +252,8 @@ public void testStartupDetectsInvalidAuthenticationManager() { this.successHandler.setDefaultTargetUrl("/"); filter.setAuthenticationSuccessHandler(this.successHandler); filter.setFilterProcessesUrl("/login"); - try { - filter.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("authenticationManager must be specified"); - } + assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet) + .withMessage("authenticationManager must be specified"); } @Test @@ -266,13 +262,8 @@ public void testStartupDetectsInvalidFilterProcessesUrl() { filter.setAuthenticationFailureHandler(this.failureHandler); filter.setAuthenticationManager(mock(AuthenticationManager.class)); filter.setAuthenticationSuccessHandler(this.successHandler); - try { - filter.setFilterProcessesUrl(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("Pattern cannot be null or empty"); - } + assertThatIllegalArgumentException().isThrownBy(() -> filter.setFilterProcessesUrl(null)) + .withMessage("Pattern cannot be null or empty"); } @Test diff --git a/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java index 36a439e57ea..3d32c4c4c90 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/AuthenticationFilterTests.java @@ -43,6 +43,7 @@ import org.springframework.security.web.util.matcher.RequestMatcher; 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.eq; import static org.mockito.BDDMockito.given; @@ -205,7 +206,7 @@ public void filterWhenConvertAndAuthenticationSuccessThenSuccess() throws Except assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); } - @Test(expected = ServletException.class) + @Test public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exception { Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER"); given(this.authenticationConverter.convert(any())).willReturn(authentication); @@ -216,14 +217,9 @@ public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exce MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); - try { - filter.doFilter(request, response, chain); - } - catch (ServletException ex) { - verifyZeroInteractions(this.successHandler); - assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); - throw ex; - } + assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain)); + verifyZeroInteractions(this.successHandler); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } @Test diff --git a/web/src/test/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandlerTests.java index 61bfc56446a..5ebd4611aa3 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/SavedRequestAwareAuthenticationSuccessHandlerTests.java @@ -25,7 +25,7 @@ import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SavedRequest; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -38,12 +38,7 @@ public void defaultUrlMuststartWithSlashOrHttpScheme() { handler.setDefaultTargetUrl("/acceptableRelativeUrl"); handler.setDefaultTargetUrl("https://some.site.org/index.html"); handler.setDefaultTargetUrl("https://some.site.org/index.html"); - try { - handler.setDefaultTargetUrl("missingSlash"); - fail("Shouldn't accept default target without leading slash"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> handler.setDefaultTargetUrl("missingSlash")); } @Test diff --git a/web/src/test/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandlerTests.java index 10882616120..b1abd204827 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/SimpleUrlAuthenticationSuccessHandlerTests.java @@ -23,7 +23,7 @@ import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -104,18 +104,8 @@ public void setTargetUrlParameterNullTargetUrlParameter() { @Test public void setTargetUrlParameterEmptyTargetUrlParameter() { SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(); - try { - ash.setTargetUrlParameter(""); - fail("Expected Exception"); - } - catch (IllegalArgumentException success) { - } - try { - ash.setTargetUrlParameter(" "); - fail("Expected Exception"); - } - catch (IllegalArgumentException success) { - } + assertThatIllegalArgumentException().isThrownBy(() -> ash.setTargetUrlParameter("")); + assertThatIllegalArgumentException().isThrownBy(() -> ash.setTargetUrlParameter(" ")); } } diff --git a/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java index cfc5c356669..f34586943e4 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java @@ -27,7 +27,7 @@ import org.springframework.security.core.AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -114,12 +114,8 @@ public void testFailedAuthenticationThrowsException() { AuthenticationManager am = mock(AuthenticationManager.class); given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); filter.setAuthenticationManager(am); - try { - filter.attemptAuthentication(request, new MockHttpServletResponse()); - fail("Expected AuthenticationException"); - } - catch (AuthenticationException ex) { - } + assertThatExceptionOfType(AuthenticationException.class) + .isThrownBy(() -> filter.attemptAuthentication(request, new MockHttpServletResponse())); } /** diff --git a/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java index 422311985a9..0f6298b12c3 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/CompositeLogoutHandlerTests.java @@ -29,7 +29,7 @@ import org.springframework.security.core.Authentication; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.inOrder; @@ -88,12 +88,8 @@ public void callLogoutHandlersThrowException() { any(HttpServletResponse.class), any(Authentication.class)); List logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler); LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers); - try { - handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class)); - fail("Expected Exception"); - } - catch (IllegalArgumentException success) { - } + assertThatIllegalArgumentException().isThrownBy(() -> handler.logout(mock(HttpServletRequest.class), + mock(HttpServletResponse.class), mock(Authentication.class))); InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, secondLogoutHandler); logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class)); diff --git a/web/src/test/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandlerTests.java b/web/src/test/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandlerTests.java index 2065a83fed9..494f7e033c1 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/logout/HttpStatusReturningLogoutSuccessHandlerTests.java @@ -24,7 +24,7 @@ import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** @@ -59,14 +59,8 @@ public void testCustomHttpStatusBeingReturned() throws Exception { @Test public void testThatSettNullHttpStatusThrowsException() { - try { - new HttpStatusReturningLogoutSuccessHandler(null); - } - catch (IllegalArgumentException ex) { - assertThat(ex).hasMessage("The provided HttpStatus must not be null."); - return; - } - fail("Expected an IllegalArgumentException to be thrown."); + assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusReturningLogoutSuccessHandler(null)) + .withMessage("The provided HttpStatus must not be null."); } } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java index d305e844e59..239dbd2c5f3 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java @@ -42,7 +42,7 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -105,15 +105,7 @@ public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsucc @Test public void testAfterPropertiesSet() { ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); - try { - filter.afterPropertiesSet(); - fail("AfterPropertiesSet didn't throw expected exception"); - } - catch (IllegalArgumentException expected) { - } - catch (Exception unexpected) { - fail("AfterPropertiesSet throws unexpected exception"); - } + assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet); } // SEC-2045 diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java index 90758721487..096c5315b35 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/Http403ForbiddenEntryPointTests.java @@ -26,22 +26,15 @@ import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; public class Http403ForbiddenEntryPointTests { - public void testCommence() { + public void testCommence() throws IOException { MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse resp = new MockHttpServletResponse(); Http403ForbiddenEntryPoint fep = new Http403ForbiddenEntryPoint(); - try { - fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test")); - assertThat(resp.getStatus()).withFailMessage("Incorrect status") - .isEqualTo(HttpServletResponse.SC_FORBIDDEN); - } - catch (IOException ex) { - fail("Unexpected exception thrown: " + ex); - } + fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test")); + assertThat(resp.getStatus()).withFailMessage("Incorrect status").isEqualTo(HttpServletResponse.SC_FORBIDDEN); } } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java index 694827cc1e2..770f52dce58 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java @@ -35,7 +35,7 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author TSARDD @@ -45,15 +45,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests { @Test public final void testAfterPropertiesSetException() { J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(); - try { - t.afterPropertiesSet(); - fail("AfterPropertiesSet didn't throw expected exception"); - } - catch (IllegalArgumentException expected) { - } - catch (Exception unexpected) { - fail("AfterPropertiesSet throws unexpected exception"); - } + assertThatIllegalArgumentException().isThrownBy(t::afterPropertiesSet); } @Test @@ -139,12 +131,7 @@ private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource getJ2eeBasedPreA J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(); result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles)); result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper()); - try { - result.afterPropertiesSet(); - } - catch (Exception expected) { - fail("AfterPropertiesSet throws unexpected exception"); - } + result.afterPropertiesSet(); return result; } diff --git a/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java b/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java index 5c75c28c8e8..a407dc5962e 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/session/CompositeSessionAuthenticationStrategyTests.java @@ -29,7 +29,7 @@ import org.springframework.security.core.Authentication; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -86,12 +86,8 @@ public void delegateShortCircuits() { .onAuthentication(this.authentication, this.request, this.response); CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy( Arrays.asList(this.strategy1, this.strategy2)); - try { - strategy.onAuthentication(this.authentication, this.request, this.response); - fail("Expected Exception"); - } - catch (SessionAuthenticationException success) { - } + assertThatExceptionOfType(SessionAuthenticationException.class) + .isThrownBy(() -> strategy.onAuthentication(this.authentication, this.request, this.response)); verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response); verify(this.strategy2, times(0)).onAuthentication(this.authentication, this.request, this.response); } diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPointTests.java index 2050d9267f3..ea6bc24ac87 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPointTests.java @@ -24,7 +24,7 @@ import org.springframework.security.authentication.DisabledException; 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 BasicAuthenticationEntryPoint}. @@ -36,13 +36,8 @@ public class BasicAuthenticationEntryPointTests { @Test public void testDetectsMissingRealmName() { BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint(); - try { - ep.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("realmName must be specified"); - } + assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) + .withMessage("realmName must be specified"); } @Test diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthUtilsTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthUtilsTests.java index f2731df602b..8fcaf532afe 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthUtilsTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthUtilsTests.java @@ -23,7 +23,7 @@ import org.springframework.util.StringUtils; 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 org.springframework.security.util.StringSplitUtils}. @@ -90,36 +90,12 @@ public void testSplitNormalOperation() { @Test public void testSplitRejectsNullsAndIncorrectLengthStrings() { - try { - DigestAuthUtils.split(null, "="); // null - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - DigestAuthUtils.split("", "="); // empty string - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - DigestAuthUtils.split("sdch=dfgf", null); // null - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - DigestAuthUtils.split("fvfv=dcdc", ""); // empty string - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } - try { - DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER"); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split(null, "=")); + assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("", "=")); + assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("sdch=dfgf", null)); + assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("fvfv=dcdc", "")); + assertThatIllegalArgumentException() + .isThrownBy(() -> DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER")); } @Test diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPointTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPointTests.java index 3f6b2c61f91..e33efb4e8bc 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPointTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationEntryPointTests.java @@ -28,7 +28,7 @@ import org.springframework.util.StringUtils; 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 DigestAuthenticationEntryPoint}. @@ -53,13 +53,7 @@ private void checkNonceValid(String nonce) { public void testDetectsMissingKey() throws Exception { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setRealmName("realm"); - try { - ep.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("key must be specified"); - } + assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet).withMessage("key must be specified"); } @Test @@ -67,13 +61,8 @@ public void testDetectsMissingRealmName() throws Exception { DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); ep.setKey("dcdc"); ep.setNonceValiditySeconds(12); - try { - ep.afterPropertiesSet(); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - assertThat(expected.getMessage()).isEqualTo("realmName must be specified"); - } + assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) + .withMessage("realmName must be specified"); } @Test diff --git a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java index 2bbfe08032e..8a7087eefc3 100644 --- a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java @@ -33,7 +33,7 @@ import org.springframework.security.core.context.SecurityContextImpl; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIOException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; @@ -69,12 +69,7 @@ public void contextIsStillClearedIfExceptionIsThrowByFilterChain() throws Except SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(); SecurityContextHolder.getContext().setAuthentication(this.testToken); willThrow(new IOException()).given(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); - try { - filter.doFilter(request, response, chain); - fail("IOException should have been thrown"); - } - catch (IOException expected) { - } + assertThatIOException().isThrownBy(() -> filter.doFilter(request, response, chain)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } diff --git a/web/src/test/java/org/springframework/security/web/firewall/DefaultHttpFirewallTests.java b/web/src/test/java/org/springframework/security/web/firewall/DefaultHttpFirewallTests.java index ef2b49258a1..cbc09f48b96 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/DefaultHttpFirewallTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/DefaultHttpFirewallTests.java @@ -20,7 +20,7 @@ import org.springframework.mock.web.MockHttpServletRequest; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor @@ -33,23 +33,14 @@ public class DefaultHttpFirewallTests { @Test public void unnormalizedPathsAreRejected() { DefaultHttpFirewall fw = new DefaultHttpFirewall(); - MockHttpServletRequest request; for (String path : this.unnormalizedPaths) { - request = new MockHttpServletRequest(); + MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath(path); - try { - fw.getFirewalledRequest(request); - fail(path + " is un-normalized"); - } - catch (RequestRejectedException expected) { - } + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> fw.getFirewalledRequest(request)); request.setPathInfo(path); - try { - fw.getFirewalledRequest(request); - fail(path + " is un-normalized"); - } - catch (RequestRejectedException expected) { - } + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> fw.getFirewalledRequest(request)); } } diff --git a/web/src/test/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandlerTests.java b/web/src/test/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandlerTests.java index e00195629d9..b9d0cacdefc 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/DefaultRequestRejectedHandlerTests.java @@ -19,10 +19,9 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.hamcrest.CoreMatchers; -import org.junit.Assert; import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; public class DefaultRequestRejectedHandlerTests { @@ -31,14 +30,9 @@ public class DefaultRequestRejectedHandlerTests { public void defaultRequestRejectedHandlerRethrowsTheException() throws Exception { RequestRejectedException requestRejectedException = new RequestRejectedException("rejected"); DefaultRequestRejectedHandler sut = new DefaultRequestRejectedHandler(); - try { - sut.handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException); - } - catch (RequestRejectedException exception) { - Assert.assertThat(exception.getMessage(), CoreMatchers.is("rejected")); - return; - } - Assert.fail("Exception was not rethrown"); + assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> sut + .handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException)) + .withMessage("rejected"); } } diff --git a/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java b/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java index 66280703505..5ded76a4685 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/FirewalledResponseTests.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -166,12 +166,7 @@ private void expectCrlfValidationException() { } private void validateLineEnding(String name, String value) { - try { - this.fwResponse.validateCrlf(name, value); - fail("IllegalArgumentException should have thrown"); - } - catch (IllegalArgumentException expected) { - } + assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.validateCrlf(name, value)); } } diff --git a/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java b/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java index eb38bdabd25..9ae4704b486 100644 --- a/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java +++ b/web/src/test/java/org/springframework/security/web/firewall/StrictHttpFirewallTests.java @@ -27,7 +27,6 @@ import org.springframework.mock.web.MockHttpServletRequest; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.fail; /** * @author Rob Winch @@ -94,12 +93,8 @@ public void getFirewalledRequestWhenRequestURINotNormalizedThenThrowsRequestReje for (String path : this.unnormalizedPaths) { this.request = new MockHttpServletRequest("GET", ""); this.request.setRequestURI(path); - try { - this.firewall.getFirewalledRequest(this.request); - fail(path + " is un-normalized"); - } - catch (RequestRejectedException expected) { - } + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } } @@ -108,12 +103,8 @@ public void getFirewalledRequestWhenContextPathNotNormalizedThenThrowsRequestRej for (String path : this.unnormalizedPaths) { this.request = new MockHttpServletRequest("GET", ""); this.request.setContextPath(path); - try { - this.firewall.getFirewalledRequest(this.request); - fail(path + " is un-normalized"); - } - catch (RequestRejectedException expected) { - } + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } } @@ -122,12 +113,8 @@ public void getFirewalledRequestWhenServletPathNotNormalizedThenThrowsRequestRej for (String path : this.unnormalizedPaths) { this.request = new MockHttpServletRequest("GET", ""); this.request.setServletPath(path); - try { - this.firewall.getFirewalledRequest(this.request); - fail(path + " is un-normalized"); - } - catch (RequestRejectedException expected) { - } + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } } @@ -136,12 +123,8 @@ public void getFirewalledRequestWhenPathInfoNotNormalizedThenThrowsRequestReject for (String path : this.unnormalizedPaths) { this.request = new MockHttpServletRequest("GET", ""); this.request.setPathInfo(path); - try { - this.firewall.getFirewalledRequest(this.request); - fail(path + " is un-normalized"); - } - catch (RequestRejectedException expected) { - } + assertThatExceptionOfType(RequestRejectedException.class) + .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request)); } } diff --git a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java index 0f59497165b..0a528ffb1f7 100644 --- a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java @@ -51,7 +51,7 @@ import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -179,15 +179,11 @@ public void loginWithExistingUser() throws Exception { given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) .willReturn(new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(expectedAuth); - try { - wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials())); - fail("Expected Exception"); - } - catch (ServletException success) { - assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth); - verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler); - verify(this.request, times(0)).login(anyString(), anyString()); - } + assertThatExceptionOfType(ServletException.class).isThrownBy( + () -> wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials()))); + assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth); + verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler); + verify(this.request, times(0)).login(anyString(), anyString()); } @Test @@ -195,13 +191,8 @@ public void loginFail() throws Exception { AuthenticationException authException = new BadCredentialsException("Invalid"); given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) .willThrow(authException); - try { - wrappedRequest().login("invalid", "credentials"); - fail("Expected Exception"); - } - catch (ServletException success) { - assertThat(success.getCause()).isEqualTo(authException); - } + assertThatExceptionOfType(ServletException.class) + .isThrownBy(() -> wrappedRequest().login("invalid", "credentials")).withCause(authException); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler); verify(this.request, times(0)).login(anyString(), anyString()); @@ -226,13 +217,8 @@ public void loginNullAuthenticationManagerFail() throws Exception { String password = "password"; ServletException authException = new ServletException("Failed Login"); willThrow(authException).given(this.request).login(username, password); - try { - wrappedRequest().login(username, password); - fail("Expected Exception"); - } - catch (ServletException success) { - assertThat(success).isEqualTo(authException); - } + assertThatExceptionOfType(ServletException.class).isThrownBy(() -> wrappedRequest().login(username, password)) + .isEqualTo(authException); verifyZeroInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler); } diff --git a/web/src/test/java/org/springframework/security/web/util/ThrowableAnalyzerTests.java b/web/src/test/java/org/springframework/security/web/util/ThrowableAnalyzerTests.java index 893d8db75af..7928e7203c8 100644 --- a/web/src/test/java/org/springframework/security/web/util/ThrowableAnalyzerTests.java +++ b/web/src/test/java/org/springframework/security/web/util/ThrowableAnalyzerTests.java @@ -22,7 +22,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Test cases for {@link ThrowableAnalyzer}. @@ -78,22 +78,15 @@ protected void initExtractorMap() { @Test public void testRegisterExtractorWithInvalidExtractor() { - try { - new ThrowableAnalyzer() { - /** - * @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap() - */ - @Override - protected void initExtractorMap() { - // null is no valid extractor - super.registerExtractor(Exception.class, null); - } - }; - fail("IllegalArgumentExpected"); - } - catch (IllegalArgumentException ex) { - // ok - } + assertThatIllegalArgumentException().isThrownBy(() -> new ThrowableAnalyzer() { + + @Override + protected void initExtractorMap() { + // null is no valid extractor + super.registerExtractor(Exception.class, null); + } + + }); } @Test @@ -199,25 +192,15 @@ public void testVerifyThrowableHierarchyWithCompatibleType() { @Test public void testVerifyThrowableHierarchyWithNull() { - try { - ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException ex) { - // ok - } + assertThatIllegalArgumentException() + .isThrownBy(() -> ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class)); } @Test public void testVerifyThrowableHierarchyWithNonmatchingType() { Throwable throwable = new IllegalStateException("Test"); - try { - ThrowableAnalyzer.verifyThrowableHierarchy(throwable, InvocationTargetException.class); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException ex) { - // ok - } + assertThatIllegalArgumentException().isThrownBy( + () -> ThrowableAnalyzer.verifyThrowableHierarchy(throwable, InvocationTargetException.class)); } /**