1
0
mirror of synced 2026-05-22 21:33:16 +00:00

Migrate to BDD Mockito

Migrate Mockito imports to use the BDD variant. This aligns better with
the "given" / "when" / "then" style used in most tests since the "given"
block now uses Mockito `given(...)` calls.

The commit also updates a few tests that were accidentally using
Power Mockito when regular Mockito could be used.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-07-27 12:53:19 -07:00
committed by Rob Winch
parent c12ced6aaa
commit db55ef4b3b
259 changed files with 2126 additions and 2125 deletions
@@ -22,9 +22,9 @@ import javax.naming.directory.DirContext;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link LdapUtils}
@@ -36,7 +36,7 @@ public class LdapUtilsTests {
@Test
public void testCloseContextSwallowsNamingException() throws Exception {
final DirContext dirCtx = mock(DirContext.class);
doThrow(new NamingException()).when(dirCtx).close();
willThrow(new NamingException()).given(dirCtx).close();
LdapUtils.closeContext(dirCtx);
}
@@ -45,7 +45,7 @@ public class LdapUtilsTests {
public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception {
final DirContext mockCtx = mock(DirContext.class);
when(mockCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
given(mockCtx.getNameInNamespace()).willReturn("dc=springframework,dc=org");
assertThat(LdapUtils.getRelativeName("dc=springframework,dc=org", mockCtx)).isEqualTo("");
}
@@ -53,7 +53,7 @@ public class LdapUtilsTests {
@Test
public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception {
final DirContext mockCtx = mock(DirContext.class);
when(mockCtx.getNameInNamespace()).thenReturn("");
given(mockCtx.getNameInNamespace()).willReturn("");
assertThat(LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx))
.isEqualTo("cn=jane,dc=springframework,dc=org");
@@ -62,7 +62,7 @@ public class LdapUtilsTests {
@Test
public void testGetRelativeNameWorksWithArbitrarySpaces() throws Exception {
final DirContext mockCtx = mock(DirContext.class);
when(mockCtx.getNameInNamespace()).thenReturn("dc=springsecurity,dc = org");
given(mockCtx.getNameInNamespace()).willReturn("dc=springsecurity,dc = org");
assertThat(LdapUtils.getRelativeName("cn=jane smith, dc = springsecurity , dc=org", mockCtx))
.isEqualTo("cn=jane smith");
@@ -33,8 +33,8 @@ import org.springframework.ldap.core.DistinguishedName;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SpringSecurityLdapTemplateTests {
@@ -60,11 +60,11 @@ public class SpringSecurityLdapTemplateTests {
Object[] params = new Object[] {};
DirContextAdapter searchResultObject = mock(DirContextAdapter.class);
when(this.ctx.search(any(DistinguishedName.class), eq(filter), eq(params), this.searchControls.capture()))
.thenReturn(this.resultsEnum);
when(this.resultsEnum.hasMore()).thenReturn(true, false);
when(this.resultsEnum.next()).thenReturn(this.searchResult);
when(this.searchResult.getObject()).thenReturn(searchResultObject);
given(this.ctx.search(any(DistinguishedName.class), eq(filter), eq(params), this.searchControls.capture()))
.willReturn(this.resultsEnum);
given(this.resultsEnum.hasMore()).willReturn(true, false);
given(this.resultsEnum.next()).willReturn(this.searchResult);
given(this.searchResult.getObject()).willReturn(searchResultObject);
SpringSecurityLdapTemplate.searchForSingleEntryInternal(this.ctx, mock(SearchControls.class), base, filter,
params);
@@ -37,8 +37,8 @@ import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link LdapAuthenticationProvider}.
@@ -89,7 +89,7 @@ public class LdapAuthenticationProviderTests {
public void usernameNotFoundExceptionIsHiddenByDefault() {
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
when(authenticator.authenticate(joe)).thenThrow(new UsernameNotFoundException("nobody"));
given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
provider.authenticate(joe);
@@ -99,7 +99,7 @@ public class LdapAuthenticationProviderTests {
public void usernameNotFoundExceptionIsNotHiddenIfConfigured() {
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
when(authenticator.authenticate(joe)).thenThrow(new UsernameNotFoundException("nobody"));
given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
provider.setHideUserNotFoundExceptions(false);
@@ -165,7 +165,7 @@ public class LdapAuthenticationProviderTests {
"benspassword");
LdapAuthenticator mockAuthenticator = mock(LdapAuthenticator.class);
CommunicationException expectedCause = new CommunicationException(new javax.naming.CommunicationException());
when(mockAuthenticator.authenticate(authRequest)).thenThrow(expectedCause);
given(mockAuthenticator.authenticate(authRequest)).willThrow(expectedCause);
LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(mockAuthenticator);
try {
@@ -29,8 +29,8 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -49,15 +49,15 @@ public class PasswordComparisonAuthenticatorMockTests {
authenticator.setUserDnPatterns(new String[] { "cn={0},ou=people" });
// Get the mock to return an empty attribute set
when(source.getReadOnlyContext()).thenReturn(dirCtx);
when(dirCtx.getAttributes(eq("cn=Bob,ou=people"), any(String[].class))).thenReturn(attrs);
when(dirCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
given(source.getReadOnlyContext()).willReturn(dirCtx);
given(dirCtx.getAttributes(eq("cn=Bob,ou=people"), any(String[].class))).willReturn(attrs);
given(dirCtx.getNameInNamespace()).willReturn("dc=springframework,dc=org");
// Setup a single return value (i.e. success)
final NamingEnumeration searchResults = new BasicAttributes("", null).getAll();
when(dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class),
any(SearchControls.class))).thenReturn(searchResults);
given(dirCtx.search(eq("cn=Bob,ou=people"), eq("(userPassword={0})"), any(Object[].class),
any(SearchControls.class))).willReturn(searchResults);
authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob", "bobspassword"));
}
@@ -56,9 +56,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -100,12 +100,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
String customSearchFilter = "(&(objectClass=user)(sAMAccountName={0}))";
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
DirContextAdapter dca = new DirContextAdapter();
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
when(ctx.search(any(Name.class), eq(customSearchFilter), any(Object[].class), any(SearchControls.class)))
.thenReturn(new MockNamingEnumeration(sr));
given(ctx.search(any(Name.class), eq(customSearchFilter), any(Object[].class), any(SearchControls.class)))
.willReturn(new MockNamingEnumeration(sr));
ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider(
"mydomain.eu", "ldap://192.168.1.200/");
@@ -125,12 +125,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
final String defaultSearchFilter = "(&(objectClass=user)(userPrincipalName={0}))";
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
DirContextAdapter dca = new DirContextAdapter();
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
when(ctx.search(any(Name.class), eq(defaultSearchFilter), any(Object[].class), any(SearchControls.class)))
.thenReturn(new MockNamingEnumeration(sr));
given(ctx.search(any(Name.class), eq(defaultSearchFilter), any(Object[].class), any(SearchControls.class)))
.willReturn(new MockNamingEnumeration(sr));
ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider(
"mydomain.eu", "ldap://192.168.1.200/");
@@ -153,12 +153,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
ArgumentCaptor<Object[]> captor = ArgumentCaptor.forClass(Object[].class);
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
DirContextAdapter dca = new DirContextAdapter();
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
when(ctx.search(any(Name.class), eq(defaultSearchFilter), captor.capture(), any(SearchControls.class)))
.thenReturn(new MockNamingEnumeration(sr));
given(ctx.search(any(Name.class), eq(defaultSearchFilter), captor.capture(), any(SearchControls.class)))
.willReturn(new MockNamingEnumeration(sr));
ActiveDirectoryLdapAuthenticationProvider customProvider = new ActiveDirectoryLdapAuthenticationProvider(
"mydomain.eu", "ldap://192.168.1.200/");
@@ -186,12 +186,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
public void nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal() throws Exception {
this.provider = new ActiveDirectoryLdapAuthenticationProvider(null, "ldap://192.168.1.200/");
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
DirContextAdapter dca = new DirContextAdapter();
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
when(ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class),
any(SearchControls.class))).thenReturn(new MockNamingEnumeration(sr));
given(ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class),
any(SearchControls.class))).willReturn(new MockNamingEnumeration(sr));
this.provider.contextFactory = createContextFactoryReturning(ctx);
try {
@@ -207,9 +207,9 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Test(expected = BadCredentialsException.class)
public void failedUserSearchCausesBadCredentials() throws Exception {
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenThrow(new NameNotFoundException());
given(ctx.getNameInNamespace()).willReturn("");
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.willThrow(new NameNotFoundException());
this.provider.contextFactory = createContextFactoryReturning(ctx);
@@ -220,9 +220,9 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Test(expected = BadCredentialsException.class)
public void noUserSearchCausesUsernameNotFound() throws Exception {
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenReturn(new EmptyEnumeration<>());
given(ctx.getNameInNamespace()).willReturn("");
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.willReturn(new EmptyEnumeration<>());
this.provider.contextFactory = createContextFactoryReturning(ctx);
@@ -239,14 +239,14 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Test(expected = IncorrectResultSizeDataAccessException.class)
public void duplicateUserSearchCausesError() throws Exception {
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
NamingEnumeration<SearchResult> searchResults = mock(NamingEnumeration.class);
when(searchResults.hasMore()).thenReturn(true, true, false);
given(searchResults.hasMore()).willReturn(true, true, false);
SearchResult searchResult = mock(SearchResult.class);
when(searchResult.getObject()).thenReturn(new DirContextAdapter("ou=1"), new DirContextAdapter("ou=2"));
when(searchResults.next()).thenReturn(searchResult);
when(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenReturn(searchResults);
given(searchResult.getObject()).willReturn(new DirContextAdapter("ou=1"), new DirContextAdapter("ou=2"));
given(searchResults.next()).willReturn(searchResult);
given(ctx.search(any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
.willReturn(searchResults);
this.provider.contextFactory = createContextFactoryReturning(ctx);
@@ -440,14 +440,14 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
private void checkAuthentication(String rootDn, ActiveDirectoryLdapAuthenticationProvider provider)
throws NamingException {
DirContext ctx = mock(DirContext.class);
when(ctx.getNameInNamespace()).thenReturn("");
given(ctx.getNameInNamespace()).willReturn("");
DirContextAdapter dca = new DirContextAdapter();
SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
@SuppressWarnings("deprecation")
DistinguishedName searchBaseDn = new DistinguishedName(rootDn);
when(ctx.search(eq(searchBaseDn), any(String.class), any(Object[].class), any(SearchControls.class)))
.thenReturn(new MockNamingEnumeration(sr)).thenReturn(new MockNamingEnumeration(sr));
given(ctx.search(eq(searchBaseDn), any(String.class), any(Object[].class), any(SearchControls.class)))
.willReturn(new MockNamingEnumeration(sr)).willReturn(new MockNamingEnumeration(sr));
provider.contextFactory = createContextFactoryReturning(ctx);
@@ -30,10 +30,10 @@ import org.springframework.ldap.UncategorizedLdapException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -69,17 +69,17 @@ public class PasswordPolicyAwareContextSourceTests {
@Test(expected = UncategorizedLdapException.class)
public void standardExceptionIsPropagatedWhenExceptionRaisedAndNoControlsAreSet() throws Exception {
doThrow(new NamingException("some LDAP exception")).when(this.ctx).reconnect(any(Control[].class));
willThrow(new NamingException("some LDAP exception")).given(this.ctx).reconnect(any(Control[].class));
this.ctxSource.getContext("user", "ignored");
}
@Test(expected = PasswordPolicyException.class)
public void lockedPasswordPolicyControlRaisesPasswordPolicyException() throws Exception {
when(this.ctx.getResponseControls()).thenReturn(new Control[] {
given(this.ctx.getResponseControls()).willReturn(new Control[] {
new PasswordPolicyResponseControl(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL) });
doThrow(new NamingException("locked message")).when(this.ctx).reconnect(any(Control[].class));
willThrow(new NamingException("locked message")).given(this.ctx).reconnect(any(Control[].class));
this.ctxSource.getContext("user", "ignored");
}
@@ -20,8 +20,8 @@ import javax.naming.ldap.Control;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -33,7 +33,7 @@ public class PasswordPolicyControlFactoryTests {
PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory();
Control wrongCtrl = mock(Control.class);
when(wrongCtrl.getID()).thenReturn("wrongId");
given(wrongCtrl.getID()).willReturn("wrongId");
assertThat(ctrlFactory.getControlInstance(wrongCtrl)).isNull();
}
@@ -42,8 +42,8 @@ public class PasswordPolicyControlFactoryTests {
PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory();
Control control = mock(Control.class);
when(control.getID()).thenReturn(PasswordPolicyControl.OID);
when(control.getEncodedValue()).thenReturn(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL);
given(control.getID()).willReturn(PasswordPolicyControl.OID);
given(control.getEncodedValue()).willReturn(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL);
Control result = ctrlFactory.getControlInstance(control);
assertThat(result).isNotNull();
assertThat(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL).isEqualTo(result.getEncodedValue());
@@ -28,8 +28,8 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.ldap.authentication.UserDetailsServiceLdapAuthoritiesPopulator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -40,9 +40,9 @@ public class UserDetailsServiceLdapAuthoritiesPopulatorTests {
public void delegationToUserDetailsServiceReturnsCorrectRoles() {
UserDetailsService uds = mock(UserDetailsService.class);
UserDetails user = mock(UserDetails.class);
when(uds.loadUserByUsername("joe")).thenReturn(user);
given(uds.loadUserByUsername("joe")).willReturn(user);
List authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
when(user.getAuthorities()).thenReturn(authorities);
given(user.getAuthorities()).willReturn(authorities);
UserDetailsServiceLdapAuthoritiesPopulator populator = new UserDetailsServiceLdapAuthoritiesPopulator(uds);
Collection<? extends GrantedAuthority> auths = populator.getGrantedAuthorities(new DirContextAdapter(), "joe");