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

@@ -45,11 +45,11 @@ 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.doAnswer;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -73,13 +73,13 @@ public class FilterChainProxyTests {
public void setup() throws Exception {
this.matcher = mock(RequestMatcher.class);
this.filter = mock(Filter.class);
doAnswer((Answer<Object>) inv -> {
willAnswer((Answer<Object>) inv -> {
Object[] args = inv.getArguments();
FilterChain fc = (FilterChain) args[2];
HttpServletRequestWrapper extraWrapper = new HttpServletRequestWrapper((HttpServletRequest) args[0]);
fc.doFilter(extraWrapper, (HttpServletResponse) args[1]);
return null;
}).when(this.filter).doFilter(any(), any(), any());
}).given(this.filter).doFilter(any(), any(), any());
this.fcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, Arrays.asList(this.filter)));
this.fcp.setFilterChainValidator(mock(FilterChainProxy.FilterChainValidator.class));
this.request = new MockHttpServletRequest("GET", "");
@@ -101,7 +101,7 @@ public class FilterChainProxyTests {
@Test
public void securityFilterChainIsNotInvokedIfMatchFails() throws Exception {
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(false);
this.fcp.doFilter(this.request, this.response, this.chain);
assertThat(this.fcp.getFilterChains()).hasSize(1);
assertThat(this.fcp.getFilterChains().get(0).getFilters().get(0)).isSameAs(this.filter);
@@ -113,7 +113,7 @@ public class FilterChainProxyTests {
@Test
public void originalChainIsInvokedAfterSecurityChainIfMatchSucceeds() throws Exception {
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
@@ -126,7 +126,7 @@ public class FilterChainProxyTests {
List<Filter> noFilters = Collections.emptyList();
this.fcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, noFilters));
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(this.chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
@@ -134,7 +134,7 @@ public class FilterChainProxyTests {
@Test
public void requestIsWrappedForMatchingAndFilteringWhenMatchIsFound() throws Exception {
when(this.matcher.matches(any())).thenReturn(true);
given(this.matcher.matches(any())).willReturn(true);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(this.matcher).matches(any(FirewalledRequest.class));
verify(this.filter).doFilter(any(FirewalledRequest.class), any(HttpServletResponse.class),
@@ -144,7 +144,7 @@ public class FilterChainProxyTests {
@Test
public void requestIsWrappedForMatchingAndFilteringWhenMatchIsNotFound() throws Exception {
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(false);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(this.matcher).matches(any(FirewalledRequest.class));
verifyZeroInteractions(this.filter);
@@ -155,11 +155,11 @@ public class FilterChainProxyTests {
public void wrapperIsResetWhenNoMatchingFilters() throws Exception {
HttpFirewall fw = mock(HttpFirewall.class);
FirewalledRequest fwr = mock(FirewalledRequest.class);
when(fwr.getRequestURI()).thenReturn("/");
when(fwr.getContextPath()).thenReturn("");
given(fwr.getRequestURI()).willReturn("/");
given(fwr.getContextPath()).willReturn("");
this.fcp.setFirewall(fw);
when(fw.getFirewalledRequest(this.request)).thenReturn(fwr);
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
given(fw.getFirewalledRequest(this.request)).willReturn(fwr);
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(false);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(fwr).reset();
}
@@ -172,16 +172,16 @@ public class FilterChainProxyTests {
firstFcp.setFirewall(fw);
this.fcp.setFirewall(fw);
FirewalledRequest firstFwr = mock(FirewalledRequest.class, "firstFwr");
when(firstFwr.getRequestURI()).thenReturn("/");
when(firstFwr.getContextPath()).thenReturn("");
given(firstFwr.getRequestURI()).willReturn("/");
given(firstFwr.getContextPath()).willReturn("");
FirewalledRequest fwr = mock(FirewalledRequest.class, "fwr");
when(fwr.getRequestURI()).thenReturn("/");
when(fwr.getContextPath()).thenReturn("");
when(fw.getFirewalledRequest(this.request)).thenReturn(firstFwr);
when(fw.getFirewalledRequest(firstFwr)).thenReturn(fwr);
when(fwr.getRequest()).thenReturn(firstFwr);
when(firstFwr.getRequest()).thenReturn(this.request);
when(this.matcher.matches(any())).thenReturn(true);
given(fwr.getRequestURI()).willReturn("/");
given(fwr.getContextPath()).willReturn("");
given(fw.getFirewalledRequest(this.request)).willReturn(firstFwr);
given(fw.getFirewalledRequest(firstFwr)).willReturn(fwr);
given(fwr.getRequest()).willReturn(firstFwr);
given(firstFwr.getRequest()).willReturn(this.request);
given(this.matcher.matches(any())).willReturn(true);
firstFcp.doFilter(this.request, this.response, this.chain);
verify(firstFwr).reset();
verify(fwr).reset();
@@ -189,12 +189,12 @@ public class FilterChainProxyTests {
@Test
public void doFilterClearsSecurityContextHolder() throws Exception {
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer((Answer<Object>) inv -> {
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true);
willAnswer((Answer<Object>) inv -> {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("username", "password"));
return null;
}).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
this.fcp.doFilter(this.request, this.response, this.chain);
@@ -204,12 +204,12 @@ public class FilterChainProxyTests {
@Test
public void doFilterClearsSecurityContextHolderWithException() throws Exception {
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer((Answer<Object>) inv -> {
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true);
willAnswer((Answer<Object>) inv -> {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("username", "password"));
throw new ServletException("oops");
}).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
try {
@@ -226,20 +226,20 @@ public class FilterChainProxyTests {
@Test
public void doFilterClearsSecurityContextHolderOnceOnForwards() throws Exception {
final FilterChain innerChain = mock(FilterChain.class);
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer((Answer<Object>) inv -> {
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true);
willAnswer((Answer<Object>) inv -> {
TestingAuthenticationToken expected = new TestingAuthenticationToken("username", "password");
SecurityContextHolder.getContext().setAuthentication(expected);
doAnswer((Answer<Object>) inv1 -> {
willAnswer((Answer<Object>) inv1 -> {
innerChain.doFilter(this.request, this.response);
return null;
}).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
this.fcp.doFilter(this.request, this.response, innerChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expected);
return null;
}).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
this.fcp.doFilter(this.request, this.response, this.chain);
@@ -260,7 +260,7 @@ public class FilterChainProxyTests {
this.fcp.setFirewall(fw);
this.fcp.setRequestRejectedHandler(rjh);
RequestRejectedException requestRejectedException = new RequestRejectedException("Contains illegal chars");
when(fw.getFirewalledRequest(this.request)).thenThrow(requestRejectedException);
given(fw.getFirewalledRequest(this.request)).willThrow(requestRejectedException);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(rjh).handle(eq(this.request), eq(this.response), eq((requestRejectedException)));
}

View File

@@ -34,9 +34,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyObject;
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
@@ -71,14 +71,14 @@ public class DefaultWebInvocationPrivilegeEvaluatorTests {
@Test
public void permitsAccessIfNoMatchingAttributesAndPublicInvocationsAllowed() {
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor);
when(this.ods.getAttributes(anyObject())).thenReturn(null);
given(this.ods.getAttributes(anyObject())).willReturn(null);
assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class))).isTrue();
}
@Test
public void deniesAccessIfNoMatchingAttributesAndPublicInvocationsNotAllowed() {
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor);
when(this.ods.getAttributes(anyObject())).thenReturn(null);
given(this.ods.getAttributes(anyObject())).willReturn(null);
this.interceptor.setRejectPublicInvocations(true);
assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class))).isFalse();
}
@@ -102,7 +102,8 @@ public class DefaultWebInvocationPrivilegeEvaluatorTests {
Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX");
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor);
doThrow(new AccessDeniedException("")).when(this.adm).decide(any(Authentication.class), anyObject(), anyList());
willThrow(new AccessDeniedException("")).given(this.adm).decide(any(Authentication.class), anyObject(),
anyList());
assertThat(wipe.isAllowed("/foo/index.jsp", token)).isFalse();
}

View File

@@ -49,7 +49,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyZeroInteractions;
@@ -92,7 +92,7 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
doThrow(new AccessDeniedException("")).when(fc).doFilter(any(HttpServletRequest.class),
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is
@@ -124,7 +124,7 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
doThrow(new AccessDeniedException("")).when(fc).doFilter(any(HttpServletRequest.class),
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is remembered
@@ -149,7 +149,7 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
doThrow(new AccessDeniedException("")).when(fc).doFilter(any(HttpServletRequest.class),
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is
@@ -179,7 +179,7 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
doThrow(new AccessDeniedException("")).when(fc).doFilter(any(HttpServletRequest.class),
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is
@@ -213,7 +213,7 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an authentication failure exception
FilterChain fc = mock(FilterChain.class);
doThrow(new BadCredentialsException("")).when(fc).doFilter(any(HttpServletRequest.class),
willThrow(new BadCredentialsException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Test
@@ -239,7 +239,7 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an authentication failure exception
FilterChain fc = mock(FilterChain.class);
doThrow(new BadCredentialsException("")).when(fc).doFilter(any(HttpServletRequest.class),
willThrow(new BadCredentialsException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Test
@@ -286,7 +286,7 @@ public class ExceptionTranslationFilterTests {
for (Exception e : exceptions) {
FilterChain fc = mock(FilterChain.class);
doThrow(e).when(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
willThrow(e).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
try {
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc);
fail("Should have thrown Exception");

View File

@@ -26,10 +26,10 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Josh Cummings
@@ -55,7 +55,7 @@ public class RequestMatcherDelegatingAccessDeniedHandlerTests {
public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() throws Exception {
AccessDeniedHandler handler = mock(AccessDeniedHandler.class);
RequestMatcher matcher = mock(RequestMatcher.class);
when(matcher.matches(this.request)).thenReturn(false);
given(matcher.matches(this.request)).willReturn(false);
this.deniedHandlers.put(matcher, handler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
@@ -71,7 +71,7 @@ public class RequestMatcherDelegatingAccessDeniedHandlerTests {
RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
when(firstMatcher.matches(this.request)).thenReturn(true);
given(firstMatcher.matches(this.request)).willReturn(true);
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
@@ -90,8 +90,8 @@ public class RequestMatcherDelegatingAccessDeniedHandlerTests {
RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
when(firstMatcher.matches(this.request)).thenReturn(false);
when(secondMatcher.matches(this.request)).thenReturn(true);
given(firstMatcher.matches(this.request)).willReturn(false);
given(secondMatcher.matches(this.request)).willReturn(true);
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);

View File

@@ -36,9 +36,9 @@ import org.springframework.expression.TypeLocator;
import org.springframework.expression.TypedValue;
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.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -55,7 +55,7 @@ public class DelegatingEvaluationContextTests {
@Test
public void getRootObject() {
TypedValue expected = mock(TypedValue.class);
when(this.delegate.getRootObject()).thenReturn(expected);
given(this.delegate.getRootObject()).willReturn(expected);
assertThat(this.context.getRootObject()).isEqualTo(expected);
}
@@ -63,7 +63,7 @@ public class DelegatingEvaluationContextTests {
@Test
public void getConstructorResolvers() {
List<ConstructorResolver> expected = new ArrayList<>();
when(this.delegate.getConstructorResolvers()).thenReturn(expected);
given(this.delegate.getConstructorResolvers()).willReturn(expected);
assertThat(this.context.getConstructorResolvers()).isEqualTo(expected);
}
@@ -71,7 +71,7 @@ public class DelegatingEvaluationContextTests {
@Test
public void getMethodResolvers() {
List<MethodResolver> expected = new ArrayList<>();
when(this.delegate.getMethodResolvers()).thenReturn(expected);
given(this.delegate.getMethodResolvers()).willReturn(expected);
assertThat(this.context.getMethodResolvers()).isEqualTo(expected);
}
@@ -79,7 +79,7 @@ public class DelegatingEvaluationContextTests {
@Test
public void getPropertyAccessors() {
List<PropertyAccessor> expected = new ArrayList<>();
when(this.delegate.getPropertyAccessors()).thenReturn(expected);
given(this.delegate.getPropertyAccessors()).willReturn(expected);
assertThat(this.context.getPropertyAccessors()).isEqualTo(expected);
}
@@ -88,7 +88,7 @@ public class DelegatingEvaluationContextTests {
public void getTypeLocator() {
TypeLocator expected = mock(TypeLocator.class);
when(this.delegate.getTypeLocator()).thenReturn(expected);
given(this.delegate.getTypeLocator()).willReturn(expected);
assertThat(this.context.getTypeLocator()).isEqualTo(expected);
}
@@ -96,7 +96,7 @@ public class DelegatingEvaluationContextTests {
@Test
public void getTypeConverter() {
TypeConverter expected = mock(TypeConverter.class);
when(this.delegate.getTypeConverter()).thenReturn(expected);
given(this.delegate.getTypeConverter()).willReturn(expected);
assertThat(this.context.getTypeConverter()).isEqualTo(expected);
}
@@ -104,7 +104,7 @@ public class DelegatingEvaluationContextTests {
@Test
public void getTypeComparator() {
TypeComparator expected = mock(TypeComparator.class);
when(this.delegate.getTypeComparator()).thenReturn(expected);
given(this.delegate.getTypeComparator()).willReturn(expected);
assertThat(this.context.getTypeComparator()).isEqualTo(expected);
}
@@ -112,7 +112,7 @@ public class DelegatingEvaluationContextTests {
@Test
public void getOperatorOverloader() {
OperatorOverloader expected = mock(OperatorOverloader.class);
when(this.delegate.getOperatorOverloader()).thenReturn(expected);
given(this.delegate.getOperatorOverloader()).willReturn(expected);
assertThat(this.context.getOperatorOverloader()).isEqualTo(expected);
}
@@ -120,7 +120,7 @@ public class DelegatingEvaluationContextTests {
@Test
public void getBeanResolver() {
BeanResolver expected = mock(BeanResolver.class);
when(this.delegate.getBeanResolver()).thenReturn(expected);
given(this.delegate.getBeanResolver()).willReturn(expected);
assertThat(this.context.getBeanResolver()).isEqualTo(expected);
}
@@ -139,7 +139,7 @@ public class DelegatingEvaluationContextTests {
public void lookupVariable() {
String name = "name";
String expected = "expected";
when(this.delegate.lookupVariable(name)).thenReturn(expected);
given(this.delegate.lookupVariable(name)).willReturn(expected);
assertThat(this.context.lookupVariable(name)).isEqualTo(expected);
}

View File

@@ -35,8 +35,8 @@ import org.springframework.security.web.FilterInvocation;
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;
/**
* @author Luke Taylor
@@ -70,15 +70,15 @@ public class WebExpressionVoterTests {
WebExpressionVoter voter = new WebExpressionVoter();
Expression ex = mock(Expression.class);
EvaluationContextPostProcessor postProcessor = mock(EvaluationContextPostProcessor.class);
when(postProcessor.postProcess(any(EvaluationContext.class), any(FilterInvocation.class)))
.thenAnswer(invocation -> invocation.getArgument(0));
given(postProcessor.postProcess(any(EvaluationContext.class), any(FilterInvocation.class)))
.willAnswer(invocation -> invocation.getArgument(0));
WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex, postProcessor);
EvaluationContext ctx = mock(EvaluationContext.class);
SecurityExpressionHandler eh = mock(SecurityExpressionHandler.class);
FilterInvocation fi = new FilterInvocation("/path", "GET");
voter.setExpressionHandler(eh);
when(eh.createEvaluationContext(this.user, fi)).thenReturn(ctx);
when(ex.getValue(ctx, Boolean.class)).thenReturn(Boolean.TRUE).thenReturn(Boolean.FALSE);
given(eh.createEvaluationContext(this.user, fi)).willReturn(ctx);
given(ex.getValue(ctx, Boolean.class)).willReturn(Boolean.TRUE, Boolean.FALSE);
ArrayList attributes = new ArrayList();
attributes.addAll(SecurityConfig.createList("A", "B", "C"));
attributes.add(weca);

View File

@@ -46,12 +46,12 @@ import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
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 FilterSecurityInterceptor}.
@@ -97,13 +97,13 @@ public class FilterSecurityInterceptorTests {
@Test(expected = IllegalArgumentException.class)
public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass() throws Exception {
when(this.adm.supports(FilterInvocation.class)).thenReturn(true);
given(this.adm.supports(FilterInvocation.class)).willReturn(true);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testEnsuresRunAsManagerSupportsFilterInvocationClass() throws Exception {
when(this.adm.supports(FilterInvocation.class)).thenReturn(false);
given(this.adm.supports(FilterInvocation.class)).willReturn(false);
this.interceptor.afterPropertiesSet();
}
@@ -120,7 +120,7 @@ public class FilterSecurityInterceptorTests {
FilterInvocation fi = createinvocation();
when(this.ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
this.interceptor.invoke(fi);
@@ -136,9 +136,9 @@ public class FilterSecurityInterceptorTests {
FilterInvocation fi = createinvocation();
FilterChain chain = fi.getChain();
doThrow(new RuntimeException()).when(chain).doFilter(any(HttpServletRequest.class),
willThrow(new RuntimeException()).given(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
when(this.ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
@@ -163,16 +163,16 @@ public class FilterSecurityInterceptorTests {
ctx.setAuthentication(token);
RunAsManager runAsManager = mock(RunAsManager.class);
when(runAsManager.buildRunAs(eq(token), any(), anyCollection()))
.thenReturn(new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), token.getClass()));
given(runAsManager.buildRunAs(eq(token), any(), anyCollection()))
.willReturn(new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), token.getClass()));
this.interceptor.setRunAsManager(runAsManager);
FilterInvocation fi = createinvocation();
FilterChain chain = fi.getChain();
doThrow(new RuntimeException()).when(chain).doFilter(any(HttpServletRequest.class),
willThrow(new RuntimeException()).given(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
when(this.ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);

View File

@@ -44,10 +44,10 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
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.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Sergey Bespalov
@@ -76,7 +76,7 @@ public class AuthenticationFilterTests {
@Before
public void setup() {
when(this.authenticationManagerResolver.resolve(any())).thenReturn(this.authenticationManager);
given(this.authenticationManagerResolver.resolve(any())).willReturn(this.authenticationManager);
}
@After
@@ -117,8 +117,8 @@ public class AuthenticationFilterTests {
@Test
public void filterWhenDefaultsAndAuthenticationSuccessThenContinues() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(authentication);
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
@@ -136,8 +136,8 @@ public class AuthenticationFilterTests {
public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationSuccessThenContinues()
throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(authentication);
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
@@ -155,8 +155,8 @@ public class AuthenticationFilterTests {
@Test
public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenThrow(new BadCredentialsException("failed"));
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed"));
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
@@ -174,8 +174,8 @@ public class AuthenticationFilterTests {
public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized()
throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenThrow(new BadCredentialsException("failed"));
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed"));
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
@@ -191,7 +191,7 @@ public class AuthenticationFilterTests {
@Test
public void filterWhenConvertEmptyThenOk() throws Exception {
when(this.authenticationConverter.convert(any())).thenReturn(null);
given(this.authenticationConverter.convert(any())).willReturn(null);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
@@ -207,8 +207,8 @@ public class AuthenticationFilterTests {
@Test
public void filterWhenConvertAndAuthenticationSuccessThenSuccess() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(authentication);
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
@@ -227,8 +227,8 @@ public class AuthenticationFilterTests {
@Test(expected = ServletException.class)
public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(null);
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(null);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
@@ -250,7 +250,7 @@ public class AuthenticationFilterTests {
@Test
public void filterWhenNotMatchAndConvertAndAuthenticationSuccessThenContinues() throws Exception {
when(this.requestMatcher.matches(any())).thenReturn(false);
given(this.requestMatcher.matches(any())).willReturn(false);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
@@ -269,8 +269,8 @@ public class AuthenticationFilterTests {
@Test
public void filterWhenSuccessfulAuthenticationThenSessionIdChanges() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(authentication);
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
MockHttpSession session = new MockHttpSession();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");

View File

@@ -26,10 +26,10 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Test class for {@link DelegatingAuthenticationEntryPoint}
@@ -60,7 +60,7 @@ public class DelegatingAuthenticationEntryPointTests {
public void testDefaultEntryPoint() throws Exception {
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher firstRM = mock(RequestMatcher.class);
when(firstRM.matches(this.request)).thenReturn(false);
given(firstRM.matches(this.request)).willReturn(false);
this.entryPoints.put(firstRM, firstAEP);
this.daep.commence(this.request, null, null);
@@ -75,7 +75,7 @@ public class DelegatingAuthenticationEntryPointTests {
RequestMatcher firstRM = mock(RequestMatcher.class);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
when(firstRM.matches(this.request)).thenReturn(true);
given(firstRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
@@ -93,8 +93,8 @@ public class DelegatingAuthenticationEntryPointTests {
RequestMatcher firstRM = mock(RequestMatcher.class);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
when(firstRM.matches(this.request)).thenReturn(false);
when(secondRM.matches(this.request)).thenReturn(true);
given(firstRM.matches(this.request)).willReturn(false);
given(secondRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);

View File

@@ -25,9 +25,9 @@ import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class SavedRequestAwareAuthenticationSuccessHandlerTests {
@@ -55,8 +55,8 @@ public class SavedRequestAwareAuthenticationSuccessHandlerTests {
SavedRequest savedRequest = mock(SavedRequest.class);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
when(savedRequest.getRedirectUrl()).thenReturn(redirectUrl);
when(requestCache.getRequest(request, response)).thenReturn(savedRequest);
given(savedRequest.getRedirectUrl()).willReturn(redirectUrl);
given(requestCache.getRequest(request, response)).willReturn(savedRequest);
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
handler.setRequestCache(requestCache);

View File

@@ -29,8 +29,8 @@ import org.springframework.security.core.AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link UsernamePasswordAuthenticationFilter}.
@@ -122,7 +122,7 @@ public class UsernamePasswordAuthenticationFilterTests {
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod");
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
filter.setAuthenticationManager(am);
try {
@@ -152,8 +152,8 @@ public class UsernamePasswordAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class)))
.thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -31,7 +31,7 @@ import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -91,7 +91,7 @@ public class CompositeLogoutHandlerTests {
LogoutHandler firstLogoutHandler = mock(LogoutHandler.class);
LogoutHandler secondLogoutHandler = mock(LogoutHandler.class);
doThrow(new IllegalArgumentException()).when(firstLogoutHandler).logout(any(HttpServletRequest.class),
willThrow(new IllegalArgumentException()).given(firstLogoutHandler).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler);

View File

@@ -29,9 +29,9 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* DelegatingLogoutSuccessHandlerTests Tests
@@ -79,7 +79,7 @@ public class DelegatingLogoutSuccessHandlerTests {
@Test
public void onLogoutSuccessFirstMatches() throws Exception {
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
when(this.matcher.matches(this.request)).thenReturn(true);
given(this.matcher.matches(this.request)).willReturn(true);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
@@ -90,7 +90,7 @@ public class DelegatingLogoutSuccessHandlerTests {
@Test
public void onLogoutSuccessSecondMatches() throws Exception {
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
when(this.matcher2.matches(this.request)).thenReturn(true);
given(this.matcher2.matches(this.request)).willReturn(true);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);

View File

@@ -43,10 +43,10 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -81,7 +81,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void filterChainProceedsOnFailedAuthenticationByDefault() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
this.filter.setAuthenticationManager(am);
this.filter.afterPropertiesSet();
this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
@@ -93,7 +93,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse()
throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
this.filter.setContinueFilterChainOnUnsuccessfulAuthentication(false);
this.filter.setAuthenticationManager(am);
this.filter.afterPropertiesSet();
@@ -238,8 +238,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
filter.setAuthenticationFailureHandler(new ForwardAuthenticationFailureHandler("/forwardUrl"));
filter.setCheckForPrincipalChanges(true);
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(PreAuthenticatedAuthenticationToken.class)))
.thenThrow(new PreAuthenticatedCredentialsNotFoundException("invalid"));
given(am.authenticate(any(PreAuthenticatedAuthenticationToken.class)))
.willThrow(new PreAuthenticatedCredentialsNotFoundException("invalid"));
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
@@ -418,11 +418,11 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
if (!grantAccess) {
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
}
else {
when(am.authenticate(any(Authentication.class)))
.thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
}
filter.setAuthenticationManager(am);

View File

@@ -29,8 +29,8 @@ 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.mock;
import static org.mockito.Mockito.when;
/**
* @author Milan Sevcik
@@ -149,8 +149,8 @@ public class RequestAttributeAuthenticationFilterTests {
*/
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class)))
.thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -31,8 +31,8 @@ import org.springframework.security.web.authentication.preauth.RequestHeaderAuth
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;
/**
* @author Luke Taylor
@@ -150,8 +150,8 @@ public class RequestHeaderAuthenticationFilterTests {
*/
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class)))
.thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -30,8 +30,8 @@ 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.mock;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -47,14 +47,14 @@ public class WebSpherePreAuthenticatedProcessingFilterTests {
public void principalsAndCredentialsAreExtractedCorrectly() throws Exception {
new WebSpherePreAuthenticatedProcessingFilter();
WASUsernameAndGroupsExtractor helper = mock(WASUsernameAndGroupsExtractor.class);
when(helper.getCurrentUserName()).thenReturn("jerry");
given(helper.getCurrentUserName()).willReturn("jerry");
WebSpherePreAuthenticatedProcessingFilter filter = new WebSpherePreAuthenticatedProcessingFilter(helper);
assertThat(filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest())).isEqualTo("jerry");
assertThat(filter.getPreAuthenticatedCredentials(new MockHttpServletRequest())).isEqualTo("N/A");
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class)))
.thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
filter.setAuthenticationManager(am);
WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource(

View File

@@ -41,10 +41,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
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.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -133,7 +133,7 @@ public class JdbcTokenRepositoryImplTests {
// SEC-1964
@Test
public void retrievingTokenWithNoSeriesReturnsNull() {
when(this.logger.isDebugEnabled()).thenReturn(true);
given(this.logger.isDebugEnabled()).willReturn(true);
assertThat(this.repo.getTokenForSeries("missingSeries")).isNull();

View File

@@ -39,10 +39,10 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationSu
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.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link RememberMeAuthenticationFilter}.
@@ -98,7 +98,7 @@ public class RememberMeAuthenticationFilterTests {
@Test
public void testOperationWhenNoAuthenticationInContextHolder() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(this.remembered)).thenReturn(this.remembered);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
new MockRememberMeServices(this.remembered));
@@ -118,7 +118,7 @@ public class RememberMeAuthenticationFilterTests {
public void onUnsuccessfulLoginIsCalledWhenProviderRejectsAuth() throws Exception {
final Authentication failedAuth = new TestingAuthenticationToken("failed", "");
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
new MockRememberMeServices(this.remembered)) {
@@ -144,7 +144,7 @@ public class RememberMeAuthenticationFilterTests {
@Test
public void authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(this.remembered)).thenReturn(this.remembered);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));

View File

@@ -38,8 +38,8 @@ import org.springframework.util.StringUtils;
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;
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.DEFAULT_PARAMETER;
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY;
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.TWO_WEEKS_S;
@@ -67,15 +67,15 @@ public class TokenBasedRememberMeServicesTests {
}
void udsWillReturnUser() {
when(this.uds.loadUserByUsername(any(String.class))).thenReturn(this.user);
given(this.uds.loadUserByUsername(any(String.class))).willReturn(this.user);
}
void udsWillThrowNotFound() {
when(this.uds.loadUserByUsername(any(String.class))).thenThrow(new UsernameNotFoundException(""));
given(this.uds.loadUserByUsername(any(String.class))).willThrow(new UsernameNotFoundException(""));
}
void udsWillReturnNull() {
when(this.uds.loadUserByUsername(any(String.class))).thenReturn(null);
given(this.uds.loadUserByUsername(any(String.class))).willReturn(null);
}
private long determineExpiryTimeFromBased64EncodedToken(String validToken) {

View File

@@ -30,7 +30,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.doThrow;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -83,8 +83,8 @@ public class CompositeSessionAuthenticationStrategyTests {
@Test
public void delegateShortCircuits() {
doThrow(new SessionAuthenticationException("oops")).when(this.strategy1).onAuthentication(this.authentication,
this.request, this.response);
willThrow(new SessionAuthenticationException("oops")).given(this.strategy1)
.onAuthentication(this.authentication, this.request, this.response);
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
Arrays.asList(this.strategy1, this.strategy2));

View File

@@ -38,7 +38,7 @@ import org.springframework.security.core.session.SessionRegistry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -78,8 +78,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test
public void noRegisteredSession() {
when(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>emptyList());
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Collections.<SessionInformation>emptyList());
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
@@ -92,8 +92,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
public void maxSessionsSameSessionId() {
MockHttpSession session = new MockHttpSession(new MockServletContext(), this.sessionInformation.getSessionId());
this.request.setSession(session);
when(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
@@ -104,8 +104,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test(expected = SessionAuthenticationException.class)
public void maxSessionsWithException() {
when(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
@@ -114,8 +114,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test
public void maxSessionsExpireExistingUser() {
when(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
@@ -127,8 +127,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
public void maxSessionsExpireLeastRecentExistingUser() {
SessionInformation moreRecentSessionInfo = new SessionInformation(this.authentication.getPrincipal(), "unique",
new Date(1374766999999L));
when(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Arrays.<SessionInformation>asList(moreRecentSessionInfo, this.sessionInformation));
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Arrays.<SessionInformation>asList(moreRecentSessionInfo, this.sessionInformation));
this.strategy.setMaximumSessions(2);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
@@ -142,7 +142,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
new Date(1374766134214L));
SessionInformation secondOldestSessionInfo = new SessionInformation(this.authentication.getPrincipal(),
"unique2", new Date(1374766134215L));
when(this.sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
given(this.sessionRegistry.getAllSessions(any(), anyBoolean())).willReturn(
Arrays.<SessionInformation>asList(oldestSessionInfo, secondOldestSessionInfo, this.sessionInformation));
this.strategy.setMaximumSessions(2);

View File

@@ -44,10 +44,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.AdditionalMatchers.not;
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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests {@link BasicAuthenticationFilter}.
@@ -69,8 +69,8 @@ public class BasicAuthenticationFilterTests {
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
when(this.manager.authenticate(rodRequest)).thenReturn(rod);
when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
}
@@ -312,8 +312,8 @@ public class BasicAuthenticationFilterTests {
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
when(this.manager.authenticate(rodRequest)).thenReturn(rod);
when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
@@ -347,8 +347,8 @@ public class BasicAuthenticationFilterTests {
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
when(this.manager.authenticate(rodRequest)).thenReturn(rod);
when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
this.filter.setCredentialsCharset("ISO-8859-1");
@@ -383,8 +383,8 @@ public class BasicAuthenticationFilterTests {
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
when(this.manager.authenticate(rodRequest)).thenReturn(rod);
when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
this.filter.setCredentialsCharset("ISO-8859-1");

View File

@@ -44,10 +44,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
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.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Tests {@link ConcurrentSessionFilter}.
@@ -179,7 +179,7 @@ public class ConcurrentSessionFilterTests {
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
when(registry.getSessionInformation(anyString())).thenReturn(information);
given(registry.getSessionInformation(anyString())).willReturn(information);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl);
@@ -224,7 +224,7 @@ public class ConcurrentSessionFilterTests {
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
when(registry.getSessionInformation(anyString())).thenReturn(information);
given(registry.getSessionInformation(anyString())).willReturn(information);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl);
@@ -247,7 +247,7 @@ public class ConcurrentSessionFilterTests {
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
when(registry.getSessionInformation(anyString())).thenReturn(information);
given(registry.getSessionInformation(anyString())).willReturn(information);
final String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl + "will-be-overrridden") {
@@ -276,7 +276,7 @@ public class ConcurrentSessionFilterTests {
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
when(registry.getSessionInformation(anyString())).thenReturn(information);
given(registry.getSessionInformation(anyString())).willReturn(information);
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
@@ -298,7 +298,7 @@ public class ConcurrentSessionFilterTests {
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
when(registry.getSessionInformation(anyString())).thenReturn(information);
given(registry.getSessionInformation(anyString())).willReturn(information);
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
filter.setLogoutHandlers(new LogoutHandler[] { handler });

View File

@@ -34,10 +34,10 @@ import org.springframework.security.core.context.SecurityContextImpl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.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.verify;
import static org.mockito.Mockito.when;
public class SecurityContextPersistenceFilterTests {
@@ -68,7 +68,7 @@ public class SecurityContextPersistenceFilterTests {
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
SecurityContextHolder.getContext().setAuthentication(this.testToken);
doThrow(new IOException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
willThrow(new IOException()).given(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
try {
filter.doFilter(request, response, chain);
fail("IOException should have been thrown");
@@ -91,7 +91,7 @@ public class SecurityContextPersistenceFilterTests {
final SecurityContextRepository repo = mock(SecurityContextRepository.class);
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo);
when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore);
given(repo.loadContext(any(HttpRequestResponseHolder.class))).willReturn(scBefore);
final FilterChain chain = (request1, response1) -> {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth);

View File

@@ -39,7 +39,7 @@ import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -79,7 +79,7 @@ public class WebAsyncManagerIntegrationFilterTests {
this.asyncManager = WebAsyncUtils.getAsyncManager(this.request);
this.asyncManager.setAsyncWebRequest(this.asyncWebRequest);
this.asyncManager.setTaskExecutor(executor);
when(this.request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).thenReturn(this.asyncManager);
given(this.request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).willReturn(this.asyncManager);
this.filter = new WebAsyncManagerIntegrationFilter();
}

View File

@@ -31,9 +31,9 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -72,8 +72,8 @@ public class CsrfAuthenticationStrategyTests {
@Test
public void logoutRemovesCsrfTokenAndSavesNew() {
when(this.csrfTokenRepository.loadToken(this.request)).thenReturn(this.existingToken);
when(this.csrfTokenRepository.generateToken(this.request)).thenReturn(this.generatedToken);
given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken);
given(this.csrfTokenRepository.generateToken(this.request)).willReturn(this.generatedToken);
this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request,
this.response);
@@ -93,8 +93,8 @@ public class CsrfAuthenticationStrategyTests {
public void delaySavingCsrf() {
this.strategy = new CsrfAuthenticationStrategy(new LazyCsrfTokenRepository(this.csrfTokenRepository));
when(this.csrfTokenRepository.loadToken(this.request)).thenReturn(this.existingToken);
when(this.csrfTokenRepository.generateToken(this.request)).thenReturn(this.generatedToken);
given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken);
given(this.csrfTokenRepository.generateToken(this.request)).willReturn(this.generatedToken);
this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request,
this.response);

View File

@@ -40,13 +40,13 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
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.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -103,8 +103,8 @@ public class CsrfFilterTests {
@Test
public void doFilterDoesNotSaveCsrfTokenUntilAccessed() throws ServletException, IOException {
this.filter = createCsrfFilter(new LazyCsrfTokenRepository(this.tokenRepository));
when(this.requestMatcher.matches(this.request)).thenReturn(false);
when(this.tokenRepository.generateToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(false);
given(this.tokenRepository.generateToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
CsrfToken attrToken = (CsrfToken) this.request.getAttribute(this.token.getParameterName());
@@ -124,8 +124,8 @@ public class CsrfFilterTests {
@Test
public void doFilterAccessDeniedNoTokenPresent() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -138,8 +138,8 @@ public class CsrfFilterTests {
@Test
public void doFilterAccessDeniedIncorrectTokenPresent() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken() + " INVALID");
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -153,8 +153,8 @@ public class CsrfFilterTests {
@Test
public void doFilterAccessDeniedIncorrectTokenPresentHeader() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.addHeader(this.token.getHeaderName(), this.token.getToken() + " INVALID");
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -169,8 +169,8 @@ public class CsrfFilterTests {
@Test
public void doFilterAccessDeniedIncorrectTokenPresentHeaderPreferredOverParameter()
throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken());
this.request.addHeader(this.token.getHeaderName(), this.token.getToken() + " INVALID");
@@ -185,8 +185,8 @@ public class CsrfFilterTests {
@Test
public void doFilterNotCsrfRequestExistingToken() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(false);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(false);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -199,8 +199,8 @@ public class CsrfFilterTests {
@Test
public void doFilterNotCsrfRequestGenerateToken() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(false);
when(this.tokenRepository.generateToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(false);
given(this.tokenRepository.generateToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -213,8 +213,8 @@ public class CsrfFilterTests {
@Test
public void doFilterIsCsrfRequestExistingTokenHeader() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.addHeader(this.token.getHeaderName(), this.token.getToken());
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -229,8 +229,8 @@ public class CsrfFilterTests {
@Test
public void doFilterIsCsrfRequestExistingTokenHeaderPreferredOverInvalidParam()
throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken() + " INVALID");
this.request.addHeader(this.token.getHeaderName(), this.token.getToken());
@@ -245,8 +245,8 @@ public class CsrfFilterTests {
@Test
public void doFilterIsCsrfRequestExistingToken() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken());
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -262,8 +262,8 @@ public class CsrfFilterTests {
@Test
public void doFilterIsCsrfRequestGenerateToken() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.generateToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.generateToken(this.request)).willReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken());
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -286,7 +286,7 @@ public class CsrfFilterTests {
for (String method : Arrays.asList("GET", "TRACE", "OPTIONS", "HEAD")) {
resetRequestResponse();
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setMethod(method);
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -309,7 +309,7 @@ public class CsrfFilterTests {
for (String method : Arrays.asList("get", "TrAcE", "oPTIOnS", "hEaD")) {
resetRequestResponse();
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setMethod(method);
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -327,7 +327,7 @@ public class CsrfFilterTests {
for (String method : Arrays.asList("POST", "PUT", "PATCH", "DELETE", "INVALID")) {
resetRequestResponse();
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setMethod(method);
this.filter.doFilter(this.request, this.response, this.filterChain);
@@ -342,8 +342,8 @@ public class CsrfFilterTests {
public void doFilterDefaultAccessDenied() throws ServletException, IOException {
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setRequireCsrfProtectionMatcher(this.requestMatcher);
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);

View File

@@ -27,10 +27,10 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
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.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -55,8 +55,8 @@ public class LazyCsrfTokenRepositoryTests {
@Before
public void setup() {
this.token = new DefaultCsrfToken("header", "param", "token");
when(this.delegate.generateToken(this.request)).thenReturn(this.token);
when(this.request.getAttribute(HttpServletResponse.class.getName())).thenReturn(this.response);
given(this.delegate.generateToken(this.request)).willReturn(this.token);
given(this.request.getAttribute(HttpServletResponse.class.getName())).willReturn(this.response);
}
@Test(expected = IllegalArgumentException.class)
@@ -94,7 +94,7 @@ public class LazyCsrfTokenRepositoryTests {
@Test
public void loadTokenDelegates() {
when(this.delegate.loadToken(this.request)).thenReturn(this.token);
given(this.delegate.loadToken(this.request)).willReturn(this.token);
CsrfToken loadToken = this.repository.loadToken(this.request);
assertThat(loadToken).isSameAs(this.token);

View File

@@ -39,9 +39,9 @@ import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -78,8 +78,8 @@ public class DebugFilterTests {
@Before
public void setUp() {
when(this.request.getHeaderNames()).thenReturn(Collections.enumeration(Collections.<String>emptyList()));
when(this.request.getServletPath()).thenReturn("/login");
given(this.request.getHeaderNames()).willReturn(Collections.enumeration(Collections.<String>emptyList()));
given(this.request.getServletPath()).willReturn("/login");
this.filter = new DebugFilter(this.fcp);
ReflectionTestUtils.setField(this.filter, "logger", this.logger);
this.requestAttr = DebugFilter.ALREADY_FILTERED_ATTR_NAME;
@@ -99,7 +99,7 @@ public class DebugFilterTests {
// SEC-1901
@Test
public void doFilterProcessesForwardedRequests() throws Exception {
when(this.request.getAttribute(this.requestAttr)).thenReturn(Boolean.TRUE);
given(this.request.getAttribute(this.requestAttr)).willReturn(Boolean.TRUE);
HttpServletRequest request = new DebugRequestWrapper(this.request);
this.filter.doFilter(request, this.response, this.filterChain);
@@ -111,7 +111,7 @@ public class DebugFilterTests {
@Test
public void doFilterDoesNotWrapWithDebugRequestWrapperAgain() throws Exception {
when(this.request.getAttribute(this.requestAttr)).thenReturn(Boolean.TRUE);
given(this.request.getAttribute(this.requestAttr)).willReturn(Boolean.TRUE);
HttpServletRequest fireWalledRequest = new HttpServletRequestWrapper(new DebugRequestWrapper(this.request));
this.filter.doFilter(fireWalledRequest, this.response, this.filterChain);

View File

@@ -28,11 +28,11 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
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.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -93,9 +93,9 @@ public class RequestWrapperTests {
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
RequestDispatcher mockDispatcher = mock(RequestDispatcher.class);
when(mockRequest.getServletPath()).thenReturn("");
when(mockRequest.getPathInfo()).thenReturn(denormalizedPath);
when(mockRequest.getRequestDispatcher(forwardPath)).thenReturn(mockDispatcher);
given(mockRequest.getServletPath()).willReturn("");
given(mockRequest.getPathInfo()).willReturn(denormalizedPath);
given(mockRequest.getRequestDispatcher(forwardPath)).willReturn(mockDispatcher);
RequestWrapper wrapper = new RequestWrapper(mockRequest);
RequestDispatcher dispatcher = wrapper.getRequestDispatcher(forwardPath);
@@ -116,7 +116,7 @@ public class RequestWrapperTests {
String path = "/forward/path";
HttpServletRequest request = mock(HttpServletRequest.class);
RequestDispatcher dispatcher = mock(RequestDispatcher.class);
when(request.getRequestDispatcher(path)).thenReturn(dispatcher);
given(request.getRequestDispatcher(path)).willReturn(dispatcher);
RequestWrapper wrapper = new RequestWrapper(request);
wrapper.reset();
assertThat(wrapper.getRequestDispatcher(path)).isSameAs(dispatcher);

View File

@@ -26,9 +26,9 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.web.header.HeaderWriter;
import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -68,7 +68,7 @@ public class DelegatingRequestMatcherHeaderWriterTests {
@Test
public void writeHeadersOnMatch() {
when(this.matcher.matches(this.request)).thenReturn(true);
given(this.matcher.matches(this.request)).willReturn(true);
this.headerWriter.writeHeaders(this.request, this.response);
@@ -77,7 +77,7 @@ public class DelegatingRequestMatcherHeaderWriterTests {
@Test
public void writeHeadersOnNoMatch() {
when(this.matcher.matches(this.request)).thenReturn(false);
given(this.matcher.matches(this.request)).willReturn(false);
this.headerWriter.writeHeaders(this.request, this.response);

View File

@@ -26,7 +26,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter.XFrameOptionsMode;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -77,7 +77,7 @@ public class FrameOptionsHeaderWriterTests {
@Test
public void writeHeadersAllowFrom() {
String allowFromValue = "https://example.com/";
when(this.strategy.getAllowFromValue(this.request)).thenReturn(allowFromValue);
given(this.strategy.getAllowFromValue(this.request)).willReturn(allowFromValue);
this.writer = new XFrameOptionsHeaderWriter(this.strategy);
this.writer.writeHeaders(this.request, this.response);

View File

@@ -43,7 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat;
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.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -93,7 +93,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void resolveArgumentWhenIsAuthenticationThenObtainsPrincipal() {
MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
when(this.authentication.getPrincipal()).thenReturn("user");
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
@@ -114,7 +114,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void resolveArgumentWhenMonoIsAuthenticationThenObtainsPrincipal() {
MethodParameter parameter = this.authenticationPrincipal.arg(Mono.class, String.class);
when(this.authentication.getPrincipal()).thenReturn("user");
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
@@ -126,7 +126,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentWhenMonoIsAuthenticationAndNoGenericThenObtainsPrincipal() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("authenticationPrincipalNoGeneric").build()
.arg(Mono.class);
when(this.authentication.getPrincipal()).thenReturn("user");
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
@@ -138,7 +138,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentWhenSpelThenObtainsPrincipal() {
MyUser user = new MyUser(3L);
MethodParameter parameter = this.spel.arg(Long.class);
when(this.authentication.getPrincipal()).thenReturn(user);
given(this.authentication.getPrincipal()).willReturn(user);
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
@@ -150,8 +150,8 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentWhenBeanThenObtainsPrincipal() throws Exception {
MyUser user = new MyUser(3L);
MethodParameter parameter = this.bean.arg(Long.class);
when(this.authentication.getPrincipal()).thenReturn(user);
when(this.beanResolver.resolve(any(), eq("beanName"))).thenReturn(new Bean());
given(this.authentication.getPrincipal()).willReturn(user);
given(this.beanResolver.resolve(any(), eq("beanName"))).willReturn(new Bean());
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
@@ -162,7 +162,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void resolveArgumentWhenMetaThenObtainsPrincipal() {
MethodParameter parameter = this.meta.arg(String.class);
when(this.authentication.getPrincipal()).thenReturn("user");
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
@@ -174,7 +174,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentWhenErrorOnInvalidTypeImplicit() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenImplicit").build()
.arg(Integer.class);
when(this.authentication.getPrincipal()).thenReturn("user");
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
@@ -186,7 +186,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentWhenErrorOnInvalidTypeExplicitFalse() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitFalse").build()
.arg(Integer.class);
when(this.authentication.getPrincipal()).thenReturn("user");
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
@@ -198,7 +198,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentWhenErrorOnInvalidTypeExplicitTrue() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitTrue").build()
.arg(Integer.class);
when(this.authentication.getPrincipal()).thenReturn("user");
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));

View File

@@ -32,9 +32,9 @@ import org.springframework.security.web.server.util.matcher.ServerWebExchangeMat
import org.springframework.web.server.ServerWebExchange;
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.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -64,9 +64,9 @@ public class DelegatingServerAuthenticationEntryPointTests {
@Test
public void commenceWhenNotMatchThenMatchThenOnlySecondDelegateInvoked() {
Mono<Void> expectedResult = Mono.empty();
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(this.delegate2.commence(this.exchange, this.e)).thenReturn(expectedResult);
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.commence(this.exchange, this.e)).willReturn(expectedResult);
this.entryPoint = new DelegatingServerAuthenticationEntryPoint(new DelegateEntry(this.matcher1, this.delegate1),
new DelegateEntry(this.matcher2, this.delegate2));
@@ -79,7 +79,7 @@ public class DelegatingServerAuthenticationEntryPointTests {
@Test
public void commenceWhenNotMatchThenDefault() {
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
this.entryPoint = new DelegatingServerAuthenticationEntryPoint(
new DelegateEntry(this.matcher1, this.delegate1));

View File

@@ -31,7 +31,7 @@ import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author David Kovac
@@ -63,35 +63,35 @@ public class AuthenticationConverterServerWebExchangeMatcherTests {
@Test
public void matchesWhenNotEmptyThenReturnTrue() {
when(this.converter.convert(any())).thenReturn(Mono.just(this.authentication));
given(this.converter.convert(any())).willReturn(Mono.just(this.authentication));
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue();
}
@Test
public void matchesWhenEmptyThenReturnFalse() {
when(this.converter.convert(any())).thenReturn(Mono.empty());
given(this.converter.convert(any())).willReturn(Mono.empty());
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse();
}
@Test
public void matchesWhenErrorThenReturnFalse() {
when(this.converter.convert(any())).thenReturn(Mono.error(new RuntimeException()));
given(this.converter.convert(any())).willReturn(Mono.error(new RuntimeException()));
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse();
}
@Test
public void matchesWhenNullThenThrowsException() {
when(this.converter.convert(any())).thenReturn(null);
given(this.converter.convert(any())).willReturn(null);
assertThatCode(() -> this.matcher.matches(this.exchange).block()).isInstanceOf(NullPointerException.class);
}
@Test
public void matchesWhenExceptionThenPropagates() {
when(this.converter.convert(any())).thenThrow(RuntimeException.class);
given(this.converter.convert(any())).willThrow(RuntimeException.class);
assertThatCode(() -> this.matcher.matches(this.exchange).block()).isInstanceOf(RuntimeException.class);
}

View File

@@ -38,10 +38,10 @@ import org.springframework.web.server.ServerWebExchange;
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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -110,8 +110,8 @@ public class AuthenticationWebFilterTests {
@Test
public void filterWhenDefaultsAndAuthenticationSuccessThenContinues() {
when(this.authenticationManager.authenticate(any()))
.thenReturn(Mono.just(new TestingAuthenticationToken("test", "this", "ROLE")));
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken("test", "this", "ROLE")));
this.filter = new AuthenticationWebFilter(this.authenticationManager);
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
@@ -126,9 +126,9 @@ public class AuthenticationWebFilterTests {
@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationSuccessThenContinues() {
when(this.authenticationManager.authenticate(any()))
.thenReturn(Mono.just(new TestingAuthenticationToken("test", "this", "ROLE")));
when(this.authenticationManagerResolver.resolve(any())).thenReturn(Mono.just(this.authenticationManager));
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken("test", "this", "ROLE")));
given(this.authenticationManagerResolver.resolve(any())).willReturn(Mono.just(this.authenticationManager));
this.filter = new AuthenticationWebFilter(this.authenticationManagerResolver);
@@ -144,8 +144,8 @@ public class AuthenticationWebFilterTests {
@Test
public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() {
when(this.authenticationManager.authenticate(any()))
.thenReturn(Mono.error(new BadCredentialsException("failed")));
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.error(new BadCredentialsException("failed")));
this.filter = new AuthenticationWebFilter(this.authenticationManager);
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
@@ -159,9 +159,9 @@ public class AuthenticationWebFilterTests {
@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized() {
when(this.authenticationManager.authenticate(any()))
.thenReturn(Mono.error(new BadCredentialsException("failed")));
when(this.authenticationManagerResolver.resolve(any())).thenReturn(Mono.just(this.authenticationManager));
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.error(new BadCredentialsException("failed")));
given(this.authenticationManagerResolver.resolve(any())).willReturn(Mono.just(this.authenticationManager));
this.filter = new AuthenticationWebFilter(this.authenticationManagerResolver);
@@ -176,7 +176,7 @@ public class AuthenticationWebFilterTests {
@Test
public void filterWhenConvertEmptyThenOk() {
when(this.authenticationConverter.convert(any())).thenReturn(Mono.empty());
given(this.authenticationConverter.convert(any())).willReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
@@ -189,7 +189,7 @@ public class AuthenticationWebFilterTests {
@Test
public void filterWhenConvertErrorThenServerError() {
when(this.authenticationConverter.convert(any())).thenReturn(Mono.error(new RuntimeException("Unexpected")));
given(this.authenticationConverter.convert(any())).willReturn(Mono.error(new RuntimeException("Unexpected")));
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
@@ -202,10 +202,10 @@ public class AuthenticationWebFilterTests {
@Test
public void filterWhenConvertAndAuthenticationSuccessThenSuccess() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(authentication);
when(this.successHandler.onAuthenticationSuccess(any(), any())).thenReturn(Mono.empty());
when(this.securityContextRepository.save(any(), any())).thenAnswer(a -> Mono.just(a.getArguments()[0]));
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
given(this.successHandler.onAuthenticationSuccess(any(), any())).willReturn(Mono.empty());
given(this.securityContextRepository.save(any(), any())).willAnswer(a -> Mono.just(a.getArguments()[0]));
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
@@ -219,8 +219,8 @@ public class AuthenticationWebFilterTests {
@Test
public void filterWhenConvertAndAuthenticationEmptyThenServerError() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(Mono.empty());
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
@@ -248,10 +248,10 @@ public class AuthenticationWebFilterTests {
@Test
public void filterWhenConvertAndAuthenticationFailThenEntryPoint() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any()))
.thenReturn(Mono.error(new BadCredentialsException("Failed")));
when(this.failureHandler.onAuthenticationFailure(any(), any())).thenReturn(Mono.empty());
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.error(new BadCredentialsException("Failed")));
given(this.failureHandler.onAuthenticationFailure(any(), any())).willReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
@@ -265,8 +265,8 @@ public class AuthenticationWebFilterTests {
@Test
public void filterWhenConvertAndAuthenticationExceptionThenServerError() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(Mono.error(new RuntimeException("Failed")));
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new RuntimeException("Failed")));
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();

View File

@@ -35,7 +35,7 @@ import org.springframework.security.web.server.WebFilterExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
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 DelegatingServerAuthenticationSuccessHandlerTests {
@Before
public void setup() {
when(this.delegate1.onAuthenticationSuccess(any(), any())).thenReturn(this.delegate1Result.mono());
when(this.delegate2.onAuthenticationSuccess(any(), any())).thenReturn(this.delegate2Result.mono());
given(this.delegate1.onAuthenticationSuccess(any(), any())).willReturn(this.delegate1Result.mono());
given(this.delegate2.onAuthenticationSuccess(any(), any())).willReturn(this.delegate2Result.mono());
}
@Test

View File

@@ -33,8 +33,8 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedA
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Alexey Nesterov
@@ -62,7 +62,7 @@ public class ReactivePreAuthenticatedAuthenticationManagerTests {
@Test
public void returnsAuthenticatedTokenForValidAccount() {
when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.validAccount));
given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.validAccount));
Authentication authentication = this.manager.authenticate(tokenForUser(this.validAccount.getUsername()))
.block();
@@ -71,36 +71,36 @@ public class ReactivePreAuthenticatedAuthenticationManagerTests {
@Test(expected = UsernameNotFoundException.class)
public void returnsNullForNonExistingAccount() {
when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.empty());
given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.empty());
this.manager.authenticate(tokenForUser(this.nonExistingAccount.getUsername())).block();
}
@Test(expected = LockedException.class)
public void throwsExceptionForLockedAccount() {
when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.lockedAccount));
given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.lockedAccount));
this.manager.authenticate(tokenForUser(this.lockedAccount.getUsername())).block();
}
@Test(expected = DisabledException.class)
public void throwsExceptionForDisabledAccount() {
when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.disabledAccount));
given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.disabledAccount));
this.manager.authenticate(tokenForUser(this.disabledAccount.getUsername())).block();
}
@Test(expected = AccountExpiredException.class)
public void throwsExceptionForExpiredAccount() {
when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.expiredAccount));
given(this.mockUserDetailsService.findByUsername(anyString())).willReturn(Mono.just(this.expiredAccount));
this.manager.authenticate(tokenForUser(this.expiredAccount.getUsername())).block();
}
@Test(expected = CredentialsExpiredException.class)
public void throwsExceptionForAccountWithExpiredCredentials() {
when(this.mockUserDetailsService.findByUsername(anyString()))
.thenReturn(Mono.just(this.accountWithExpiredCredentials));
given(this.mockUserDetailsService.findByUsername(anyString()))
.willReturn(Mono.just(this.accountWithExpiredCredentials));
this.manager.authenticate(tokenForUser(this.accountWithExpiredCredentials.getUsername())).block();
}

View File

@@ -32,7 +32,7 @@ import org.springframework.web.server.ServerWebExchange;
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
@@ -82,7 +82,7 @@ public class RedirectServerAuthenticationEntryPointTests {
@Test
public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() {
PublisherProbe<Void> redirectResult = PublisherProbe.empty();
when(this.redirectStrategy.sendRedirect(any(), any())).thenReturn(redirectResult.mono());
given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono());
this.entryPoint.setRedirectStrategy(this.redirectStrategy);
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());

View File

@@ -34,7 +34,7 @@ import org.springframework.web.server.handler.DefaultWebFilterChain;
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
@@ -83,7 +83,7 @@ public class RedirectServerAuthenticationFailureHandlerTests {
@Test
public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() {
PublisherProbe<Void> redirectResult = PublisherProbe.empty();
when(this.redirectStrategy.sendRedirect(any(), any())).thenReturn(redirectResult.mono());
given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono());
this.handler.setRedirectStrategy(this.redirectStrategy);
this.exchange = createExchange();

View File

@@ -36,8 +36,8 @@ import org.springframework.web.server.WebFilterChain;
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.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -91,7 +91,7 @@ public class RedirectServerAuthenticationSuccessHandlerTests {
@Test
public void successWhenCustomLocationThenCustomLocationUsed() {
PublisherProbe<Void> redirectResult = PublisherProbe.empty();
when(this.redirectStrategy.sendRedirect(any(), any())).thenReturn(redirectResult.mono());
given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono());
this.handler.setRedirectStrategy(this.redirectStrategy);
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());

View File

@@ -30,7 +30,7 @@ import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -64,7 +64,7 @@ public class ServerAuthenticationEntryPointFailureHandlerTests {
public void onAuthenticationFailureWhenInvokedThenDelegatesToEntryPoint() {
Mono<Void> result = Mono.empty();
BadCredentialsException e = new BadCredentialsException("Failed");
when(this.authenticationEntryPoint.commence(this.exchange, e)).thenReturn(result);
given(this.authenticationEntryPoint.commence(this.exchange, e)).willReturn(result);
assertThat(this.handler.onAuthenticationFailure(this.filterExchange, e)).isEqualTo(result);
}

View File

@@ -29,7 +29,7 @@ import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -47,7 +47,7 @@ public class ServerFormLoginAuthenticationConverterTests {
@Before
public void setup() {
when(this.exchange.getFormData()).thenReturn(Mono.just(this.data));
given(this.exchange.getFormData()).willReturn(Mono.just(this.data));
}
@Test

View File

@@ -34,7 +34,7 @@ import org.springframework.security.web.authentication.preauth.x509.X509TestUtil
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;
@RunWith(MockitoJUnitRunner.class)
public class ServerX509AuthenticationConverterTests {
@@ -54,7 +54,7 @@ public class ServerX509AuthenticationConverterTests {
this.request = MockServerHttpRequest.get("/");
this.certificate = X509TestUtils.buildTestCertificate();
when(this.principalExtractor.extractPrincipal(any())).thenReturn("Luke Taylor");
given(this.principalExtractor.extractPrincipal(any())).willReturn("Luke Taylor");
}
@Test

View File

@@ -57,10 +57,10 @@ 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.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.security.core.context.ReactiveSecurityContextHolder.withSecurityContext;
import static org.springframework.security.web.server.authentication.SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR;
@@ -100,7 +100,7 @@ public class SwitchUserWebFilterTests {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/not/existing"));
WebFilterChain chain = mock(WebFilterChain.class);
when(chain.filter(exchange)).thenReturn(Mono.empty());
given(chain.filter(exchange)).willReturn(Mono.empty());
// when
this.switchUserWebFilter.filter(exchange, chain).block();
@@ -128,11 +128,11 @@ public class SwitchUserWebFilterTests {
"credentials");
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
when(this.userDetailsService.findByUsername(targetUsername)).thenReturn(Mono.just(switchUserDetails));
when(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
.thenReturn(Mono.empty());
when(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
.thenReturn(Mono.empty());
given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails));
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
.willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
.willReturn(Mono.empty());
// when
this.switchUserWebFilter.filter(exchange, chain)
@@ -182,12 +182,12 @@ public class SwitchUserWebFilterTests {
final WebFilterChain chain = mock(WebFilterChain.class);
when(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
.thenReturn(Mono.empty());
when(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
.thenReturn(Mono.empty());
when(this.userDetailsService.findByUsername(targetUsername))
.thenReturn(Mono.just(switchUserDetails(targetUsername, true)));
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
.willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
.willReturn(Mono.empty());
given(this.userDetailsService.findByUsername(targetUsername))
.willReturn(Mono.just(switchUserDetails(targetUsername, true)));
// when
this.switchUserWebFilter.filter(exchange, chain)
@@ -235,9 +235,9 @@ public class SwitchUserWebFilterTests {
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
final UserDetails switchUserDetails = switchUserDetails(targetUsername, false);
when(this.userDetailsService.findByUsername(any(String.class))).thenReturn(Mono.just(switchUserDetails));
when(this.failureHandler.onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class)))
.thenReturn(Mono.empty());
given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails));
given(this.failureHandler.onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class)))
.willReturn(Mono.empty());
// when
this.switchUserWebFilter.filter(exchange, chain)
@@ -260,7 +260,7 @@ public class SwitchUserWebFilterTests {
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
final UserDetails switchUserDetails = switchUserDetails(targetUsername, false);
when(this.userDetailsService.findByUsername(any(String.class))).thenReturn(Mono.just(switchUserDetails));
given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails));
this.exceptionRule.expect(DisabledException.class);
@@ -287,10 +287,10 @@ public class SwitchUserWebFilterTests {
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
when(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
.thenReturn(Mono.empty());
when(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
.thenReturn(Mono.empty());
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
.willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
.willReturn(Mono.empty());
// when
this.switchUserWebFilter.filter(exchange, chain)

View File

@@ -36,7 +36,7 @@ import org.springframework.security.web.server.WebFilterExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Eric Deandrea
@@ -63,10 +63,10 @@ public class DelegatingServerLogoutHandlerTests {
@Before
public void setup() {
when(this.delegate1.logout(any(WebFilterExchange.class), any(Authentication.class)))
.thenReturn(this.delegate1Result.mono());
when(this.delegate2.logout(any(WebFilterExchange.class), any(Authentication.class)))
.thenReturn(this.delegate2Result.mono());
given(this.delegate1.logout(any(WebFilterExchange.class), any(Authentication.class)))
.willReturn(this.delegate1Result.mono());
given(this.delegate2.logout(any(WebFilterExchange.class), any(Authentication.class)))
.willReturn(this.delegate2Result.mono());
}
@Test

View File

@@ -23,9 +23,9 @@ import org.springframework.security.web.server.header.ServerHttpHeadersWriter;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
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 MD Sayem Ahmed
@@ -45,7 +45,7 @@ public class HeaderWriterServerLogoutHandlerTests {
HeaderWriterServerLogoutHandler handler = new HeaderWriterServerLogoutHandler(headersWriter);
ServerWebExchange serverWebExchange = mock(ServerWebExchange.class);
WebFilterExchange filterExchange = mock(WebFilterExchange.class);
when(filterExchange.getExchange()).thenReturn(serverWebExchange);
given(filterExchange.getExchange()).willReturn(serverWebExchange);
Authentication authentication = mock(Authentication.class);
handler.logout(filterExchange, authentication);

View File

@@ -33,7 +33,7 @@ import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -52,7 +52,7 @@ public class AuthorizationWebFilterTests {
@Test
public void filterWhenNoSecurityContextThenThrowsAccessDenied() {
when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono());
given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono());
AuthorizationWebFilter filter = new AuthorizationWebFilter(
(a, e) -> Mono.error(new AccessDeniedException("Denied")));
@@ -64,7 +64,7 @@ public class AuthorizationWebFilterTests {
@Test
public void filterWhenNoAuthenticationThenThrowsAccessDenied() {
when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono());
given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono());
AuthorizationWebFilter filter = new AuthorizationWebFilter(
(a, e) -> a.flatMap(auth -> Mono.error(new AccessDeniedException("Denied"))));
@@ -77,7 +77,7 @@ public class AuthorizationWebFilterTests {
@Test
public void filterWhenAuthenticationThenThrowsAccessDenied() {
when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono());
given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono());
AuthorizationWebFilter filter = new AuthorizationWebFilter(
(a, e) -> Mono.error(new AccessDeniedException("Denied")));
@@ -91,7 +91,7 @@ public class AuthorizationWebFilterTests {
@Test
public void filterWhenDoesNotAccessAuthenticationThenSecurityContextNotSubscribed() {
PublisherProbe<SecurityContext> context = PublisherProbe.empty();
when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono());
given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono());
AuthorizationWebFilter filter = new AuthorizationWebFilter(
(a, e) -> Mono.error(new AccessDeniedException("Denied")));
@@ -106,7 +106,7 @@ public class AuthorizationWebFilterTests {
@Test
public void filterWhenGrantedAndDoesNotAccessAuthenticationThenChainSubscribedAndSecurityContextNotSubscribed() {
PublisherProbe<SecurityContext> context = PublisherProbe.empty();
when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono());
given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono());
AuthorizationWebFilter filter = new AuthorizationWebFilter(
(a, e) -> Mono.just(new AuthorizationDecision(true)));
@@ -121,7 +121,7 @@ public class AuthorizationWebFilterTests {
@Test
public void filterWhenGrantedAndDoeAccessAuthenticationThenChainSubscribedAndSecurityContextSubscribed() {
PublisherProbe<SecurityContext> context = PublisherProbe.empty();
when(this.chain.filter(this.exchange)).thenReturn(this.chainResult.mono());
given(this.chain.filter(this.exchange)).willReturn(this.chainResult.mono());
AuthorizationWebFilter filter = new AuthorizationWebFilter((a, e) -> a
.map(auth -> new AuthorizationDecision(true)).defaultIfEmpty(new AuthorizationDecision(true)));

View File

@@ -33,8 +33,8 @@ import org.springframework.web.server.ServerWebExchange;
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.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -75,9 +75,9 @@ public class DelegatingReactiveAuthorizationManagerTests {
@Test
public void checkWhenFirstMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
when(this.match1.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(this.delegate1.check(eq(this.authentication), any(AuthorizationContext.class)))
.thenReturn(Mono.just(this.decision));
given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate1.check(eq(this.authentication), any(AuthorizationContext.class)))
.willReturn(Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
@@ -86,10 +86,10 @@ public class DelegatingReactiveAuthorizationManagerTests {
@Test
public void checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
when(this.match1.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.match2.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class)))
.thenReturn(Mono.just(this.decision));
given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.match2.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class)))
.willReturn(Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);

View File

@@ -36,7 +36,7 @@ import org.springframework.web.server.WebFilterChain;
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
@@ -68,9 +68,9 @@ public class ExceptionTranslationWebFilterTests {
@Before
public void setup() {
when(this.exchange.getResponse()).thenReturn(new MockServerHttpResponse());
when(this.deniedHandler.handle(any(), any())).thenReturn(this.deniedPublisher.mono());
when(this.entryPoint.commence(any(), any())).thenReturn(this.entryPointPublisher.mono());
given(this.exchange.getResponse()).willReturn(new MockServerHttpResponse());
given(this.deniedHandler.handle(any(), any())).willReturn(this.deniedPublisher.mono());
given(this.entryPoint.commence(any(), any())).willReturn(this.entryPointPublisher.mono());
this.filter.setAuthenticationEntryPoint(this.entryPoint);
this.filter.setAccessDeniedHandler(this.deniedHandler);
@@ -78,7 +78,7 @@ public class ExceptionTranslationWebFilterTests {
@Test
public void filterWhenNoExceptionThenNotHandled() {
when(this.chain.filter(this.exchange)).thenReturn(Mono.empty());
given(this.chain.filter(this.exchange)).willReturn(Mono.empty());
StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify();
@@ -88,7 +88,7 @@ public class ExceptionTranslationWebFilterTests {
@Test
public void filterWhenNotAccessDeniedExceptionThenNotHandled() {
when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new IllegalArgumentException("oops")));
given(this.chain.filter(this.exchange)).willReturn(Mono.error(new IllegalArgumentException("oops")));
StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectError(IllegalArgumentException.class)
.verify();
@@ -99,8 +99,8 @@ public class ExceptionTranslationWebFilterTests {
@Test
public void filterWhenAccessDeniedExceptionAndNotAuthenticatedThenHandled() {
when(this.exchange.getPrincipal()).thenReturn(Mono.empty());
when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized")));
given(this.exchange.getPrincipal()).willReturn(Mono.empty());
given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized")));
StepVerifier.create(this.filter.filter(this.exchange, this.chain)).verifyComplete();
@@ -111,8 +111,8 @@ public class ExceptionTranslationWebFilterTests {
@Test
public void filterWhenDefaultsAndAccessDeniedExceptionAndAuthenticatedThenForbidden() {
this.filter = new ExceptionTranslationWebFilter();
when(this.exchange.getPrincipal()).thenReturn(Mono.just(this.principal));
when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized")));
given(this.exchange.getPrincipal()).willReturn(Mono.just(this.principal));
given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized")));
StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify();
@@ -122,8 +122,8 @@ public class ExceptionTranslationWebFilterTests {
@Test
public void filterWhenDefaultsAndAccessDeniedExceptionAndNotAuthenticatedThenUnauthorized() {
this.filter = new ExceptionTranslationWebFilter();
when(this.exchange.getPrincipal()).thenReturn(Mono.empty());
when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized")));
given(this.exchange.getPrincipal()).willReturn(Mono.empty());
given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized")));
StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify();
@@ -132,8 +132,8 @@ public class ExceptionTranslationWebFilterTests {
@Test
public void filterWhenAccessDeniedExceptionAndAuthenticatedThenHandled() {
when(this.exchange.getPrincipal()).thenReturn(Mono.just(this.principal));
when(this.chain.filter(this.exchange)).thenReturn(Mono.error(new AccessDeniedException("Not Authorized")));
given(this.exchange.getPrincipal()).willReturn(Mono.just(this.principal));
given(this.chain.filter(this.exchange)).willReturn(Mono.error(new AccessDeniedException("Not Authorized")));
StepVerifier.create(this.filter.filter(this.exchange, this.chain)).expectComplete().verify();

View File

@@ -27,10 +27,10 @@ import org.springframework.security.web.server.authorization.ServerWebExchangeDe
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.web.server.ServerWebExchange;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.match;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.notMatch;
@@ -55,9 +55,9 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests {
public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() {
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
when(matcher.matches(this.exchange)).thenReturn(notMatch());
when(handler.handle(this.exchange, null)).thenReturn(Mono.empty());
when(this.accessDeniedHandler.handle(this.exchange, null)).thenReturn(Mono.empty());
given(matcher.matches(this.exchange)).willReturn(notMatch());
given(handler.handle(this.exchange, null)).willReturn(Mono.empty());
given(this.accessDeniedHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(matcher, handler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
@@ -75,9 +75,9 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests {
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
when(firstMatcher.matches(this.exchange)).thenReturn(match());
when(firstHandler.handle(this.exchange, null)).thenReturn(Mono.empty());
when(secondHandler.handle(this.exchange, null)).thenReturn(Mono.empty());
given(firstMatcher.matches(this.exchange)).willReturn(match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
@@ -98,10 +98,10 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests {
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
when(firstMatcher.matches(this.exchange)).thenReturn(notMatch());
when(secondMatcher.matches(this.exchange)).thenReturn(match());
when(firstHandler.handle(this.exchange, null)).thenReturn(Mono.empty());
when(secondHandler.handle(this.exchange, null)).thenReturn(Mono.empty());
given(firstMatcher.matches(this.exchange)).willReturn(notMatch());
given(secondMatcher.matches(this.exchange)).willReturn(match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));

View File

@@ -39,7 +39,7 @@ import org.springframework.web.server.handler.DefaultWebFilterChain;
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
@@ -66,7 +66,7 @@ public class ReactorContextWebFilterTests {
public void setup() {
this.filter = new ReactorContextWebFilter(this.repository);
this.handler = WebTestHandler.bindToWebFilters(this.filter);
when(this.repository.load(any())).thenReturn(this.securityContext.mono());
given(this.repository.load(any())).willReturn(this.securityContext.mono());
}
@Test(expected = IllegalArgumentException.class)
@@ -97,7 +97,7 @@ public class ReactorContextWebFilterTests {
@Test
public void filterWhenPrincipalAndGetPrincipalThenInteractAndUseOriginalPrincipal() {
SecurityContextImpl context = new SecurityContextImpl(this.principal);
when(this.repository.load(any())).thenReturn(Mono.just(context));
given(this.repository.load(any())).willReturn(Mono.just(context));
this.handler = WebTestHandler.bindToWebFilters(this.filter,
(e, c) -> ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)
.doOnSuccess(p -> assertThat(p).isSameAs(this.principal)).flatMap(p -> c.filter(e)));

View File

@@ -29,8 +29,8 @@ import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.web.server.WebFilterChain;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Eric Deandrea
@@ -56,7 +56,7 @@ public class CsrfServerLogoutHandlerTests {
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
this.filterExchange = new WebFilterExchange(this.exchange, this.filterChain);
this.handler = new CsrfServerLogoutHandler(this.csrfTokenRepository);
when(this.csrfTokenRepository.saveToken(this.exchange, null)).thenReturn(Mono.empty());
given(this.csrfTokenRepository.saveToken(this.exchange, null)).willReturn(Mono.empty());
}
@Test

View File

@@ -40,9 +40,9 @@ import org.springframework.web.server.WebSession;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.mock.web.server.MockServerWebExchange.from;
import static org.springframework.web.reactive.function.BodyInserters.fromMultipartData;
@@ -71,7 +71,7 @@ public class CsrfWebFilterTests {
@Test
public void filterWhenGetThenSessionNotCreatedAndChainContinues() {
PublisherProbe<Void> chainResult = PublisherProbe.empty();
when(this.chain.filter(this.get)).thenReturn(chainResult.mono());
given(this.chain.filter(this.get)).willReturn(chainResult.mono());
Mono<Void> result = this.csrfFilter.filter(this.get, this.chain);
@@ -95,7 +95,7 @@ public class CsrfWebFilterTests {
@Test
public void filterWhenPostAndEstablishedCsrfTokenAndRequestMissingTokenThenCsrfException() {
this.csrfFilter.setCsrfTokenRepository(this.repository);
when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token));
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
@@ -107,7 +107,7 @@ public class CsrfWebFilterTests {
@Test
public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamInvalidTokenThenCsrfException() {
this.csrfFilter.setCsrfTokenRepository(this.repository);
when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token));
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
this.post = from(MockServerHttpRequest.post("/")
.body(this.token.getParameterName() + "=" + this.token.getToken() + "INVALID"));
@@ -121,11 +121,11 @@ public class CsrfWebFilterTests {
@Test
public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamValidTokenThenContinues() {
PublisherProbe<Void> chainResult = PublisherProbe.empty();
when(this.chain.filter(any())).thenReturn(chainResult.mono());
given(this.chain.filter(any())).willReturn(chainResult.mono());
this.csrfFilter.setCsrfTokenRepository(this.repository);
when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token));
when(this.repository.generateToken(any())).thenReturn(Mono.just(this.token));
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
this.post = from(MockServerHttpRequest.post("/").contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(this.token.getParameterName() + "=" + this.token.getToken()));
@@ -139,7 +139,7 @@ public class CsrfWebFilterTests {
@Test
public void filterWhenPostAndEstablishedCsrfTokenAndHeaderInvalidTokenThenCsrfException() {
this.csrfFilter.setCsrfTokenRepository(this.repository);
when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token));
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
this.post = from(
MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken() + "INVALID"));
@@ -153,11 +153,11 @@ public class CsrfWebFilterTests {
@Test
public void filterWhenPostAndEstablishedCsrfTokenAndHeaderValidTokenThenContinues() {
PublisherProbe<Void> chainResult = PublisherProbe.empty();
when(this.chain.filter(any())).thenReturn(chainResult.mono());
given(this.chain.filter(any())).willReturn(chainResult.mono());
this.csrfFilter.setCsrfTokenRepository(this.repository);
when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token));
when(this.repository.generateToken(any())).thenReturn(Mono.just(this.token));
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
this.post = from(MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken()));
Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
@@ -181,7 +181,7 @@ public class CsrfWebFilterTests {
@Test
public void doFilterWhenSkipExchangeInvokedThenSkips() {
PublisherProbe<Void> chainResult = PublisherProbe.empty();
when(this.chain.filter(any())).thenReturn(chainResult.mono());
given(this.chain.filter(any())).willReturn(chainResult.mono());
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
this.csrfFilter.setRequireCsrfProtectionMatcher(matcher);
@@ -196,7 +196,7 @@ public class CsrfWebFilterTests {
@Test
public void filterWhenMultipartFormDataAndNotEnabledThenDenied() {
this.csrfFilter.setCsrfTokenRepository(this.repository);
when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token));
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
@@ -209,8 +209,8 @@ public class CsrfWebFilterTests {
public void filterWhenMultipartFormDataAndEnabledThenGranted() {
this.csrfFilter.setCsrfTokenRepository(this.repository);
this.csrfFilter.setTokenFromMultipartDataEnabled(true);
when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token));
when(this.repository.generateToken(any())).thenReturn(Mono.just(this.token));
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
@@ -223,8 +223,8 @@ public class CsrfWebFilterTests {
public void filterWhenFormDataAndEnabledThenGranted() {
this.csrfFilter.setCsrfTokenRepository(this.repository);
this.csrfFilter.setTokenFromMultipartDataEnabled(true);
when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token));
when(this.repository.generateToken(any())).thenReturn(Mono.just(this.token));
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
@@ -237,7 +237,7 @@ public class CsrfWebFilterTests {
public void filterWhenMultipartMixedAndEnabledThenNotRead() {
this.csrfFilter.setCsrfTokenRepository(this.repository);
this.csrfFilter.setTokenFromMultipartDataEnabled(true);
when(this.repository.loadToken(any())).thenReturn(Mono.just(this.token));
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();

View File

@@ -34,8 +34,8 @@ import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
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
@@ -61,7 +61,7 @@ public class CompositeServerHttpHeadersWriterTests {
@Test
public void writeHttpHeadersWhenErrorNoErrorThenError() {
when(this.writer1.writeHttpHeaders(this.exchange)).thenReturn(Mono.error(new RuntimeException()));
given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException()));
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
@@ -72,7 +72,7 @@ public class CompositeServerHttpHeadersWriterTests {
@Test
public void writeHttpHeadersWhenErrorErrorThenError() {
when(this.writer1.writeHttpHeaders(this.exchange)).thenReturn(Mono.error(new RuntimeException()));
given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException()));
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
@@ -83,8 +83,8 @@ public class CompositeServerHttpHeadersWriterTests {
@Test
public void writeHttpHeadersWhenNoErrorThenNoError() {
when(this.writer1.writeHttpHeaders(this.exchange)).thenReturn(Mono.empty());
when(this.writer2.writeHttpHeaders(this.exchange)).thenReturn(Mono.empty());
given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
given(this.writer2.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);

View File

@@ -29,9 +29,9 @@ import org.springframework.security.test.web.reactive.server.WebTestHandler.WebH
import org.springframework.test.web.reactive.server.WebTestClient;
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;
/**
* @author Rob Winch
@@ -47,7 +47,7 @@ public class HttpHeaderWriterWebFilterTests {
@Before
public void setup() {
when(this.writer.writeHttpHeaders(any())).thenReturn(Mono.empty());
given(this.writer.writeHttpHeaders(any())).willReturn(Mono.empty());
this.filter = new HttpHeaderWriterWebFilter(this.writer);
}

View File

@@ -35,8 +35,8 @@ import org.springframework.web.server.WebFilterChain;
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.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link ServerRequestCacheWebFilter}
@@ -61,7 +61,7 @@ public class ServerRequestCacheWebFilterTests {
public void setup() {
this.requestCacheFilter = new ServerRequestCacheWebFilter();
this.requestCacheFilter.setRequestCache(this.requestCache);
when(this.chain.filter(any(ServerWebExchange.class))).thenReturn(Mono.empty());
given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty());
}
@Test
@@ -69,7 +69,7 @@ public class ServerRequestCacheWebFilterTests {
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
ServerHttpRequest savedRequest = MockServerHttpRequest.get("/")
.header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML.getType()).build();
when(this.requestCache.removeMatchingRequest(any())).thenReturn(Mono.just(savedRequest));
given(this.requestCache.removeMatchingRequest(any())).willReturn(Mono.just(savedRequest));
this.requestCacheFilter.filter(exchange, this.chain).block();
@@ -82,7 +82,7 @@ public class ServerRequestCacheWebFilterTests {
public void filterWhenRequestDoesNotMatchThenRequestDoesNotChange() {
MockServerHttpRequest initialRequest = MockServerHttpRequest.get("/").build();
ServerWebExchange exchange = MockServerWebExchange.from(initialRequest);
when(this.requestCache.removeMatchingRequest(any())).thenReturn(Mono.empty());
given(this.requestCache.removeMatchingRequest(any())).willReturn(Mono.empty());
this.requestCacheFilter.filter(exchange, this.chain).block();

View File

@@ -34,9 +34,9 @@ import org.springframework.web.server.WebFilterChain;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests for {@link HttpsRedirectWebFilter}
@@ -54,7 +54,7 @@ public class HttpsRedirectWebFilterTests {
@Before
public void configureFilter() {
this.filter = new HttpsRedirectWebFilter();
when(this.chain.filter(any(ServerWebExchange.class))).thenReturn(Mono.empty());
given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty());
}
@Test
@@ -75,7 +75,8 @@ public class HttpsRedirectWebFilterTests {
@Test
public void filterWhenExchangeMismatchesThenNoRedirect() {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
when(matcher.matches(any(ServerWebExchange.class))).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(matcher.matches(any(ServerWebExchange.class)))
.willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
this.filter.setRequiresHttpsRedirectMatcher(matcher);
ServerWebExchange exchange = get("http://localhost:8080");
@@ -86,7 +87,7 @@ public class HttpsRedirectWebFilterTests {
@Test
public void filterWhenExchangeMatchesAndRequestIsInsecureThenRedirects() {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
when(matcher.matches(any(ServerWebExchange.class))).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
given(matcher.matches(any(ServerWebExchange.class))).willReturn(ServerWebExchangeMatcher.MatchResult.match());
this.filter.setRequiresHttpsRedirectMatcher(matcher);
ServerWebExchange exchange = get("http://localhost:8080");
@@ -100,7 +101,7 @@ public class HttpsRedirectWebFilterTests {
@Test
public void filterWhenRequestIsInsecureThenPortMapperRemapsPort() {
PortMapper portMapper = mock(PortMapper.class);
when(portMapper.lookupHttpsPort(314)).thenReturn(159);
given(portMapper.lookupHttpsPort(314)).willReturn(159);
this.filter.setPortMapper(portMapper);
ServerWebExchange exchange = get("http://localhost:314");

View File

@@ -28,9 +28,9 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -59,8 +59,8 @@ public class AndServerWebExchangeMatcherTests {
public void matchesWhenTrueTrueThenTrue() {
Map<String, Object> params1 = Collections.singletonMap("foo", "bar");
Map<String, Object> params2 = Collections.singletonMap("x", "y");
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params1));
when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params2));
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params1));
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params2));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
@@ -75,7 +75,7 @@ public class AndServerWebExchangeMatcherTests {
@Test
public void matchesWhenFalseFalseThenFalseAndMatcher2NotInvoked() {
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
@@ -89,8 +89,8 @@ public class AndServerWebExchangeMatcherTests {
@Test
public void matchesWhenTrueFalseThenFalse() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
@@ -103,7 +103,7 @@ public class AndServerWebExchangeMatcherTests {
@Test
public void matchesWhenFalseTrueThenFalse() {
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();

View File

@@ -25,8 +25,8 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.web.server.ServerWebExchange;
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 Tao Qian
@@ -50,7 +50,7 @@ public class NegatedServerWebExchangeMatcherTests {
@Test
public void matchesWhenFalseThenTrue() {
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
@@ -62,7 +62,7 @@ public class NegatedServerWebExchangeMatcherTests {
@Test
public void matchesWhenTrueThenFalse() {
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();

View File

@@ -28,9 +28,9 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -57,8 +57,8 @@ public class OrServerWebExchangeMatcherTests {
@Test
public void matchesWhenFalseFalseThenFalse() {
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
@@ -72,7 +72,7 @@ public class OrServerWebExchangeMatcherTests {
@Test
public void matchesWhenTrueFalseThenTrueAndMatcher2NotInvoked() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
@@ -86,8 +86,8 @@ public class OrServerWebExchangeMatcherTests {
@Test
public void matchesWhenFalseTrueThenTrue() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();

View File

@@ -32,8 +32,8 @@ import org.springframework.web.util.pattern.PathPattern;
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.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -77,16 +77,16 @@ public class PathMatcherServerWebExchangeMatcherTests {
@Test
public void matchesWhenPathMatcherTrueThenReturnTrue() {
when(this.pattern.matches(any())).thenReturn(true);
when(this.pattern.matchAndExtract(any())).thenReturn(this.pathMatchInfo);
when(this.pathMatchInfo.getUriVariables()).thenReturn(new HashMap<>());
given(this.pattern.matches(any())).willReturn(true);
given(this.pattern.matchAndExtract(any())).willReturn(this.pathMatchInfo);
given(this.pathMatchInfo.getUriVariables()).willReturn(new HashMap<>());
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue();
}
@Test
public void matchesWhenPathMatcherFalseThenReturnFalse() {
when(this.pattern.matches(any())).thenReturn(false);
given(this.pattern.matches(any())).willReturn(false);
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse();
}
@@ -95,9 +95,9 @@ public class PathMatcherServerWebExchangeMatcherTests {
public void matchesWhenPathMatcherTrueAndMethodTrueThenReturnTrue() {
this.matcher = new PathPatternParserServerWebExchangeMatcher(this.pattern,
this.exchange.getRequest().getMethod());
when(this.pattern.matches(any())).thenReturn(true);
when(this.pattern.matchAndExtract(any())).thenReturn(this.pathMatchInfo);
when(this.pathMatchInfo.getUriVariables()).thenReturn(new HashMap<>());
given(this.pattern.matches(any())).willReturn(true);
given(this.pattern.matchAndExtract(any())).willReturn(this.pathMatchInfo);
given(this.pathMatchInfo.getUriVariables()).willReturn(new HashMap<>());
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue();
}

View File

@@ -35,8 +35,8 @@ import org.springframework.web.servlet.handler.RequestMatchResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Rob Winch
@@ -72,7 +72,7 @@ public class MvcRequestMatcherTests {
@Test
public void extractUriTemplateVariablesSuccess() throws Exception {
this.matcher = new MvcRequestMatcher(this.introspector, "/{p}");
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(null);
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null);
assertThat(this.matcher.extractUriTemplateVariables(this.request)).containsEntry("p", "path");
assertThat(this.matcher.matcher(this.request).getVariables()).containsEntry("p", "path");
@@ -80,9 +80,9 @@ public class MvcRequestMatcherTests {
@Test
public void extractUriTemplateVariablesFail() throws Exception {
when(this.result.extractUriTemplateVariables()).thenReturn(Collections.<String, String>emptyMap());
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping);
when(this.mapping.match(eq(this.request), this.pattern.capture())).thenReturn(this.result);
given(this.result.extractUriTemplateVariables()).willReturn(Collections.<String, String>emptyMap());
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result);
assertThat(this.matcher.extractUriTemplateVariables(this.request)).isEmpty();
assertThat(this.matcher.matcher(this.request).getVariables()).isEmpty();
@@ -91,7 +91,7 @@ public class MvcRequestMatcherTests {
@Test
public void extractUriTemplateVariablesDefaultSuccess() throws Exception {
this.matcher = new MvcRequestMatcher(this.introspector, "/{p}");
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(null);
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null);
assertThat(this.matcher.extractUriTemplateVariables(this.request)).containsEntry("p", "path");
assertThat(this.matcher.matcher(this.request).getVariables()).containsEntry("p", "path");
@@ -100,7 +100,7 @@ public class MvcRequestMatcherTests {
@Test
public void extractUriTemplateVariablesDefaultFail() throws Exception {
this.matcher = new MvcRequestMatcher(this.introspector, "/nomatch/{p}");
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(null);
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null);
assertThat(this.matcher.extractUriTemplateVariables(this.request)).isEmpty();
assertThat(this.matcher.matcher(this.request).getVariables()).isEmpty();
@@ -108,8 +108,8 @@ public class MvcRequestMatcherTests {
@Test
public void matchesServletPathTrue() throws Exception {
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping);
when(this.mapping.match(eq(this.request), this.pattern.capture())).thenReturn(this.result);
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result);
this.matcher.setServletPath("/spring");
this.request.setServletPath("/spring");
@@ -127,8 +127,8 @@ public class MvcRequestMatcherTests {
@Test
public void matchesPathOnlyTrue() throws Exception {
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping);
when(this.mapping.match(eq(this.request), this.pattern.capture())).thenReturn(this.result);
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result);
assertThat(this.matcher.matches(this.request)).isTrue();
assertThat(this.pattern.getValue()).isEqualTo("/path");
@@ -136,7 +136,7 @@ public class MvcRequestMatcherTests {
@Test
public void matchesDefaultMatches() throws Exception {
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(null);
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null);
assertThat(this.matcher.matches(this.request)).isTrue();
}
@@ -144,14 +144,14 @@ public class MvcRequestMatcherTests {
@Test
public void matchesDefaultDoesNotMatch() throws Exception {
this.request.setServletPath("/other");
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(null);
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(null);
assertThat(this.matcher.matches(this.request)).isFalse();
}
@Test
public void matchesPathOnlyFalse() throws Exception {
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping);
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
assertThat(this.matcher.matches(this.request)).isFalse();
}
@@ -159,8 +159,8 @@ public class MvcRequestMatcherTests {
@Test
public void matchesMethodAndPathTrue() throws Exception {
this.matcher.setMethod(HttpMethod.GET);
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping);
when(this.mapping.match(eq(this.request), this.pattern.capture())).thenReturn(this.result);
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
given(this.mapping.match(eq(this.request), this.pattern.capture())).willReturn(this.result);
assertThat(this.matcher.matches(this.request)).isTrue();
assertThat(this.pattern.getValue()).isEqualTo("/path");
@@ -193,7 +193,7 @@ public class MvcRequestMatcherTests {
@Test
public void matchesMethodAndPathFalsePath() throws Exception {
this.matcher.setMethod(HttpMethod.GET);
when(this.introspector.getMatchableHandlerMapping(this.request)).thenReturn(this.mapping);
given(this.introspector.getMatchableHandlerMapping(this.request)).willReturn(this.mapping);
assertThat(this.matcher.matches(this.request)).isFalse();
}
@@ -205,8 +205,8 @@ public class MvcRequestMatcherTests {
@Test
public void matchesGetMatchableHandlerMappingThrows() throws Exception {
when(this.introspector.getMatchableHandlerMapping(this.request))
.thenThrow(new HttpRequestMethodNotSupportedException(this.request.getMethod()));
given(this.introspector.getMatchableHandlerMapping(this.request))
.willThrow(new HttpRequestMethodNotSupportedException(this.request.getMethod()));
assertThat(this.matcher.matches(this.request)).isTrue();
}

View File

@@ -36,12 +36,12 @@ import org.springframework.security.web.context.SecurityContextRepository;
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.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* @author Luke Taylor
@@ -71,7 +71,7 @@ public class SessionManagementFilterTests {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
// mock that repo contains a security context
when(repo.containsContext(any(HttpServletRequest.class))).thenReturn(true);
given(repo.containsContext(any(HttpServletRequest.class))).willReturn(true);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
HttpServletRequest request = new MockHttpServletRequest();
authenticateUser();
@@ -125,7 +125,7 @@ public class SessionManagementFilterTests {
FilterChain fc = mock(FilterChain.class);
authenticateUser();
SessionAuthenticationException exception = new SessionAuthenticationException("Failure");
doThrow(exception).when(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(),
willThrow(exception).given(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(),
request, response);
filter.doFilter(request, response, fc);

View File

@@ -29,8 +29,8 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
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;
@RunWith(MockitoJUnitRunner.class)
public class OnCommittedResponseWrapperTests {
@@ -58,8 +58,8 @@ public class OnCommittedResponseWrapperTests {
OnCommittedResponseWrapperTests.this.committed = true;
}
};
when(this.delegate.getWriter()).thenReturn(this.writer);
when(this.delegate.getOutputStream()).thenReturn(this.out);
given(this.delegate.getWriter()).willReturn(this.writer);
given(this.delegate.getOutputStream()).willReturn(this.out);
}
// --- printwriter
@@ -74,7 +74,7 @@ public class OnCommittedResponseWrapperTests {
@Test
public void printWriterCheckError() throws Exception {
boolean expected = true;
when(this.writer.checkError()).thenReturn(expected);
given(this.writer.checkError()).willReturn(expected);
assertThat(this.response.getWriter().checkError()).isEqualTo(expected);
}
@@ -1118,7 +1118,7 @@ public class OnCommittedResponseWrapperTests {
@Test
public void bufferSizePrintWriterWriteCommits() throws Exception {
String expected = "1234567890";
when(this.response.getBufferSize()).thenReturn(expected.length());
given(this.response.getBufferSize()).willReturn(expected.length());
this.response.getWriter().write(expected);
@@ -1128,7 +1128,7 @@ public class OnCommittedResponseWrapperTests {
@Test
public void bufferSizeCommitsOnce() throws Exception {
String expected = "1234567890";
when(this.response.getBufferSize()).thenReturn(expected.length());
given(this.response.getBufferSize()).willReturn(expected.length());
this.response.getWriter().write(expected);

View File

@@ -27,7 +27,7 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -79,7 +79,7 @@ public class AndRequestMatcherTests {
@Test
public void matchesSingleTrue() {
when(this.delegate.matches(this.request)).thenReturn(true);
given(this.delegate.matches(this.request)).willReturn(true);
this.matcher = new AndRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isTrue();
@@ -87,8 +87,8 @@ public class AndRequestMatcherTests {
@Test
public void matchesMultiTrue() {
when(this.delegate.matches(this.request)).thenReturn(true);
when(this.delegate2.matches(this.request)).thenReturn(true);
given(this.delegate.matches(this.request)).willReturn(true);
given(this.delegate2.matches(this.request)).willReturn(true);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();
@@ -96,7 +96,7 @@ public class AndRequestMatcherTests {
@Test
public void matchesSingleFalse() {
when(this.delegate.matches(this.request)).thenReturn(false);
given(this.delegate.matches(this.request)).willReturn(false);
this.matcher = new AndRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isFalse();
@@ -104,7 +104,7 @@ public class AndRequestMatcherTests {
@Test
public void matchesMultiBothFalse() {
when(this.delegate.matches(this.request)).thenReturn(false);
given(this.delegate.matches(this.request)).willReturn(false);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
@@ -112,8 +112,8 @@ public class AndRequestMatcherTests {
@Test
public void matchesMultiSingleFalse() {
when(this.delegate.matches(this.request)).thenReturn(true);
when(this.delegate2.matches(this.request)).thenReturn(false);
given(this.delegate.matches(this.request)).willReturn(true);
given(this.delegate2.matches(this.request)).willReturn(false);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();

View File

@@ -27,7 +27,7 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.util.UrlPathHelper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Luke Taylor
@@ -206,7 +206,7 @@ public class AntPathRequestMatcherTests {
}
private HttpServletRequest createRequestWithNullMethod(String path) {
when(this.request.getServletPath()).thenReturn(path);
given(this.request.getServletPath()).willReturn(path);
return this.request;
}

View File

@@ -33,7 +33,7 @@ import org.springframework.web.context.request.NativeWebRequest;
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
@@ -93,8 +93,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void negotiationStrategyThrowsHMTNAE() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenThrow(new HttpMediaTypeNotAcceptableException("oops"));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willThrow(new HttpMediaTypeNotAcceptableException("oops"));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.ALL);
assertThat(this.matcher.matches(this.request)).isFalse();
@@ -103,8 +103,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void mediaAllMatches() throws Exception {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(MediaType.ALL));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(MediaType.ALL));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML);
assertThat(this.matcher.matches(this.request)).isTrue();
@@ -187,8 +187,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void multipleMediaType() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.APPLICATION_XHTML_XML, MediaType.TEXT_HTML));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.APPLICATION_XHTML_XML, MediaType.TEXT_HTML));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.APPLICATION_ATOM_XML,
MediaType.TEXT_HTML);
@@ -205,8 +205,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void resolveTextPlainMatchesTextAll() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(MediaType.TEXT_PLAIN));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(MediaType.TEXT_PLAIN));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, new MediaType("text", "*"));
assertThat(this.matcher.matches(this.request)).isTrue();
@@ -222,8 +222,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void resolveTextAllMatchesTextPlain() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(new MediaType("text", "*")));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(new MediaType("text", "*")));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_PLAIN);
assertThat(this.matcher.matches(this.request)).isTrue();
@@ -241,8 +241,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void useEqualsResolveTextAllMatchesTextPlain() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(new MediaType("text", "*")));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(new MediaType("text", "*")));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_PLAIN);
this.matcher.setUseEquals(true);
@@ -260,8 +260,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void useEqualsResolveTextPlainMatchesTextAll() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(MediaType.TEXT_PLAIN));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(MediaType.TEXT_PLAIN));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, new MediaType("text", "*"));
this.matcher.setUseEquals(true);
@@ -279,8 +279,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void useEqualsSame() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(MediaType.TEXT_PLAIN));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(MediaType.TEXT_PLAIN));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_PLAIN);
this.matcher.setUseEquals(true);
@@ -298,8 +298,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void useEqualsWithCustomMediaType() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(new MediaType("text", "unique")));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(new MediaType("text", "unique")));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, new MediaType("text", "unique"));
this.matcher.setUseEquals(true);
@@ -319,8 +319,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void mediaAllIgnoreMediaTypeAll() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(MediaType.ALL));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(MediaType.ALL));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML);
this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
@@ -338,8 +338,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void mediaAllAndTextHtmlIgnoreMediaTypeAll() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(MediaType.ALL, MediaType.TEXT_HTML));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(MediaType.ALL, MediaType.TEXT_HTML));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML);
this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
@@ -357,8 +357,8 @@ public class MediaTypeRequestMatcherTests {
@Test
public void mediaAllQ08AndTextPlainIgnoreMediaTypeAll() throws HttpMediaTypeNotAcceptableException {
when(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.thenReturn(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.parseMediaType("*/*;q=0.8")));
given(this.negotiationStrategy.resolveMediaTypes(any(NativeWebRequest.class)))
.willReturn(Arrays.asList(MediaType.TEXT_PLAIN, MediaType.parseMediaType("*/*;q=0.8")));
this.matcher = new MediaTypeRequestMatcher(this.negotiationStrategy, MediaType.TEXT_HTML);
this.matcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));

View File

@@ -23,7 +23,7 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -47,7 +47,7 @@ public class NegatedRequestMatcherTests {
@Test
public void matchesDelegateFalse() {
when(this.delegate.matches(this.request)).thenReturn(false);
given(this.delegate.matches(this.request)).willReturn(false);
this.matcher = new NegatedRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isTrue();
@@ -55,7 +55,7 @@ public class NegatedRequestMatcherTests {
@Test
public void matchesDelegateTrue() {
when(this.delegate.matches(this.request)).thenReturn(true);
given(this.delegate.matches(this.request)).willReturn(true);
this.matcher = new NegatedRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isFalse();

View File

@@ -27,7 +27,7 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
@@ -79,7 +79,7 @@ public class OrRequestMatcherTests {
@Test
public void matchesSingleTrue() {
when(this.delegate.matches(this.request)).thenReturn(true);
given(this.delegate.matches(this.request)).willReturn(true);
this.matcher = new OrRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isTrue();
@@ -87,7 +87,7 @@ public class OrRequestMatcherTests {
@Test
public void matchesMultiTrue() {
when(this.delegate.matches(this.request)).thenReturn(true);
given(this.delegate.matches(this.request)).willReturn(true);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();
@@ -95,7 +95,7 @@ public class OrRequestMatcherTests {
@Test
public void matchesSingleFalse() {
when(this.delegate.matches(this.request)).thenReturn(false);
given(this.delegate.matches(this.request)).willReturn(false);
this.matcher = new OrRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isFalse();
@@ -103,8 +103,8 @@ public class OrRequestMatcherTests {
@Test
public void matchesMultiBothFalse() {
when(this.delegate.matches(this.request)).thenReturn(false);
when(this.delegate2.matches(this.request)).thenReturn(false);
given(this.delegate.matches(this.request)).willReturn(false);
given(this.delegate2.matches(this.request)).willReturn(false);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
@@ -112,7 +112,7 @@ public class OrRequestMatcherTests {
@Test
public void matchesMultiSingleFalse() {
when(this.delegate.matches(this.request)).thenReturn(true);
given(this.delegate.matches(this.request)).willReturn(true);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();

View File

@@ -26,7 +26,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.BDDMockito.given;
/**
* @author Luke Taylor
@@ -115,8 +115,8 @@ public class RegexRequestMatcherTests {
}
private HttpServletRequest createRequestWithNullMethod(String path) {
when(this.request.getQueryString()).thenReturn("doesntMatter");
when(this.request.getServletPath()).thenReturn(path);
given(this.request.getQueryString()).willReturn("doesntMatter");
given(this.request.getServletPath()).willReturn(path);
return this.request;
}