Skip to content

Commit

Permalink
Replace ExpectedException @rules with AssertJ
Browse files Browse the repository at this point in the history
Replace JUnit ExpectedException @rules with AssertJ calls.
  • Loading branch information
philwebb authored and jzheaux committed Sep 22, 2020
1 parent 910b819 commit 20baa7d
Show file tree
Hide file tree
Showing 24 changed files with 384 additions and 544 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@
package org.springframework.security.config;

import org.apache.commons.logging.Log;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
Expand Down Expand Up @@ -48,9 +46,6 @@
@PowerMockIgnore({ "org.w3c.dom.*", "org.xml.sax.*", "org.apache.xerces.*", "javax.xml.parsers.*" })
public class SecurityNamespaceHandlerTests {

@Rule
public ExpectedException thrown = ExpectedException.none();

// @formatter:off
private static final String XML_AUTHENTICATION_MANAGER = "<authentication-manager>"
+ " <authentication-provider>"
Expand Down Expand Up @@ -103,12 +98,12 @@ public void initDoesNotLogErrorWhenFilterChainProxyFailsToLoad() throws Exceptio
@Test
public void filterNoClassDefFoundError() throws Exception {
String className = "javax.servlet.Filter";
this.thrown.expect(BeanDefinitionParsingException.class);
this.thrown.expectMessage("NoClassDefFoundError: " + className);
PowerMockito.spy(ClassUtils.class);
PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName",
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
.withMessageContaining("NoClassDefFoundError: " + className);
}

@Test
Expand All @@ -124,12 +119,12 @@ public void filterNoClassDefFoundErrorNoHttpBlock() throws Exception {
@Test
public void filterChainProxyClassNotFoundException() throws Exception {
String className = FILTER_CHAIN_PROXY_CLASSNAME;
this.thrown.expect(BeanDefinitionParsingException.class);
this.thrown.expectMessage("ClassNotFoundException: " + className);
PowerMockito.spy(ClassUtils.class);
PowerMockito.doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
.withMessageContaining("ClassNotFoundException: " + className);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import org.aopalliance.intercept.MethodInterceptor;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;

import org.springframework.beans.BeansException;
Expand Down Expand Up @@ -80,9 +79,6 @@ public class GlobalMethodSecurityConfigurationTests {
@Rule
public final SpringTestRule spring = new SpringTestRule();

@Rule
public ExpectedException thrown = ExpectedException.none();

@Autowired(required = false)
private MethodSecurityService service;

Expand All @@ -98,8 +94,8 @@ public void setMethodInterceptor(MethodSecurityInterceptor interceptor) {

@Test
public void configureWhenGlobalMethodSecurityIsMissingMetadataSourceThenException() {
this.thrown.expect(UnsatisfiedDependencyException.class);
this.spring.register(IllegalStateGlobalMethodSecurityConfig.class).autowire();
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
.isThrownBy(() -> this.spring.register(IllegalStateGlobalMethodSecurityConfig.class).autowire());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@

package org.springframework.security.crypto.codec;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;

/**
* Test cases for {@link Hex}.
Expand All @@ -29,9 +28,6 @@
*/
public class HexTests {

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public void encode() {
assertThat(Hex.encode(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D' }))
Expand All @@ -55,30 +51,26 @@ public void decodeEmptyString() {

@Test
public void decodeNotEven() {
this.expectedException.expect(IllegalArgumentException.class);
this.expectedException.expectMessage("Hex-encoded string must have an even number of characters");
Hex.decode("414243444");
assertThatIllegalArgumentException().isThrownBy(() -> Hex.decode("414243444"))
.withMessage("Hex-encoded string must have an even number of characters");
}

@Test
public void decodeExistNonHexCharAtFirst() {
this.expectedException.expect(IllegalArgumentException.class);
this.expectedException.expectMessage("Detected a Non-hex character at 1 or 2 position");
Hex.decode("G0");
assertThatIllegalArgumentException().isThrownBy(() -> Hex.decode("G0"))
.withMessage("Detected a Non-hex character at 1 or 2 position");
}

@Test
public void decodeExistNonHexCharAtSecond() {
this.expectedException.expect(IllegalArgumentException.class);
this.expectedException.expectMessage("Detected a Non-hex character at 3 or 4 position");
Hex.decode("410G");
assertThatIllegalArgumentException().isThrownBy(() -> Hex.decode("410G"))
.withMessage("Detected a Non-hex character at 3 or 4 position");
}

@Test
public void decodeExistNonHexCharAtBoth() {
this.expectedException.expect(IllegalArgumentException.class);
this.expectedException.expectMessage("Detected a Non-hex character at 5 or 6 position");
Hex.decode("4142GG");
assertThatIllegalArgumentException().isThrownBy(() -> Hex.decode("4142GG"))
.withMessage("Detected a Non-hex character at 5 or 6 position");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,18 @@
package org.springframework.security;

import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

/**
* @author Eddú Meléndez
*/
public class LdapServerBeanDefinitionParserTests {

@Rule
public ExpectedException thrown = ExpectedException.none();

private ClassPathXmlApplicationContext context;

@After
Expand All @@ -44,10 +41,9 @@ public void closeAppContext() {

@Test
public void apacheDirectoryServerIsStartedByDefault() {
this.thrown.expect(BeanDefinitionStoreException.class);
this.thrown.expectMessage("Embedded LDAP server is not provided");

this.context = new ClassPathXmlApplicationContext("applicationContext-security.xml");
assertThatExceptionOfType(BeanDefinitionStoreException.class)
.isThrownBy(() -> this.context = new ClassPathXmlApplicationContext("applicationContext-security.xml"))
.withMessageContaining("Embedded LDAP server is not provided");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,8 @@
import javax.naming.directory.SearchResult;

import org.apache.directory.shared.ldap.util.EmptyEnumeration;
import org.hamcrest.BaseMatcher;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;

import org.springframework.dao.IncorrectResultSizeDataAccessException;
Expand Down Expand Up @@ -71,9 +65,6 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {

public static final String NON_EXISTING_LDAP_PROVIDER = "ldap://192.168.1.201/";

@Rule
public ExpectedException thrown = ExpectedException.none();

ActiveDirectoryLdapAuthenticationProvider provider;

UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
Expand Down Expand Up @@ -245,29 +236,10 @@ public void passwordNeedsResetIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(
new AuthenticationException(msg + dataCode + ", xxxx]"));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.thrown.expect(BadCredentialsException.class);
this.thrown.expect(new BaseMatcher<BadCredentialsException>() {
private Matcher<Object> causeInstance = CoreMatchers
.instanceOf(ActiveDirectoryAuthenticationException.class);

private Matcher<String> causeDataCode = CoreMatchers.equalTo(dataCode);

@Override
public boolean matches(Object that) {
Throwable t = (Throwable) that;
ActiveDirectoryAuthenticationException cause = (ActiveDirectoryAuthenticationException) t.getCause();
return this.causeInstance.matches(cause) && this.causeDataCode.matches(cause.getDataCode());
}

@Override
public void describeTo(Description desc) {
desc.appendText("getCause() ");
this.causeInstance.describeTo(desc);
desc.appendText("getCause().getDataCode() ");
this.causeDataCode.describeTo(desc);
}
});
this.provider.authenticate(this.joe);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe))
.withCauseInstanceOf(ActiveDirectoryAuthenticationException.class)
.satisfies((ex) -> assertThat(((ActiveDirectoryAuthenticationException) ex.getCause()).getDataCode())
.isEqualTo(dataCode));
}

@Test(expected = CredentialsExpiredException.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@
import java.util.Set;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;

Expand All @@ -52,7 +50,8 @@
import org.springframework.security.oauth2.core.user.OAuth2User;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.BDDMockito.given;
Expand All @@ -79,9 +78,6 @@ public class OAuth2LoginAuthenticationProviderTests {

private OAuth2LoginAuthenticationProvider authenticationProvider;

@Rule
public ExpectedException exception = ExpectedException.none();

@Before
@SuppressWarnings("unchecked")
public void setUp() {
Expand All @@ -98,20 +94,19 @@ public void setUp() {

@Test
public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
new OAuth2LoginAuthenticationProvider(null, this.userService);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationProvider(null, this.userService));
}

@Test
public void constructorWhenUserServiceIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
new OAuth2LoginAuthenticationProvider(this.accessTokenResponseClient, null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationProvider(this.accessTokenResponseClient, null));
}

@Test
public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.authenticationProvider.setAuthoritiesMapper(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.authenticationProvider.setAuthoritiesMapper(null));
}

@Test
Expand All @@ -132,26 +127,26 @@ public void authenticateWhenAuthorizationRequestContainsOpenidScopeThenReturnNul

@Test
public void authenticateWhenAuthorizationErrorResponseThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(OAuth2ErrorCodes.INVALID_REQUEST));
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error()
.errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
}

@Test
public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("invalid_state_parameter"));
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().state("67890")
.build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining("invalid_state_parameter");
}

@Test
Expand Down
Loading

0 comments on commit 20baa7d

Please sign in to comment.