Replace try/catch with AssertJ

Replace manual try/catch/fail blocks with AssertJ calls.
This commit is contained in:
Phillip Webb
2020-09-10 12:06:07 -07:00
committed by Josh Cummings
parent d9276ed8f3
commit 910b81928f
98 changed files with 717 additions and 2122 deletions

View File

@@ -43,7 +43,7 @@ import org.springframework.security.web.firewall.RequestRejectedHandler;
import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@@ -206,12 +206,8 @@ public class FilterChainProxyTests {
throw new ServletException("oops");
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
try {
this.fcp.doFilter(this.request, this.response, this.chain);
fail("Expected Exception");
}
catch (ServletException success) {
}
assertThatExceptionOfType(ServletException.class)
.isThrownBy(() -> this.fcp.doFilter(this.request, this.response, this.chain));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}

View File

@@ -22,7 +22,7 @@ import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link PortMapperImpl}.
@@ -43,23 +43,13 @@ public class PortMapperImplTests {
@Test
public void testDetectsEmptyMap() {
PortMapperImpl portMapper = new PortMapperImpl();
try {
portMapper.setPortMappings(new HashMap<>());
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(new HashMap<>()));
}
@Test
public void testDetectsNullMap() {
PortMapperImpl portMapper = new PortMapperImpl();
try {
portMapper.setPortMappings(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(null));
}
@Test
@@ -73,12 +63,7 @@ public class PortMapperImplTests {
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> map = new HashMap<>();
map.put("79", "80559");
try {
portMapper.setPortMappings(map);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(map));
}
@Test

View File

@@ -21,7 +21,7 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link PortResolverImpl}.
@@ -51,12 +51,7 @@ public class PortResolverImplTests {
@Test
public void testDetectsEmptyPortMapper() {
PortResolverImpl pr = new PortResolverImpl();
try {
pr.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> pr.setPortMapper(null));
}
@Test

View File

@@ -48,7 +48,6 @@ import org.springframework.security.web.savedrequest.SavedRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
@@ -258,16 +257,12 @@ public class ExceptionTranslationFilterTests {
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.afterPropertiesSet();
Exception[] exceptions = { new IOException(), new ServletException(), new RuntimeException() };
for (Exception e : exceptions) {
for (Exception exception : exceptions) {
FilterChain fc = mock(FilterChain.class);
willThrow(e).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
try {
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc);
fail("Should have thrown Exception");
}
catch (Exception expected) {
assertThat(expected).isSameAs(e);
}
willThrow(exception).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThatExceptionOfType(Exception.class)
.isThrownBy(() -> filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc))
.isSameAs(exception);
}
}

View File

@@ -33,6 +33,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
@@ -47,14 +48,10 @@ public class ChannelDecisionManagerImplTests {
@Test
public void testCannotSetEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try {
assertThatIllegalArgumentException().isThrownBy(() -> {
cdm.setChannelProcessors(new Vector());
cdm.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
}).withMessage("A list of ChannelProcessors is required");
}
@Test
@@ -62,25 +59,16 @@ public class ChannelDecisionManagerImplTests {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
List list = new Vector();
list.add("THIS IS NOT A CHANNELPROCESSOR");
try {
cdm.setChannelProcessors(list);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> cdm.setChannelProcessors(list));
}
@Test
public void testCannotSetNullChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try {
assertThatIllegalArgumentException().isThrownBy(() -> {
cdm.setChannelProcessors(null);
cdm.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
}).withMessage("A list of ChannelProcessors is required");
}
@Test
@@ -164,13 +152,8 @@ public class ChannelDecisionManagerImplTests {
@Test
public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try {
cdm.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
assertThatIllegalArgumentException().isThrownBy(cdm::afterPropertiesSet)
.withMessage("A list of ChannelProcessors is required");
}
private class MockChannelProcessor implements ChannelProcessor {

View File

@@ -26,7 +26,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@@ -74,12 +74,7 @@ public class InsecureChannelProcessorTests {
public void testDecideRejectsNulls() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.afterPropertiesSet();
try {
processor.decide(null, null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> processor.decide(null, null));
}
@Test
@@ -97,34 +92,19 @@ public class InsecureChannelProcessorTests {
public void testMissingEntryPoint() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.setEntryPoint(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("entryPoint required");
}
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("entryPoint required");
}
@Test
public void testMissingSecureChannelKeyword() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.setInsecureKeyword(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("insecureKeyword required");
}
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("insecureKeyword required");
processor.setInsecureKeyword("");
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("insecureKeyword required");
}
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("insecureKeyword required");
}
@Test

View File

@@ -30,7 +30,7 @@ import org.springframework.security.web.PortResolver;
import org.springframework.security.web.RedirectStrategy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@@ -43,23 +43,13 @@ public class RetryWithHttpEntryPointTests {
@Test
public void testDetectsMissingPortMapper() {
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
try {
ep.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null));
}
@Test
public void testDetectsMissingPortResolver() {
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
try {
ep.setPortResolver(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null));
}
@Test

View File

@@ -27,7 +27,7 @@ import org.springframework.security.MockPortResolver;
import org.springframework.security.web.PortMapperImpl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link RetryWithHttpsEntryPoint}.
@@ -39,23 +39,13 @@ public class RetryWithHttpsEntryPointTests {
@Test
public void testDetectsMissingPortMapper() {
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
try {
ep.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null));
}
@Test
public void testDetectsMissingPortResolver() {
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
try {
ep.setPortResolver(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null));
}
@Test

View File

@@ -26,7 +26,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@@ -74,12 +74,7 @@ public class SecureChannelProcessorTests {
public void testDecideRejectsNulls() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.afterPropertiesSet();
try {
processor.decide(null, null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> processor.decide(null, null));
}
@Test
@@ -97,34 +92,19 @@ public class SecureChannelProcessorTests {
public void testMissingEntryPoint() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.setEntryPoint(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("entryPoint required");
}
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("entryPoint required");
}
@Test
public void testMissingSecureChannelKeyword() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.setSecureKeyword(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("secureKeyword required");
}
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("secureKeyword required");
processor.setSecureKeyword("");
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("secureKeyword required");
}
assertThatIllegalArgumentException().isThrownBy(() -> processor.afterPropertiesSet())
.withMessage("secureKeyword required");
}
@Test

View File

@@ -42,7 +42,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.eq;
@@ -135,12 +135,7 @@ public class FilterSecurityInterceptorTests {
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
try {
this.interceptor.invoke(fi);
fail("Expected exception");
}
catch (RuntimeException expected) {
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(fi));
verifyZeroInteractions(aim);
}
@@ -163,12 +158,7 @@ public class FilterSecurityInterceptorTests {
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
try {
this.interceptor.invoke(fi);
fail("Expected exception");
}
catch (RuntimeException expected) {
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(fi));
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);

View File

@@ -48,6 +48,7 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -251,13 +252,8 @@ public class AbstractAuthenticationProcessingFilterTests {
this.successHandler.setDefaultTargetUrl("/");
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setFilterProcessesUrl("/login");
try {
filter.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("authenticationManager must be specified");
}
assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet)
.withMessage("authenticationManager must be specified");
}
@Test
@@ -266,13 +262,8 @@ public class AbstractAuthenticationProcessingFilterTests {
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.setAuthenticationManager(mock(AuthenticationManager.class));
filter.setAuthenticationSuccessHandler(this.successHandler);
try {
filter.setFilterProcessesUrl(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("Pattern cannot be null or empty");
}
assertThatIllegalArgumentException().isThrownBy(() -> filter.setFilterProcessesUrl(null))
.withMessage("Pattern cannot be null or empty");
}
@Test

View File

@@ -43,6 +43,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@@ -205,7 +206,7 @@ public class AuthenticationFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
}
@Test(expected = ServletException.class)
@Test
public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
@@ -216,14 +217,9 @@ public class AuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
try {
filter.doFilter(request, response, chain);
}
catch (ServletException ex) {
verifyZeroInteractions(this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
throw ex;
}
assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain));
verifyZeroInteractions(this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test

View File

@@ -25,7 +25,7 @@ import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -38,12 +38,7 @@ public class SavedRequestAwareAuthenticationSuccessHandlerTests {
handler.setDefaultTargetUrl("/acceptableRelativeUrl");
handler.setDefaultTargetUrl("https://some.site.org/index.html");
handler.setDefaultTargetUrl("https://some.site.org/index.html");
try {
handler.setDefaultTargetUrl("missingSlash");
fail("Shouldn't accept default target without leading slash");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> handler.setDefaultTargetUrl("missingSlash"));
}
@Test

View File

@@ -23,7 +23,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@@ -104,18 +104,8 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
@Test
public void setTargetUrlParameterEmptyTargetUrlParameter() {
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
try {
ash.setTargetUrlParameter("");
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
try {
ash.setTargetUrlParameter(" ");
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
assertThatIllegalArgumentException().isThrownBy(() -> ash.setTargetUrlParameter(""));
assertThatIllegalArgumentException().isThrownBy(() -> ash.setTargetUrlParameter(" "));
}
}

View File

@@ -27,7 +27,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -114,12 +114,8 @@ public class UsernamePasswordAuthenticationFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
filter.setAuthenticationManager(am);
try {
filter.attemptAuthentication(request, new MockHttpServletResponse());
fail("Expected AuthenticationException");
}
catch (AuthenticationException ex) {
}
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> filter.attemptAuthentication(request, new MockHttpServletResponse()));
}
/**

View File

@@ -29,7 +29,7 @@ import org.mockito.InOrder;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.inOrder;
@@ -88,12 +88,8 @@ public class CompositeLogoutHandlerTests {
any(HttpServletResponse.class), any(Authentication.class));
List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
try {
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class));
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
assertThatIllegalArgumentException().isThrownBy(() -> handler.logout(mock(HttpServletRequest.class),
mock(HttpServletResponse.class), mock(Authentication.class)));
InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, secondLogoutHandler);
logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));

View File

@@ -24,7 +24,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@@ -59,14 +59,8 @@ public class HttpStatusReturningLogoutSuccessHandlerTests {
@Test
public void testThatSettNullHttpStatusThrowsException() {
try {
new HttpStatusReturningLogoutSuccessHandler(null);
}
catch (IllegalArgumentException ex) {
assertThat(ex).hasMessage("The provided HttpStatus must not be null.");
return;
}
fail("Expected an IllegalArgumentException to be thrown.");
assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusReturningLogoutSuccessHandler(null))
.withMessage("The provided HttpStatus must not be null.");
}
}

View File

@@ -42,7 +42,7 @@ import org.springframework.security.web.authentication.ForwardAuthenticationSucc
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -105,15 +105,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void testAfterPropertiesSet() {
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
try {
filter.afterPropertiesSet();
fail("AfterPropertiesSet didn't throw expected exception");
}
catch (IllegalArgumentException expected) {
}
catch (Exception unexpected) {
fail("AfterPropertiesSet throws unexpected exception");
}
assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet);
}
// SEC-2045

View File

@@ -26,22 +26,15 @@ import org.springframework.security.authentication.AuthenticationCredentialsNotF
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class Http403ForbiddenEntryPointTests {
public void testCommence() {
public void testCommence() throws IOException {
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse resp = new MockHttpServletResponse();
Http403ForbiddenEntryPoint fep = new Http403ForbiddenEntryPoint();
try {
fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test"));
assertThat(resp.getStatus()).withFailMessage("Incorrect status")
.isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
catch (IOException ex) {
fail("Unexpected exception thrown: " + ex);
}
fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test"));
assertThat(resp.getStatus()).withFailMessage("Incorrect status").isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
}

View File

@@ -35,7 +35,7 @@ import org.springframework.security.core.authority.mapping.SimpleMappableAttribu
import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author TSARDD
@@ -45,15 +45,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
@Test
public final void testAfterPropertiesSetException() {
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
try {
t.afterPropertiesSet();
fail("AfterPropertiesSet didn't throw expected exception");
}
catch (IllegalArgumentException expected) {
}
catch (Exception unexpected) {
fail("AfterPropertiesSet throws unexpected exception");
}
assertThatIllegalArgumentException().isThrownBy(t::afterPropertiesSet);
}
@Test
@@ -139,12 +131,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles));
result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper());
try {
result.afterPropertiesSet();
}
catch (Exception expected) {
fail("AfterPropertiesSet throws unexpected exception");
}
result.afterPropertiesSet();
return result;
}

View File

@@ -29,7 +29,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -86,12 +86,8 @@ public class CompositeSessionAuthenticationStrategyTests {
.onAuthentication(this.authentication, this.request, this.response);
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
Arrays.asList(this.strategy1, this.strategy2));
try {
strategy.onAuthentication(this.authentication, this.request, this.response);
fail("Expected Exception");
}
catch (SessionAuthenticationException success) {
}
assertThatExceptionOfType(SessionAuthenticationException.class)
.isThrownBy(() -> strategy.onAuthentication(this.authentication, this.request, this.response));
verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response);
verify(this.strategy2, times(0)).onAuthentication(this.authentication, this.request, this.response);
}

View File

@@ -24,7 +24,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.DisabledException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link BasicAuthenticationEntryPoint}.
@@ -36,13 +36,8 @@ public class BasicAuthenticationEntryPointTests {
@Test
public void testDetectsMissingRealmName() {
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("realmName must be specified");
}
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
.withMessage("realmName must be specified");
}
@Test

View File

@@ -23,7 +23,7 @@ import org.junit.Test;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link org.springframework.security.util.StringSplitUtils}.
@@ -90,36 +90,12 @@ public class DigestAuthUtilsTests {
@Test
public void testSplitRejectsNullsAndIncorrectLengthStrings() {
try {
DigestAuthUtils.split(null, "="); // null
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("", "="); // empty string
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("sdch=dfgf", null); // null
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("fvfv=dcdc", ""); // empty string
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split(null, "="));
assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("", "="));
assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("sdch=dfgf", null));
assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("fvfv=dcdc", ""));
assertThatIllegalArgumentException()
.isThrownBy(() -> DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER"));
}
@Test

View File

@@ -28,7 +28,7 @@ import org.springframework.security.authentication.DisabledException;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link DigestAuthenticationEntryPoint}.
@@ -53,13 +53,7 @@ public class DigestAuthenticationEntryPointTests {
public void testDetectsMissingKey() throws Exception {
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setRealmName("realm");
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("key must be specified");
}
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet).withMessage("key must be specified");
}
@Test
@@ -67,13 +61,8 @@ public class DigestAuthenticationEntryPointTests {
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setKey("dcdc");
ep.setNonceValiditySeconds(12);
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("realmName must be specified");
}
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
.withMessage("realmName must be specified");
}
@Test

View File

@@ -33,7 +33,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
@@ -69,12 +69,7 @@ public class SecurityContextPersistenceFilterTests {
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
SecurityContextHolder.getContext().setAuthentication(this.testToken);
willThrow(new IOException()).given(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
try {
filter.doFilter(request, response, chain);
fail("IOException should have been thrown");
}
catch (IOException expected) {
}
assertThatIOException().isThrownBy(() -> filter.doFilter(request, response, chain));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}

View File

@@ -20,7 +20,7 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Luke Taylor
@@ -33,23 +33,14 @@ public class DefaultHttpFirewallTests {
@Test
public void unnormalizedPathsAreRejected() {
DefaultHttpFirewall fw = new DefaultHttpFirewall();
MockHttpServletRequest request;
for (String path : this.unnormalizedPaths) {
request = new MockHttpServletRequest();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath(path);
try {
fw.getFirewalledRequest(request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> fw.getFirewalledRequest(request));
request.setPathInfo(path);
try {
fw.getFirewalledRequest(request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> fw.getFirewalledRequest(request));
}
}

View File

@@ -19,10 +19,9 @@ package org.springframework.security.web.firewall;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
public class DefaultRequestRejectedHandlerTests {
@@ -31,14 +30,9 @@ public class DefaultRequestRejectedHandlerTests {
public void defaultRequestRejectedHandlerRethrowsTheException() throws Exception {
RequestRejectedException requestRejectedException = new RequestRejectedException("rejected");
DefaultRequestRejectedHandler sut = new DefaultRequestRejectedHandler();
try {
sut.handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException);
}
catch (RequestRejectedException exception) {
Assert.assertThat(exception.getMessage(), CoreMatchers.is("rejected"));
return;
}
Assert.fail("Exception was not rethrown");
assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> sut
.handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException))
.withMessage("rejected");
}
}

View File

@@ -24,7 +24,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -166,12 +166,7 @@ public class FirewalledResponseTests {
}
private void validateLineEnding(String name, String value) {
try {
this.fwResponse.validateCrlf(name, value);
fail("IllegalArgumentException should have thrown");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.validateCrlf(name, value));
}
}

View File

@@ -27,7 +27,6 @@ import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
/**
* @author Rob Winch
@@ -94,12 +93,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", "");
this.request.setRequestURI(path);
try {
this.firewall.getFirewalledRequest(this.request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}
@@ -108,12 +103,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", "");
this.request.setContextPath(path);
try {
this.firewall.getFirewalledRequest(this.request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}
@@ -122,12 +113,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", "");
this.request.setServletPath(path);
try {
this.firewall.getFirewalledRequest(this.request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}
@@ -136,12 +123,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", "");
this.request.setPathInfo(path);
try {
this.firewall.getFirewalledRequest(this.request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}

View File

@@ -51,7 +51,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -179,15 +179,11 @@ public class SecurityContextHolderAwareRequestFilterTests {
given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.willReturn(new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(expectedAuth);
try {
wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials()));
fail("Expected Exception");
}
catch (ServletException success) {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth);
verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler);
verify(this.request, times(0)).login(anyString(), anyString());
}
assertThatExceptionOfType(ServletException.class).isThrownBy(
() -> wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials())));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth);
verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler);
verify(this.request, times(0)).login(anyString(), anyString());
}
@Test
@@ -195,13 +191,8 @@ public class SecurityContextHolderAwareRequestFilterTests {
AuthenticationException authException = new BadCredentialsException("Invalid");
given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.willThrow(authException);
try {
wrappedRequest().login("invalid", "credentials");
fail("Expected Exception");
}
catch (ServletException success) {
assertThat(success.getCause()).isEqualTo(authException);
}
assertThatExceptionOfType(ServletException.class)
.isThrownBy(() -> wrappedRequest().login("invalid", "credentials")).withCause(authException);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler);
verify(this.request, times(0)).login(anyString(), anyString());
@@ -226,13 +217,8 @@ public class SecurityContextHolderAwareRequestFilterTests {
String password = "password";
ServletException authException = new ServletException("Failed Login");
willThrow(authException).given(this.request).login(username, password);
try {
wrappedRequest().login(username, password);
fail("Expected Exception");
}
catch (ServletException success) {
assertThat(success).isEqualTo(authException);
}
assertThatExceptionOfType(ServletException.class).isThrownBy(() -> wrappedRequest().login(username, password))
.isEqualTo(authException);
verifyZeroInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler);
}

View File

@@ -22,7 +22,7 @@ import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Test cases for {@link ThrowableAnalyzer}.
@@ -78,22 +78,15 @@ public class ThrowableAnalyzerTests {
@Test
public void testRegisterExtractorWithInvalidExtractor() {
try {
new ThrowableAnalyzer() {
/**
* @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap()
*/
@Override
protected void initExtractorMap() {
// null is no valid extractor
super.registerExtractor(Exception.class, null);
}
};
fail("IllegalArgumentExpected");
}
catch (IllegalArgumentException ex) {
// ok
}
assertThatIllegalArgumentException().isThrownBy(() -> new ThrowableAnalyzer() {
@Override
protected void initExtractorMap() {
// null is no valid extractor
super.registerExtractor(Exception.class, null);
}
});
}
@Test
@@ -199,25 +192,15 @@ public class ThrowableAnalyzerTests {
@Test
public void testVerifyThrowableHierarchyWithNull() {
try {
ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class);
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException ex) {
// ok
}
assertThatIllegalArgumentException()
.isThrownBy(() -> ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class));
}
@Test
public void testVerifyThrowableHierarchyWithNonmatchingType() {
Throwable throwable = new IllegalStateException("Test");
try {
ThrowableAnalyzer.verifyThrowableHierarchy(throwable, InvocationTargetException.class);
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException ex) {
// ok
}
assertThatIllegalArgumentException().isThrownBy(
() -> ThrowableAnalyzer.verifyThrowableHierarchy(throwable, InvocationTargetException.class));
}
/**