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

View File

@@ -24,8 +24,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -55,7 +55,7 @@ public class SecurityExpressionRootTests {
public void rememberMeIsCorrectlyDetected() {
AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
this.root.setTrustResolver(atr);
when(atr.isRememberMe(JOE)).thenReturn(true);
given(atr.isRememberMe(JOE)).willReturn(true);
assertThat(this.root.isRememberMe()).isTrue();
assertThat(this.root.isFullyAuthenticated()).isFalse();
}

View File

@@ -37,10 +37,10 @@ import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DefaultMethodSecurityExpressionHandlerTests {
@@ -59,8 +59,8 @@ public class DefaultMethodSecurityExpressionHandlerTests {
@Before
public void setup() {
this.handler = new DefaultMethodSecurityExpressionHandler();
when(this.methodInvocation.getThis()).thenReturn(new Foo());
when(this.methodInvocation.getMethod()).thenReturn(Foo.class.getMethods()[0]);
given(this.methodInvocation.getThis()).willReturn(new Foo());
given(this.methodInvocation.getMethod()).willReturn(Foo.class.getMethods()[0]);
}
@After

View File

@@ -29,8 +29,8 @@ import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for {@link MethodSecurityExpressionRoot}
@@ -69,13 +69,13 @@ public class MethodSecurityExpressionRootTests {
@Test
public void isAnonymousReturnsTrueIfTrustResolverReportsAnonymous() {
when(this.trustResolver.isAnonymous(this.user)).thenReturn(true);
given(this.trustResolver.isAnonymous(this.user)).willReturn(true);
assertThat(this.root.isAnonymous()).isTrue();
}
@Test
public void isAnonymousReturnsFalseIfTrustResolverReportsNonAnonymous() {
when(this.trustResolver.isAnonymous(this.user)).thenReturn(false);
given(this.trustResolver.isAnonymous(this.user)).willReturn(false);
assertThat(this.root.isAnonymous()).isFalse();
}
@@ -85,7 +85,7 @@ public class MethodSecurityExpressionRootTests {
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
this.ctx.setVariable("domainObject", dummyDomainObject);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(this.user, dummyDomainObject, "ignored")).thenReturn(false);
given(pe.hasPermission(this.user, dummyDomainObject, "ignored")).willReturn(false);
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isFalse();
@@ -97,7 +97,7 @@ public class MethodSecurityExpressionRootTests {
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
this.ctx.setVariable("domainObject", dummyDomainObject);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(this.user, dummyDomainObject, "ignored")).thenReturn(true);
given(pe.hasPermission(this.user, dummyDomainObject, "ignored")).willReturn(true);
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isTrue();
}
@@ -108,8 +108,7 @@ public class MethodSecurityExpressionRootTests {
this.ctx.setVariable("domainObject", dummyDomainObject);
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(eq(this.user), eq(dummyDomainObject), any(Integer.class))).thenReturn(true)
.thenReturn(true).thenReturn(false);
given(pe.hasPermission(eq(this.user), eq(dummyDomainObject), any(Integer.class))).willReturn(true, true, false);
Expression e = this.parser.parseExpression("hasPermission(#domainObject, 0xA)");
// evaluator returns true
@@ -133,8 +132,8 @@ public class MethodSecurityExpressionRootTests {
Integer i = 2;
PermissionEvaluator pe = mock(PermissionEvaluator.class);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(this.user, targetObject, i)).thenReturn(true).thenReturn(false);
when(pe.hasPermission(this.user, "x", i)).thenReturn(true);
given(pe.hasPermission(this.user, targetObject, i)).willReturn(true, false);
given(pe.hasPermission(this.user, "x", i)).willReturn(true);
Expression e = this.parser.parseExpression("hasPermission(this, 2)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();

View File

@@ -51,12 +51,12 @@ import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link MethodSecurityInterceptor}.
@@ -150,21 +150,21 @@ public class MethodSecurityInterceptorTests {
@Test(expected = IllegalArgumentException.class)
public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation() throws Throwable {
when(this.mds.supports(MethodInvocation.class)).thenReturn(false);
given(this.mds.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation() throws Exception {
when(this.mds.supports(MethodInvocation.class)).thenReturn(true);
when(this.adm.supports(MethodInvocation.class)).thenReturn(false);
given(this.mds.supports(MethodInvocation.class)).willReturn(true);
given(this.adm.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation() throws Exception {
final RunAsManager ram = mock(RunAsManager.class);
when(ram.supports(MethodInvocation.class)).thenReturn(false);
given(ram.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.setRunAsManager(ram);
this.interceptor.afterPropertiesSet();
}
@@ -172,21 +172,21 @@ public class MethodSecurityInterceptorTests {
@Test(expected = IllegalArgumentException.class)
public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation() throws Exception {
final AfterInvocationManager aim = mock(AfterInvocationManager.class);
when(aim.supports(MethodInvocation.class)).thenReturn(false);
given(aim.supports(MethodInvocation.class)).willReturn(false);
this.interceptor.setAfterInvocationManager(aim);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes() throws Exception {
when(this.adm.supports(any(ConfigAttribute.class))).thenReturn(false);
given(this.adm.supports(any(ConfigAttribute.class))).willReturn(false);
this.interceptor.afterPropertiesSet();
}
@Test
public void validationNotAttemptedIfIsValidateConfigAttributesSetToFalse() throws Exception {
when(this.adm.supports(MethodInvocation.class)).thenReturn(true);
when(this.mds.supports(MethodInvocation.class)).thenReturn(true);
given(this.adm.supports(MethodInvocation.class)).willReturn(true);
given(this.mds.supports(MethodInvocation.class)).willReturn(true);
this.interceptor.setValidateConfigAttributes(false);
this.interceptor.afterPropertiesSet();
verify(this.mds, never()).getAllConfigAttributes();
@@ -195,9 +195,9 @@ public class MethodSecurityInterceptorTests {
@Test
public void validationNotAttemptedIfMethodSecurityMetadataSourceReturnsNullForAttributes() throws Exception {
when(this.adm.supports(MethodInvocation.class)).thenReturn(true);
when(this.mds.supports(MethodInvocation.class)).thenReturn(true);
when(this.mds.getAllConfigAttributes()).thenReturn(null);
given(this.adm.supports(MethodInvocation.class)).willReturn(true);
given(this.mds.supports(MethodInvocation.class)).willReturn(true);
given(this.mds.getAllConfigAttributes()).willReturn(null);
this.interceptor.setValidateConfigAttributes(true);
this.interceptor.afterPropertiesSet();
@@ -226,7 +226,7 @@ public class MethodSecurityInterceptorTests {
SecurityContextHolder.getContext().setAuthentication(token);
mdsReturnsUserRole();
when(this.authman.authenticate(token)).thenThrow(new BadCredentialsException("rejected"));
given(this.authman.authenticate(token)).willThrow(new BadCredentialsException("rejected"));
this.advisedTarget.makeLowerCase("HELLO");
}
@@ -253,8 +253,8 @@ public class MethodSecurityInterceptorTests {
// so test would fail)
createTarget(true);
mdsReturnsUserRole();
when(this.authman.authenticate(this.token)).thenReturn(this.token);
doThrow(new AccessDeniedException("rejected")).when(this.adm).decide(any(Authentication.class),
given(this.authman.authenticate(this.token)).willReturn(this.token);
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(any(Authentication.class),
any(MethodInvocation.class), any(List.class));
try {
@@ -281,7 +281,7 @@ public class MethodSecurityInterceptorTests {
TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
String result = this.advisedTarget.makeUpperCase("hello");
assertThat(result).isEqualTo("HELLO org.springframework.security.access.intercept.RunAsUserToken true");
@@ -294,7 +294,7 @@ public class MethodSecurityInterceptorTests {
@Test
public void runAsReplacementCleansAfterException() {
createTarget(true);
when(this.realTarget.makeUpperCase(anyString())).thenThrow(new RuntimeException());
given(this.realTarget.makeUpperCase(anyString())).willThrow(new RuntimeException());
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
@@ -303,7 +303,7 @@ public class MethodSecurityInterceptorTests {
TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
try {
this.advisedTarget.makeUpperCase("hello");
@@ -333,7 +333,7 @@ public class MethodSecurityInterceptorTests {
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
when(mi.proceed()).thenThrow(new Throwable());
given(mi.proceed()).willThrow(new Throwable());
try {
this.interceptor.invoke(mi);
@@ -346,11 +346,11 @@ public class MethodSecurityInterceptorTests {
}
void mdsReturnsNull() {
when(this.mds.getAttributes(any(MethodInvocation.class))).thenReturn(null);
given(this.mds.getAttributes(any(MethodInvocation.class))).willReturn(null);
}
void mdsReturnsUserRole() {
when(this.mds.getAttributes(any(MethodInvocation.class))).thenReturn(SecurityConfig.createList("ROLE_USER"));
given(this.mds.getAttributes(any(MethodInvocation.class))).willReturn(SecurityConfig.createList("ROLE_USER"));
}
}

View File

@@ -25,8 +25,8 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.method.MethodSecurityMetadataSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link MethodSecurityMetadataSourceAdvisor}.
@@ -41,7 +41,7 @@ public class MethodSecurityMetadataSourceAdvisorTests {
Method method = clazz.getMethod("makeLowerCase", new Class[] { String.class });
MethodSecurityMetadataSource mds = mock(MethodSecurityMetadataSource.class);
when(mds.getAttributes(method, clazz)).thenReturn(null);
given(mds.getAttributes(method, clazz)).willReturn(null);
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor("", mds, "");
assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isFalse();
}
@@ -52,7 +52,7 @@ public class MethodSecurityMetadataSourceAdvisorTests {
Method method = clazz.getMethod("countLength", new Class[] { String.class });
MethodSecurityMetadataSource mds = mock(MethodSecurityMetadataSource.class);
when(mds.getAttributes(method, clazz)).thenReturn(SecurityConfig.createList("ROLE_A"));
given(mds.getAttributes(method, clazz)).willReturn(SecurityConfig.createList("ROLE_A"));
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor("", mds, "");
assertThat(advisor.getPointcut().getMethodMatcher().matches(method, clazz)).isTrue();
}

View File

@@ -48,12 +48,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link AspectJMethodSecurityInterceptor}.
@@ -91,17 +91,17 @@ public class AspectJMethodSecurityInterceptorTests {
this.joinPoint = mock(ProceedingJoinPoint.class); // new MockJoinPoint(new
// TargetObject(), method);
Signature sig = mock(Signature.class);
when(sig.getDeclaringType()).thenReturn(TargetObject.class);
given(sig.getDeclaringType()).willReturn(TargetObject.class);
JoinPoint.StaticPart staticPart = mock(JoinPoint.StaticPart.class);
when(this.joinPoint.getSignature()).thenReturn(sig);
when(this.joinPoint.getStaticPart()).thenReturn(staticPart);
given(this.joinPoint.getSignature()).willReturn(sig);
given(this.joinPoint.getStaticPart()).willReturn(staticPart);
CodeSignature codeSig = mock(CodeSignature.class);
when(codeSig.getName()).thenReturn("countLength");
when(codeSig.getDeclaringType()).thenReturn(TargetObject.class);
when(codeSig.getParameterTypes()).thenReturn(new Class[] { String.class });
when(staticPart.getSignature()).thenReturn(codeSig);
when(this.mds.getAttributes(any())).thenReturn(SecurityConfig.createList("ROLE_USER"));
when(this.authman.authenticate(this.token)).thenReturn(this.token);
given(codeSig.getName()).willReturn("countLength");
given(codeSig.getDeclaringType()).willReturn(TargetObject.class);
given(codeSig.getParameterTypes()).willReturn(new Class[] { String.class });
given(staticPart.getSignature()).willReturn(codeSig);
given(this.mds.getAttributes(any())).willReturn(SecurityConfig.createList("ROLE_USER"));
given(this.authman.authenticate(this.token)).willReturn(this.token);
}
@After
@@ -122,7 +122,7 @@ public class AspectJMethodSecurityInterceptorTests {
@SuppressWarnings("unchecked")
@Test
public void callbackIsNotInvokedWhenPermissionDenied() {
doThrow(new AccessDeniedException("denied")).when(this.adm).decide(any(), any(), any());
willThrow(new AccessDeniedException("denied")).given(this.adm).decide(any(), any(), any());
SecurityContextHolder.getContext().setAuthentication(this.token);
try {
@@ -139,8 +139,8 @@ public class AspectJMethodSecurityInterceptorTests {
TargetObject to = new TargetObject();
Method m = ClassUtils.getMethodIfAvailable(TargetObject.class, "countLength", new Class[] { String.class });
when(this.joinPoint.getTarget()).thenReturn(to);
when(this.joinPoint.getArgs()).thenReturn(new Object[] { "Hi" });
given(this.joinPoint.getTarget()).willReturn(to);
given(this.joinPoint.getArgs()).willReturn(new Object[] { "Hi" });
MethodInvocationAdapter mia = new MethodInvocationAdapter(this.joinPoint);
assertThat(mia.getArguments()[0]).isEqualTo("Hi");
assertThat(mia.getStaticPart()).isEqualTo(m);
@@ -156,7 +156,7 @@ public class AspectJMethodSecurityInterceptorTests {
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
when(this.aspectJCallback.proceedWithObject()).thenThrow(new RuntimeException());
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
try {
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
@@ -179,8 +179,8 @@ public class AspectJMethodSecurityInterceptorTests {
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(),
TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(this.aspectJCallback.proceedWithObject()).thenThrow(new RuntimeException());
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
try {
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
@@ -205,8 +205,8 @@ public class AspectJMethodSecurityInterceptorTests {
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(),
TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(this.joinPoint.proceed()).thenThrow(new RuntimeException());
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.joinPoint.proceed()).willThrow(new RuntimeException());
try {
this.interceptor.invoke(this.joinPoint);

View File

@@ -38,9 +38,9 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.util.MethodInvocationUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests
@@ -80,7 +80,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
when(this.mds.getAttributes(mi)).thenReturn(this.role);
given(this.mds.getAttributes(mi)).willReturn(this.role);
mipe.setSecurityInterceptor(this.interceptor);
mipe.afterPropertiesSet();
@@ -94,7 +94,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
"makeLowerCase", new Class[] { String.class }, new Object[] { "Hello world" });
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(this.interceptor);
when(this.mds.getAttributes(mi)).thenReturn(this.role);
given(this.mds.getAttributes(mi)).willReturn(this.role);
assertThat(mipe.isAllowed(mi, this.token)).isTrue();
}
@@ -105,8 +105,8 @@ public class MethodInvocationPrivilegeEvaluatorTests {
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(this.interceptor);
when(this.mds.getAttributes(mi)).thenReturn(this.role);
doThrow(new AccessDeniedException("rejected")).when(this.adm).decide(this.token, mi, this.role);
given(this.mds.getAttributes(mi)).willReturn(this.role);
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(this.token, mi, this.role);
assertThat(mipe.isAllowed(mi, this.token)).isFalse();
}
@@ -118,8 +118,8 @@ public class MethodInvocationPrivilegeEvaluatorTests {
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(this.interceptor);
when(this.mds.getAttributes(mi)).thenReturn(this.role);
doThrow(new AccessDeniedException("rejected")).when(this.adm).decide(this.token, mi, this.role);
given(this.mds.getAttributes(mi)).willReturn(this.role);
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(this.token, mi, this.role);
assertThat(mipe.isAllowed(mi, this.token)).isFalse();
}

View File

@@ -29,8 +29,8 @@ import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -44,8 +44,8 @@ public class DelegatingMethodSecurityMetadataSourceTests {
public void returnsEmptyListIfDelegateReturnsNull() throws Exception {
List sources = new ArrayList();
MethodSecurityMetadataSource delegate = mock(MethodSecurityMetadataSource.class);
when(delegate.getAttributes(ArgumentMatchers.<Method>any(), ArgumentMatchers.any(Class.class)))
.thenReturn(null);
given(delegate.getAttributes(ArgumentMatchers.<Method>any(), ArgumentMatchers.any(Class.class)))
.willReturn(null);
sources.add(delegate);
this.mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);
@@ -63,7 +63,7 @@ public class DelegatingMethodSecurityMetadataSourceTests {
ConfigAttribute ca = mock(ConfigAttribute.class);
List attributes = Arrays.asList(ca);
Method toString = String.class.getMethod("toString");
when(delegate.getAttributes(toString, String.class)).thenReturn(attributes);
given(delegate.getAttributes(toString, String.class)).willReturn(attributes);
sources.add(delegate);
this.mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);

View File

@@ -31,8 +31,8 @@ import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link AffirmativeBased}.
@@ -61,12 +61,12 @@ public class AffirmativeBasedTests {
this.abstain = mock(AccessDecisionVoter.class);
this.deny = mock(AccessDecisionVoter.class);
when(this.grant.vote(any(Authentication.class), any(Object.class), any(List.class)))
.thenReturn(AccessDecisionVoter.ACCESS_GRANTED);
when(this.abstain.vote(any(Authentication.class), any(Object.class), any(List.class)))
.thenReturn(AccessDecisionVoter.ACCESS_ABSTAIN);
when(this.deny.vote(any(Authentication.class), any(Object.class), any(List.class)))
.thenReturn(AccessDecisionVoter.ACCESS_DENIED);
given(this.grant.vote(any(Authentication.class), any(Object.class), any(List.class)))
.willReturn(AccessDecisionVoter.ACCESS_GRANTED);
given(this.abstain.vote(any(Authentication.class), any(Object.class), any(List.class)))
.willReturn(AccessDecisionVoter.ACCESS_ABSTAIN);
given(this.deny.vote(any(Authentication.class), any(Object.class), any(List.class)))
.willReturn(AccessDecisionVoter.ACCESS_DENIED);
}
@Test

View File

@@ -27,10 +27,10 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests {@link AbstractAuthenticationToken}.
@@ -128,7 +128,7 @@ public class AbstractAuthenticationTokenTests {
String principalName = "test";
AuthenticatedPrincipal principal = mock(AuthenticatedPrincipal.class);
when(principal.getName()).thenReturn(principalName);
given(principal.getName()).willReturn(principalName);
MockAuthenticationImpl token = new MockAuthenticationImpl(principal, "Password", this.authorities);
assertThat(token.getName()).isEqualTo(principalName);

View File

@@ -29,7 +29,7 @@ import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -49,8 +49,8 @@ public class DelegatingReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenEmptyAndNotThenReturnsNotEmpty() {
when(this.delegate1.authenticate(any())).thenReturn(Mono.empty());
when(this.delegate2.authenticate(any())).thenReturn(Mono.just(this.authentication));
given(this.delegate1.authenticate(any())).willReturn(Mono.empty());
given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
this.delegate2);
@@ -62,8 +62,8 @@ public class DelegatingReactiveAuthenticationManagerTests {
public void authenticateWhenNotEmptyThenOtherDelegatesNotSubscribed() {
// delay to try and force delegate2 to finish (i.e. make sure we didn't use
// flatMap)
when(this.delegate1.authenticate(any()))
.thenReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
given(this.delegate1.authenticate(any()))
.willReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
this.delegate2);
@@ -73,7 +73,7 @@ public class DelegatingReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenBadCredentialsThenDelegate2NotInvokedAndError() {
when(this.delegate1.authenticate(any())).thenReturn(Mono.error(new BadCredentialsException("Test")));
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1,
this.delegate2);

View File

@@ -31,12 +31,12 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link ProviderManager}.
@@ -121,7 +121,7 @@ public class ProviderManagerTests {
public void constructorWhenUsingListOfThenNoException() {
List<AuthenticationProvider> providers = spy(ArrayList.class);
// List.of(null) in JDK 9 throws a NullPointerException
when(providers.contains(eq(null))).thenThrow(NullPointerException.class);
given(providers.contains(eq(null))).willThrow(NullPointerException.class);
providers.add(mock(AuthenticationProvider.class));
new ProviderManager(providers);
}
@@ -211,7 +211,7 @@ public class ProviderManagerTests {
public void parentAuthenticationIsUsedIfProvidersDontAuthenticate() {
AuthenticationManager parent = mock(AuthenticationManager.class);
Authentication authReq = mock(Authentication.class);
when(parent.authenticate(authReq)).thenReturn(authReq);
given(parent.authenticate(authReq)).willReturn(authReq);
ProviderManager mgr = new ProviderManager(Collections.singletonList(mock(AuthenticationProvider.class)),
parent);
assertThat(mgr.authenticate(authReq)).isSameAs(authReq);
@@ -238,7 +238,7 @@ public class ProviderManagerTests {
final Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
AuthenticationManager parent = mock(AuthenticationManager.class);
when(parent.authenticate(authReq)).thenThrow(new ProviderNotFoundException(""));
given(parent.authenticate(authReq)).willThrow(new ProviderNotFoundException(""));
// Set a provider that throws an exception - this is the exception we expect to be
// propagated
@@ -266,7 +266,7 @@ public class ProviderManagerTests {
// Set a provider that throws an exception - this is the exception we expect to be
// propagated
final BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
when(parent.authenticate(authReq)).thenThrow(expected);
given(parent.authenticate(authReq)).willThrow(expected);
try {
mgr.authenticate(authReq);
fail("Expected exception");
@@ -339,16 +339,16 @@ public class ProviderManagerTests {
private AuthenticationProvider createProviderWhichThrows(final AuthenticationException e) {
AuthenticationProvider provider = mock(AuthenticationProvider.class);
when(provider.supports(any(Class.class))).thenReturn(true);
when(provider.authenticate(any(Authentication.class))).thenThrow(e);
given(provider.supports(any(Class.class))).willReturn(true);
given(provider.authenticate(any(Authentication.class))).willThrow(e);
return provider;
}
private AuthenticationProvider createProviderWhichReturns(final Authentication a) {
AuthenticationProvider provider = mock(AuthenticationProvider.class);
when(provider.supports(any(Class.class))).thenReturn(true);
when(provider.authenticate(any(Authentication.class))).thenReturn(a);
given(provider.supports(any(Class.class))).willReturn(true);
given(provider.authenticate(any(Authentication.class))).willReturn(a);
return provider;
}

View File

@@ -28,7 +28,7 @@ import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -62,8 +62,8 @@ public class ReactiveAuthenticationManagerAdapterTests {
@Test
public void authenticateWhenSuccessThenSuccess() {
when(this.delegate.authenticate(any())).thenReturn(this.authentication);
when(this.authentication.isAuthenticated()).thenReturn(true);
given(this.delegate.authenticate(any())).willReturn(this.authentication);
given(this.authentication.isAuthenticated()).willReturn(true);
Authentication result = this.manager.authenticate(this.authentication).block();
@@ -72,7 +72,7 @@ public class ReactiveAuthenticationManagerAdapterTests {
@Test
public void authenticateWhenReturnNotAuthenticatedThenError() {
when(this.delegate.authenticate(any())).thenReturn(this.authentication);
given(this.delegate.authenticate(any())).willReturn(this.authentication);
Authentication result = this.manager.authenticate(this.authentication).block();
@@ -81,7 +81,7 @@ public class ReactiveAuthenticationManagerAdapterTests {
@Test
public void authenticateWhenBadCredentialsThenError() {
when(this.delegate.authenticate(any())).thenThrow(new BadCredentialsException("Failed"));
given(this.delegate.authenticate(any())).willThrow(new BadCredentialsException("Failed"));
Mono<Authentication> result = this.manager.authenticate(this.authentication);

View File

@@ -33,7 +33,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -69,7 +69,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Test
public void authenticateWhenUserNotFoundThenBadCredentials() {
when(this.repository.findByUsername(this.username)).thenReturn(Mono.empty());
given(this.repository.findByUsername(this.username)).willReturn(Mono.empty());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);
@@ -86,7 +86,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
.roles("USER")
.build();
// @formatter:on
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password + "INVALID");
@@ -103,7 +103,7 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
.roles("USER")
.build();
// @formatter:on
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);
@@ -115,9 +115,9 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Test
public void authenticateWhenPasswordEncoderAndSuccessThenSuccess() {
this.manager.setPasswordEncoder(this.passwordEncoder);
when(this.passwordEncoder.matches(any(), any())).thenReturn(true);
given(this.passwordEncoder.matches(any(), any())).willReturn(true);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);
@@ -129,9 +129,9 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Test
public void authenticateWhenPasswordEncoderAndFailThenFail() {
this.manager.setPasswordEncoder(this.passwordEncoder);
when(this.passwordEncoder.matches(any(), any())).thenReturn(false);
given(this.passwordEncoder.matches(any(), any())).willReturn(false);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);

View File

@@ -38,10 +38,10 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -78,7 +78,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Before
public void setup() {
this.manager = new UserDetailsRepositoryReactiveAuthenticationManager(this.userDetailsService);
when(this.scheduler.schedule(any())).thenAnswer(a -> {
given(this.scheduler.schedule(any())).willAnswer(a -> {
Runnable r = a.getArgument(0);
return Schedulers.immediate().schedule(r);
});
@@ -91,8 +91,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authentiateWhenCustomSchedulerThenUsed() {
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
when(this.encoder.matches(any(), any())).thenReturn(true);
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setScheduler(this.scheduler);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
@@ -106,11 +106,11 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenPasswordServiceThenUpdated() {
String encodedPassword = "encoded";
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
when(this.encoder.matches(any(), any())).thenReturn(true);
when(this.encoder.upgradeEncoding(any())).thenReturn(true);
when(this.encoder.encode(any())).thenReturn(encodedPassword);
when(this.userDetailsPasswordService.updatePassword(any(), any())).thenReturn(Mono.just(this.user));
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
given(this.encoder.upgradeEncoding(any())).willReturn(true);
given(this.encoder.encode(any())).willReturn(encodedPassword);
given(this.userDetailsPasswordService.updatePassword(any(), any())).willReturn(Mono.just(this.user));
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
@@ -124,8 +124,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenPasswordServiceAndBadCredentialsThenNotUpdated() {
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
when(this.encoder.matches(any(), any())).thenReturn(false);
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
@@ -138,9 +138,9 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenPasswordServiceAndUpgradeFalseThenNotUpdated() {
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
when(this.encoder.matches(any(), any())).thenReturn(true);
when(this.encoder.upgradeEncoding(any())).thenReturn(false);
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
given(this.encoder.upgradeEncoding(any())).willReturn(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
@@ -153,9 +153,9 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenPostAuthenticationChecksFail() {
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
doThrow(new LockedException("account is locked")).when(this.postAuthenticationChecks).check(any());
when(this.encoder.matches(any(), any())).thenReturn(true);
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
willThrow(new LockedException("account is locked")).given(this.postAuthenticationChecks).check(any());
given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setPostAuthenticationChecks(this.postAuthenticationChecks);
@@ -168,8 +168,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenPostAuthenticationChecksNotSet() {
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(this.user));
when(this.encoder.matches(any(), any())).thenReturn(true);
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
@@ -190,7 +190,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.accountExpired(true)
.build();
// @formatter:on
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(expiredUser));
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(expiredUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(expiredUser,
expiredUser.getPassword());
@@ -208,7 +208,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.accountLocked(true)
.build();
// @formatter:on
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(lockedUser));
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(lockedUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(lockedUser,
lockedUser.getPassword());
@@ -227,7 +227,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
.disabled(true)
.build();
// @formatter:on
when(this.userDetailsService.findByUsername(any())).thenReturn(Mono.just(disabledUser));
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(disabledUser));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(disabledUser,
disabledUser.getPassword());

View File

@@ -55,11 +55,11 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link DaoAuthenticationProvider}.
@@ -398,11 +398,11 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
when(encoder.matches(any(), any())).thenReturn(true);
when(encoder.upgradeEncoding(any())).thenReturn(true);
when(encoder.encode(any())).thenReturn(encodedPassword);
when(userDetailsService.loadUserByUsername(any())).thenReturn(user);
when(passwordManager.updatePassword(any(), any())).thenReturn(user);
given(encoder.matches(any(), any())).willReturn(true);
given(encoder.upgradeEncoding(any())).willReturn(true);
given(encoder.encode(any())).willReturn(encodedPassword);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
given(passwordManager.updatePassword(any(), any())).willReturn(user);
Authentication result = provider.authenticate(token);
@@ -423,8 +423,8 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
when(encoder.matches(any(), any())).thenReturn(false);
when(userDetailsService.loadUserByUsername(any())).thenReturn(user);
given(encoder.matches(any(), any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
assertThatThrownBy(() -> provider.authenticate(token)).isInstanceOf(BadCredentialsException.class);
@@ -444,9 +444,9 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
when(encoder.matches(any(), any())).thenReturn(true);
when(encoder.upgradeEncoding(any())).thenReturn(false);
when(userDetailsService.loadUserByUsername(any())).thenReturn(user);
given(encoder.matches(any(), any())).willReturn(true);
given(encoder.upgradeEncoding(any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
Authentication result = provider.authenticate(token);
@@ -564,7 +564,7 @@ public class DaoAuthenticationProviderTests {
public void testUserNotFoundEncodesPassword() throws Exception {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", "koala");
PasswordEncoder encoder = mock(PasswordEncoder.class);
when(encoder.encode(anyString())).thenReturn("koala");
given(encoder.encode(anyString())).willReturn("koala");
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false);
provider.setPasswordEncoder(encoder);

View File

@@ -47,11 +47,11 @@ import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class DefaultJaasAuthenticationProviderTests {
@@ -76,7 +76,7 @@ public class DefaultJaasAuthenticationProviderTests {
AppConfigurationEntry[] aces = new AppConfigurationEntry[] {
new AppConfigurationEntry(TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED,
Collections.<String, Object>emptyMap()) };
when(configuration.getAppConfigurationEntry(this.provider.getLoginContextName())).thenReturn(aces);
given(configuration.getAppConfigurationEntry(this.provider.getLoginContextName())).willReturn(aces);
this.token = new UsernamePasswordAuthenticationToken("user", "password");
ReflectionTestUtils.setField(this.provider, "log", this.log);
@@ -141,9 +141,9 @@ public class DefaultJaasAuthenticationProviderTests {
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
when(securityContext.getAuthentication()).thenReturn(token);
when(token.getLoginContext()).thenReturn(context);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
this.provider.onApplicationEvent(event);
@@ -170,7 +170,7 @@ public class DefaultJaasAuthenticationProviderTests {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
this.provider.handleLogout(event);
@@ -185,8 +185,8 @@ public class DefaultJaasAuthenticationProviderTests {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
when(securityContext.getAuthentication()).thenReturn(this.token);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(this.token);
this.provider.handleLogout(event);
@@ -202,8 +202,8 @@ public class DefaultJaasAuthenticationProviderTests {
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
when(securityContext.getAuthentication()).thenReturn(token);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
@@ -221,10 +221,10 @@ public class DefaultJaasAuthenticationProviderTests {
LoginContext context = mock(LoginContext.class);
LoginException loginException = new LoginException("Failed Login");
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
when(securityContext.getAuthentication()).thenReturn(token);
when(token.getLoginContext()).thenReturn(context);
doThrow(loginException).when(context).logout();
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
willThrow(loginException).given(context).logout();
this.provider.onApplicationEvent(event);

View File

@@ -47,8 +47,8 @@ import org.springframework.security.core.session.SessionDestroyedEvent;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for the JaasAuthenticationProvider
@@ -258,7 +258,7 @@ public class JaasAuthenticationProviderTests {
context.setAuthentication(token);
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(context));
given(event.getSecurityContexts()).willReturn(Arrays.asList(context));
this.jaasProvider.handleLogout(event);

View File

@@ -25,8 +25,8 @@ import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link RemoteAuthenticationManagerImpl}.
@@ -39,7 +39,7 @@ public class RemoteAuthenticationManagerImplTests {
public void testFailedAuthenticationReturnsRemoteAuthenticationException() {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
manager.setAuthenticationManager(am);
manager.attemptAuthentication("rod", "password");
@@ -65,7 +65,7 @@ public class RemoteAuthenticationManagerImplTests {
public void testSuccessfulAuthentication() {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenReturn(new TestingAuthenticationToken("u", "p", "A"));
given(am.authenticate(any(Authentication.class))).willReturn(new TestingAuthenticationToken("u", "p", "A"));
manager.setAuthenticationManager(am);
manager.attemptAuthentication("rod", "password");

View File

@@ -27,8 +27,8 @@ import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -45,7 +45,7 @@ public class AuthenticatedReactiveAuthorizationManagerTests {
@Test
public void checkWhenAuthenticatedThenReturnTrue() {
when(this.authentication.isAuthenticated()).thenReturn(true);
given(this.authentication.isAuthenticated()).willReturn(true);
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();

View File

@@ -29,7 +29,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -66,8 +66,8 @@ public class AuthorityReactiveAuthorizationManagerTests {
@Test
public void checkWhenHasAuthorityAndAuthenticatedAndNoAuthoritiesThenReturnFalse() {
when(this.authentication.isAuthenticated()).thenReturn(true);
when(this.authentication.getAuthorities()).thenReturn(Collections.emptyList());
given(this.authentication.isAuthenticated()).willReturn(true);
given(this.authentication.getAuthorities()).willReturn(Collections.emptyList());
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();

View File

@@ -26,8 +26,8 @@ import org.junit.Test;
import org.mockito.Mock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Abstract class for testing {@link DelegatingSecurityContextExecutorService} which
@@ -97,7 +97,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
@Test
public void submitCallable() {
when(this.delegate.submit(this.wrappedCallable)).thenReturn(this.expectedFutureObject);
given(this.delegate.submit(this.wrappedCallable)).willReturn(this.expectedFutureObject);
Future<Object> result = this.executor.submit(this.callable);
verify(this.delegate).submit(this.wrappedCallable);
assertThat(result).isEqualTo(this.expectedFutureObject);
@@ -105,7 +105,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
@Test
public void submitRunnableWithResult() {
when(this.delegate.submit(this.wrappedRunnable, this.resultArg)).thenReturn(this.expectedFutureObject);
given(this.delegate.submit(this.wrappedRunnable, this.resultArg)).willReturn(this.expectedFutureObject);
Future<Object> result = this.executor.submit(this.runnable, this.resultArg);
verify(this.delegate).submit(this.wrappedRunnable, this.resultArg);
assertThat(result).isEqualTo(this.expectedFutureObject);
@@ -114,7 +114,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
@Test
@SuppressWarnings("unchecked")
public void submitRunnable() {
when((Future<Object>) this.delegate.submit(this.wrappedRunnable)).thenReturn(this.expectedFutureObject);
given((Future<Object>) this.delegate.submit(this.wrappedRunnable)).willReturn(this.expectedFutureObject);
Future<?> result = this.executor.submit(this.runnable);
verify(this.delegate).submit(this.wrappedRunnable);
assertThat(result).isEqualTo(this.expectedFutureObject);
@@ -125,7 +125,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
public void invokeAll() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAll(wrappedCallables)).thenReturn(exectedResult);
given(this.delegate.invokeAll(wrappedCallables)).willReturn(exectedResult);
List<Future<Object>> result = this.executor.invokeAll(Arrays.asList(this.callable));
verify(this.delegate).invokeAll(wrappedCallables);
assertThat(result).isEqualTo(exectedResult);
@@ -136,7 +136,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
public void invokeAllTimeout() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAll(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
given(this.delegate.invokeAll(wrappedCallables, 1, TimeUnit.SECONDS)).willReturn(exectedResult);
List<Future<Object>> result = this.executor.invokeAll(Arrays.asList(this.callable), 1, TimeUnit.SECONDS);
verify(this.delegate).invokeAll(wrappedCallables, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(exectedResult);
@@ -147,7 +147,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
public void invokeAny() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAny(wrappedCallables)).thenReturn(exectedResult);
given(this.delegate.invokeAny(wrappedCallables)).willReturn(exectedResult);
Object result = this.executor.invokeAny(Arrays.asList(this.callable));
verify(this.delegate).invokeAny(wrappedCallables);
assertThat(result).isEqualTo(exectedResult);
@@ -158,7 +158,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
public void invokeAnyTimeout() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAny(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
given(this.delegate.invokeAny(wrappedCallables, 1, TimeUnit.SECONDS)).willReturn(exectedResult);
Object result = this.executor.invokeAny(Arrays.asList(this.callable), 1, TimeUnit.SECONDS);
verify(this.delegate).invokeAny(wrappedCallables, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(exectedResult);

View File

@@ -23,8 +23,8 @@ import org.junit.Test;
import org.mockito.Mock;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Abstract class for testing {@link DelegatingSecurityContextScheduledExecutorService}
@@ -52,8 +52,8 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
@SuppressWarnings("unchecked")
public void scheduleRunnable() {
when((ScheduledFuture<Object>) this.delegate.schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS))
.thenReturn(this.expectedResult);
given((ScheduledFuture<Object>) this.delegate.schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS))
.willReturn(this.expectedResult);
ScheduledFuture<?> result = this.executor.schedule(this.runnable, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS);
@@ -61,7 +61,7 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
public void scheduleCallable() {
when(this.delegate.schedule(this.wrappedCallable, 1, TimeUnit.SECONDS)).thenReturn(this.expectedResult);
given(this.delegate.schedule(this.wrappedCallable, 1, TimeUnit.SECONDS)).willReturn(this.expectedResult);
ScheduledFuture<Object> result = this.executor.schedule(this.callable, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).schedule(this.wrappedCallable, 1, TimeUnit.SECONDS);
@@ -70,8 +70,8 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
@SuppressWarnings("unchecked")
public void scheduleAtFixedRate() {
when((ScheduledFuture<Object>) this.delegate.scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS))
.thenReturn(this.expectedResult);
given((ScheduledFuture<Object>) this.delegate.scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS))
.willReturn(this.expectedResult);
ScheduledFuture<?> result = this.executor.scheduleAtFixedRate(this.runnable, 1, 2, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS);
@@ -80,8 +80,8 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Test
@SuppressWarnings("unchecked")
public void scheduleWithFixedDelay() {
when((ScheduledFuture<Object>) this.delegate.scheduleWithFixedDelay(this.wrappedRunnable, 1, 2,
TimeUnit.SECONDS)).thenReturn(this.expectedResult);
given((ScheduledFuture<Object>) this.delegate.scheduleWithFixedDelay(this.wrappedRunnable, 1, 2,
TimeUnit.SECONDS)).willReturn(this.expectedResult);
ScheduledFuture<?> result = this.executor.scheduleWithFixedDelay(this.runnable, 1, 2, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).scheduleWithFixedDelay(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS);

View File

@@ -33,8 +33,8 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -62,7 +62,7 @@ public class DelegatingSecurityContextCallableTests {
@SuppressWarnings("serial")
public void setUp() throws Exception {
this.originalSecurityContext = SecurityContextHolder.createEmptyContext();
when(this.delegate.call()).thenAnswer(new Returns(this.callableResult) {
given(this.delegate.call()).willAnswer(new Returns(this.callableResult) {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
assertThat(SecurityContextHolder.getContext())

View File

@@ -33,7 +33,7 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.verify;
/**
@@ -61,10 +61,10 @@ public class DelegatingSecurityContextRunnableTests {
@Before
public void setUp() {
this.originalSecurityContext = SecurityContextHolder.createEmptyContext();
doAnswer((Answer<Object>) invocation -> {
willAnswer((Answer<Object>) invocation -> {
assertThat(SecurityContextHolder.getContext()).isEqualTo(this.securityContext);
return null;
}).when(this.delegate).run();
}).given(this.delegate).run();
this.executor = Executors.newFixedThreadPool(1);
}

View File

@@ -25,9 +25,9 @@ import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DelegatingApplicationListenerTests {
@@ -56,8 +56,8 @@ public class DelegatingApplicationListenerTests {
@Test
public void processEventSuccess() {
when(this.delegate.supportsEventType(this.event.getClass())).thenReturn(true);
when(this.delegate.supportsSourceType(this.event.getSource().getClass())).thenReturn(true);
given(this.delegate.supportsEventType(this.event.getClass())).willReturn(true);
given(this.delegate.supportsSourceType(this.event.getSource().getClass())).willReturn(true);
this.listener.onApplicationEvent(this.event);
verify(this.delegate).onApplicationEvent(this.event);
@@ -72,7 +72,7 @@ public class DelegatingApplicationListenerTests {
@Test
public void processEventSourceTypeNotSupported() {
when(this.delegate.supportsEventType(this.event.getClass())).thenReturn(true);
given(this.delegate.supportsEventType(this.event.getClass())).willReturn(true);
this.listener.onApplicationEvent(this.event);
verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class));

View File

@@ -45,8 +45,8 @@ import org.springframework.security.core.userdetails.UserDetails;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for {@link JdbcUserDetailsManager}
@@ -225,7 +225,7 @@ public class JdbcUserDetailsManagerTests {
insertJoe();
Authentication currentAuth = authenticateJoe();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(currentAuth)).thenReturn(currentAuth);
given(am.authenticate(currentAuth)).willReturn(currentAuth);
this.manager.setAuthenticationManager(am);
this.manager.changePassword("password", "newPassword");
@@ -245,7 +245,7 @@ public class JdbcUserDetailsManagerTests {
insertJoe();
authenticateJoe();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
this.manager.setAuthenticationManager(am);