1
0
mirror of synced 2026-05-22 13:23:17 +00:00

Replace try/catch with AssertJ

Replace manual try/catch/fail blocks with AssertJ calls.
This commit is contained in:
Phillip Webb
2020-09-10 12:06:07 -07:00
committed by Josh Cummings
parent d9276ed8f3
commit 910b81928f
98 changed files with 717 additions and 2122 deletions
@@ -38,7 +38,7 @@ import org.springframework.test.context.ContextConfiguration;
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 class SpringSecurityLdapTemplateITests {
@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
@@ -33,7 +33,7 @@ import org.springframework.test.context.ContextConfiguration;
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 class BindAuthenticatorTests {
@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 class BindAuthenticatorTests {
@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
@@ -36,7 +36,7 @@ import org.springframework.test.context.ContextConfiguration;
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 class PasswordComparisonAuthenticatorTests {
.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)
@@ -33,6 +33,7 @@ import org.springframework.util.FileCopyUtils;
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 class ApacheDSContainerTests {
List<Integer> 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
@@ -29,7 +29,7 @@ import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
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 class UnboundIdContainerLdifTests {
@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
@@ -39,7 +39,7 @@ import org.springframework.test.context.ContextConfiguration;
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 class LdapUserDetailsManagerTests {
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);
@@ -36,7 +36,7 @@ import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
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 class LdapAuthenticationProviderTests {
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 class LdapAuthenticationProviderTests {
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 {
@@ -54,7 +54,7 @@ import org.springframework.security.core.Authentication;
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 class ActiveDirectoryLdapAuthenticationProviderTests {
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 class ActiveDirectoryLdapAuthenticationProviderTests {
@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 class ActiveDirectoryLdapAuthenticationProviderTests {
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 class ActiveDirectoryLdapAuthenticationProviderTests {
Hashtable<String, Object> 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) {