You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@shiro.apache.org by bm...@apache.org on 2023/06/22 17:12:07 UTC
[shiro] 01/01: [#947] rewrite java tests to Junit-Jupiter
This is an automated email from the ASF dual-hosted git repository.
bmarwell pushed a commit to branch #947_junit-jupiter
in repository https://gitbox.apache.org/repos/asf/shiro.git
commit aeef99d3cf72ec1f7a65d0bd68d0837d0041995d
Author: Benjamin Marwell <bm...@apache.org>
AuthorDate: Thu Jun 22 19:11:57 2023 +0200
[#947] rewrite java tests to Junit-Jupiter
---
.../test/java/org/apache/shiro/ExceptionTest.java | 13 +-
.../apache/shiro/aop/AnnotationResolverTest.java | 35 ++--
.../shiro/authc/AbstractAuthenticatorTest.java | 59 +++----
.../shiro/authc/SimpleAuthenticationInfoTest.java | 14 +-
.../AbstractHashedCredentialsMatcherTest.java | 10 +-
.../credential/AllowAllCredentialsMatcherTest.java | 7 +-
.../credential/HashedCredentialsMatcherTest.java | 10 +-
.../shiro/authc/pam/AllSuccessfulStrategyTest.java | 46 +++---
.../authc/pam/FirstSuccessfulStrategyTest.java | 35 ++--
.../shiro/authz/ModularRealmAuthorizerTest.java | 10 +-
.../authz/aop/DenyAllAnnotationHandlerTest.java | 63 +++----
.../authz/aop/PermitAllAnnotationHandlerTest.java | 4 +-
.../aop/RolesAllowedAnnotationHandlerTest.java | 116 +++++++------
.../shiro/authz/permission/AllPermissionTest.java | 9 +-
.../authz/permission/DomainPermissionTest.java | 16 +-
.../permission/WildcardPermissionResolverTest.java | 36 ++--
.../authz/permission/WildcardPermissionTest.java | 50 +++---
.../apache/shiro/jndi/JndiObjectFactoryTest.java | 59 ++++---
.../shiro/mgt/AbstractRememberMeManagerTest.java | 6 +-
.../shiro/mgt/AbstractSecurityManagerTest.java | 4 +-
.../shiro/mgt/DefaultSecurityManagerTest.java | 20 +--
.../mgt/VMSingletonDefaultSecurityManagerTest.java | 14 +-
.../apache/shiro/realm/AuthorizingRealmTest.java | 28 ++--
.../activedirectory/ActiveDirectoryRealmTest.java | 20 +--
.../org/apache/shiro/realm/jdbc/JDBCRealmTest.java | 122 ++++++++------
.../shiro/realm/ldap/DefaultLdapRealmTest.java | 170 ++++++++++---------
.../realm/ldap/JndiLdapContextFactoryTest.java | 184 +++++++++++----------
.../apache/shiro/realm/ldap/JndiLdapRealmTest.java | 5 +-
.../org/apache/shiro/realm/text/IniRealmTest.java | 22 +--
.../realm/text/TextConfigurationRealmTest.java | 44 ++---
.../mgt/AbstractValidatingSessionManagerTest.java | 42 ++---
.../session/mgt/DefaultSessionManagerTest.java | 28 ++--
.../shiro/session/mgt/DelegatingSessionTest.java | 16 +-
...cutorServiceSessionValidationSchedulerTest.java | 38 ++---
.../shiro/session/mgt/SimpleSessionTest.java | 32 ++--
.../shiro/subject/DelegatingSubjectTest.java | 26 +--
.../subject/SimplePrincipalCollectionTest.java | 4 +-
.../org/apache/shiro/test/AbstractShiroTest.java | 8 +-
.../shiro/test/ExampleShiroIntegrationTest.java | 22 +--
.../apache/shiro/test/ExampleShiroUnitTest.java | 8 +-
.../org/apache/shiro/util/AntPathMatcherTests.java | 26 ++-
.../apache/shiro/util/RegExPatternMatcherTest.java | 19 ++-
.../org/apache/shiro/util/StringUtilsTest.java | 20 +--
.../samples/guice/ContainerIntegrationIT.java | 10 +-
.../samples/guice/ContainerIntegrationIT.java | 10 +-
integration-tests/support/pom.xml | 5 +-
.../shiro/testing/web/AbstractContainerIT.java | 18 +-
pom.xml | 10 +-
.../aspectj/bank/SecureBankServiceTest.java | 109 ++++++------
.../samples/guice/ContainerIntegrationIT.java | 10 +-
.../apache/shiro/test/ContainerIntegrationIT.java | 8 +-
.../shiro/samples/ContainerIntegrationIT.java | 8 +-
.../web/jakarta/JakartaAbstractContainerIT.java | 4 +-
.../shiro/test/WebAppContainerIntegrationIT.java | 8 +-
.../org/apache/shiro/aspectj/DummyServiceTest.java | 108 +++++++-----
.../shiro/cache/ehcache/EhCacheManagerTest.java | 24 +--
.../apache/shiro/guice/BeanTypeListenerTest.java | 35 ++--
.../guice/DestroyableInjectionListenerTest.java | 14 +-
.../apache/shiro/guice/GuiceEnvironmentTest.java | 24 +--
.../guice/InitializableInjectionListenerTest.java | 14 +-
.../shiro/guice/LifecycleTypeListenerTest.java | 24 +--
.../org/apache/shiro/guice/ShiroMatchersTest.java | 20 +--
.../org/apache/shiro/guice/ShiroModuleTest.java | 88 +++++-----
.../apache/shiro/guice/ShiroSessionScopeTest.java | 43 ++---
.../AopAllianceMethodInterceptorAdapterTest.java | 22 +--
.../AopAllianceMethodInvocationAdapterTest.java | 40 ++---
.../apache/shiro/guice/aop/ShiroAopModuleTest.java | 28 ++--
.../guice/web/AbstractInjectionProviderTest.java | 40 ++---
.../apache/shiro/guice/web/DefaultFiltersTest.java | 18 +-
.../guice/web/FilterChainResolverProviderTest.java | 38 ++---
.../apache/shiro/guice/web/FilterConfigTest.java | 26 +--
.../shiro/guice/web/GuiceShiroFilterTest.java | 31 ++--
.../guice/web/PathMatchingFilterProviderTest.java | 14 +-
.../apache/shiro/guice/web/ShiroWebModuleTest.java | 109 ++++++------
.../guice/web/SimpleFilterChainResolverTest.java | 20 +--
.../shiro/guice/web/SimpleFilterChainTest.java | 14 +-
.../shiro/guice/web/WebGuiceEnvironmentTest.java | 28 ++--
.../SecureRemoteInvocationFactoryTest.java | 18 +-
.../AbstractAuthorizationAnnotationTest.java | 138 +++++++++-------
.../AuthorizationAttributeSourceAdvisorTest.java | 32 ++--
.../DapcAuthorizationAnnotationTest.java | 52 +++---
.../spring/web/ShiroFilterFactoryBeanTest.java | 8 +-
.../config/WebIniSecurityManagerFactoryTest.java | 8 +-
.../web/env/EnvironmentLoaderServiceTest.java | 20 +--
.../PathMatchingFilterParameterizedTest.java | 35 ++--
.../shiro/web/filter/PathMatchingFilterTest.java | 34 ++--
.../web/filter/authc/AnonymousFilterTest.java | 7 +-
.../shiro/web/filter/authz/HostFilterTest.java | 9 +-
.../authz/HttpMethodPermissionFilterTest.java | 28 ++--
.../web/filter/authz/IpAddressMatcherTests.java | 28 ++--
.../shiro/web/filter/authz/IpFilterTest.java | 15 +-
.../shiro/web/filter/authz/PortFilterTest.java | 36 ++--
.../shiro/web/filter/authz/SslFilterTest.java | 16 +-
.../mgt/PathMatchingFilterChainResolverTest.java | 45 +++--
.../web/filter/mgt/SimpleNamedFilterListTest.java | 26 +--
.../web/mgt/AbstractWebSecurityManagerTest.java | 4 +-
.../shiro/web/mgt/CookieRememberMeManagerTest.java | 94 +++++------
.../web/mgt/DefaultWebSecurityManagerTest.java | 35 ++--
.../web/mgt/NonIniWebSecurityManagerTest.java | 12 +-
.../web/servlet/OncePerRequestFilterTest.java | 20 +--
.../shiro/web/session/HttpServletSessionTest.java | 10 +-
101 files changed, 1688 insertions(+), 1584 deletions(-)
diff --git a/core/src/test/java/org/apache/shiro/ExceptionTest.java b/core/src/test/java/org/apache/shiro/ExceptionTest.java
index 3832f981d..112f4089c 100644
--- a/core/src/test/java/org/apache/shiro/ExceptionTest.java
+++ b/core/src/test/java/org/apache/shiro/ExceptionTest.java
@@ -18,35 +18,34 @@
*/
package org.apache.shiro;
-import junit.framework.TestCase;
import org.apache.shiro.lang.util.ClassUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
*/
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
-public abstract class ExceptionTest extends TestCase {
+public abstract class ExceptionTest {
protected abstract Class getExceptionClass();
@Test
- public void testNoArgConstructor() {
+ void testNoArgConstructor() {
ClassUtils.newInstance(getExceptionClass());
}
@Test
- public void testMsgConstructor() throws Exception {
+ void testMsgConstructor() throws Exception {
ClassUtils.newInstance(getExceptionClass(), "Msg");
}
@Test
- public void testCauseConstructor() throws Exception {
+ void testCauseConstructor() throws Exception {
ClassUtils.newInstance(getExceptionClass(), new Throwable());
}
@Test
- public void testMsgCauseConstructor() {
+ void testMsgCauseConstructor() {
ClassUtils.newInstance(getExceptionClass(), "Msg", new Throwable());
}
}
diff --git a/core/src/test/java/org/apache/shiro/aop/AnnotationResolverTest.java b/core/src/test/java/org/apache/shiro/aop/AnnotationResolverTest.java
index 1b2916c5e..495d50561 100644
--- a/core/src/test/java/org/apache/shiro/aop/AnnotationResolverTest.java
+++ b/core/src/test/java/org/apache/shiro/aop/AnnotationResolverTest.java
@@ -25,11 +25,12 @@ import static org.easymock.EasyMock.replay;
import java.lang.reflect.Method;
import org.apache.shiro.authz.annotation.RequiresRoles;
-import org.apache.shiro.authz.annotation.RequiresUser;
-import org.junit.Test;
-import static org.junit.Assert.*;
-
-
+import org.apache.shiro.authz.annotation.RequiresUser;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+
public class AnnotationResolverTest {
@SuppressWarnings("unused")
@RequiresRoles("root")
@@ -39,10 +40,10 @@ public class AnnotationResolverTest {
public void operateThat() {}
}
- DefaultAnnotationResolver annotationResolver = new DefaultAnnotationResolver();
-
- @Test
- public void testAnnotationFoundFromClass() throws SecurityException, NoSuchMethodException {
+ DefaultAnnotationResolver annotationResolver = new DefaultAnnotationResolver();
+
+ @Test
+ void testAnnotationFoundFromClass() throws SecurityException, NoSuchMethodException {
MyFixture myFixture = new MyFixture();
MethodInvocation methodInvocation = createMock(MethodInvocation.class);
Method method = MyFixture.class.getDeclaredMethod("operateThis");
@@ -50,19 +51,19 @@ public class AnnotationResolverTest {
expect(methodInvocation.getThis()).andReturn(myFixture);
replay(methodInvocation);
assertNotNull(annotationResolver.getAnnotation(methodInvocation, RequiresRoles.class));
- }
-
- @Test
- public void testAnnotationFoundFromMethod() throws SecurityException, NoSuchMethodException {
+ }
+
+ @Test
+ void testAnnotationFoundFromMethod() throws SecurityException, NoSuchMethodException {
MethodInvocation methodInvocation = createMock(MethodInvocation.class);
Method method = MyFixture.class.getDeclaredMethod("operateThat");
expect(methodInvocation.getMethod()).andReturn(method);
replay(methodInvocation);
assertNotNull(annotationResolver.getAnnotation(methodInvocation, RequiresUser.class));
- }
-
- @Test
- public void testNullMethodInvocation() throws SecurityException, NoSuchMethodException {
+ }
+
+ @Test
+ void testNullMethodInvocation() throws SecurityException, NoSuchMethodException {
MethodInvocation methodInvocation = createMock(MethodInvocation.class);
Method method = MyFixture.class.getDeclaredMethod("operateThis");
expect(methodInvocation.getMethod()).andReturn(method);
diff --git a/core/src/test/java/org/apache/shiro/authc/AbstractAuthenticatorTest.java b/core/src/test/java/org/apache/shiro/authc/AbstractAuthenticatorTest.java
index 6b1b5bfb4..0659ca7be 100644
--- a/core/src/test/java/org/apache/shiro/authc/AbstractAuthenticatorTest.java
+++ b/core/src/test/java/org/apache/shiro/authc/AbstractAuthenticatorTest.java
@@ -20,17 +20,14 @@ package org.apache.shiro.authc;
import org.apache.logging.log4j.core.test.appender.ListAppender;
import org.apache.logging.log4j.core.test.junit.LoggerContextRule;
-import org.junit.Before;
import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -64,13 +61,13 @@ public class AbstractAuthenticatorTest {
return new UsernamePasswordToken("user1", "secret");
}
- @Before
+ @BeforeEach
public void setUp() {
abstractAuthenticator = createAuthcReturnValidAuthcInfo();
}
@Test
- public void newAbstractAuthenticatorSecurityManagerConstructor() {
+ void newAbstractAuthenticatorSecurityManagerConstructor() {
abstractAuthenticator = new AbstractAuthenticator() {
protected AuthenticationInfo doAuthenticate(AuthenticationToken token) throws AuthenticationException {
return info;
@@ -83,19 +80,23 @@ public class AbstractAuthenticatorTest {
* Ensures that the authenticate() method proactively fails if a <tt>null</tt> AuthenticationToken is passed as an
* argument.
*/
- @Test(expected = IllegalArgumentException.class)
- public void authenticateWithNullArgument() {
- abstractAuthenticator.authenticate(null);
+ @Test
+ void authenticateWithNullArgument() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ abstractAuthenticator.authenticate(null);
+ });
}
/**
* Ensures that the authenticate() method throws an AuthenticationException if the subclass returns <tt>null</tt>
* as the return value to the doAuthenticate() method.
*/
- @Test(expected = AuthenticationException.class)
- public void throwAuthenticationExceptionIfDoAuthenticateReturnsNull() {
- abstractAuthenticator = createAuthcReturnNull();
- abstractAuthenticator.authenticate(newToken());
+ @Test
+ void throwAuthenticationExceptionIfDoAuthenticateReturnsNull() {
+ assertThrows(AuthenticationException.class, () -> {
+ abstractAuthenticator = createAuthcReturnNull();
+ abstractAuthenticator.authenticate(newToken());
+ });
}
/**
@@ -104,13 +105,13 @@ public class AbstractAuthenticatorTest {
* AuthenticationInfo object).
*/
@Test
- public void nonNullAuthenticationInfoAfterAuthenticate() {
+ void nonNullAuthenticationInfoAfterAuthenticate() {
AuthenticationInfo authcInfo = abstractAuthenticator.authenticate(newToken());
assertNotNull(authcInfo);
}
@Test
- public void notifySuccessAfterDoAuthenticate() {
+ void notifySuccessAfterDoAuthenticate() {
AuthenticationListener mockListener = createMock(AuthenticationListener.class);
abstractAuthenticator.getAuthenticationListeners().add(mockListener);
AuthenticationToken token = newToken();
@@ -122,7 +123,7 @@ public class AbstractAuthenticatorTest {
}
@Test
- public void notifyFailureAfterDoAuthenticateThrowsAuthenticationException() {
+ void notifyFailureAfterDoAuthenticateThrowsAuthenticationException() {
AuthenticationListener mockListener = createMock(AuthenticationListener.class);
AuthenticationToken token = newToken();
@@ -152,19 +153,21 @@ public class AbstractAuthenticatorTest {
}
}
- @Test(expected = AuthenticationException.class)
- public void notifyFailureAfterDoAuthenticateThrowsNonAuthenticationException() {
- abstractAuthenticator = new AbstractAuthenticator() {
- protected AuthenticationInfo doAuthenticate(AuthenticationToken token) throws AuthenticationException {
- throw new IllegalArgumentException("not an AuthenticationException subclass");
- }
- };
- AuthenticationToken token = newToken();
- abstractAuthenticator.authenticate(token);
+ @Test
+ void notifyFailureAfterDoAuthenticateThrowsNonAuthenticationException() {
+ assertThrows(AuthenticationException.class, () -> {
+ abstractAuthenticator = new AbstractAuthenticator() {
+ protected AuthenticationInfo doAuthenticate(AuthenticationToken token) throws AuthenticationException {
+ throw new IllegalArgumentException("not an AuthenticationException subclass");
+ }
+ };
+ AuthenticationToken token = newToken();
+ abstractAuthenticator.authenticate(token);
+ });
}
@Test
- public void logExceptionAfterDoAuthenticateThrowsNonAuthenticationException() {
+ void logExceptionAfterDoAuthenticateThrowsNonAuthenticationException() {
// NOTE: log4j is a test dependency
final String expectedExceptionMessage = "exception thrown for test logExceptionAfterDoAuthenticateThrowsNonAuthenticationException";
diff --git a/core/src/test/java/org/apache/shiro/authc/SimpleAuthenticationInfoTest.java b/core/src/test/java/org/apache/shiro/authc/SimpleAuthenticationInfoTest.java
index 4790b3239..22c29b402 100644
--- a/core/src/test/java/org/apache/shiro/authc/SimpleAuthenticationInfoTest.java
+++ b/core/src/test/java/org/apache/shiro/authc/SimpleAuthenticationInfoTest.java
@@ -18,8 +18,6 @@
*/
package org.apache.shiro.authc;
-import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
@@ -28,7 +26,9 @@ import java.util.List;
import java.util.Set;
import org.apache.shiro.subject.PrincipalCollection;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -37,7 +37,7 @@ import org.junit.Test;
public class SimpleAuthenticationInfoTest {
@Test
- public void testMergeWithEmptyInstances() {
+ void testMergeWithEmptyInstances() {
SimpleAuthenticationInfo aggregate = new SimpleAuthenticationInfo();
SimpleAuthenticationInfo local = new SimpleAuthenticationInfo();
aggregate.merge(local);
@@ -47,15 +47,15 @@ public class SimpleAuthenticationInfoTest {
* Verifies fix for JSEC-122
*/
@Test
- public void testMergeWithAggregateNullCredentials() {
+ void testMergeWithAggregateNullCredentials() {
SimpleAuthenticationInfo aggregate = new SimpleAuthenticationInfo();
SimpleAuthenticationInfo local = new SimpleAuthenticationInfo("username", "password", "testRealm");
aggregate.merge(local);
}
-
+
@SuppressWarnings("serial")
@Test
- public void testMergeWithImmutablePrincipalCollection() {
+ void testMergeWithImmutablePrincipalCollection() {
SimpleAuthenticationInfo aggregate = new SimpleAuthenticationInfo();
// Make a quick test fixture that does *not* implement MutablePrincipalCollection
PrincipalCollection principalCollection = new PrincipalCollection() {
diff --git a/core/src/test/java/org/apache/shiro/authc/credential/AbstractHashedCredentialsMatcherTest.java b/core/src/test/java/org/apache/shiro/authc/credential/AbstractHashedCredentialsMatcherTest.java
index dba089c6b..38f559605 100644
--- a/core/src/test/java/org/apache/shiro/authc/credential/AbstractHashedCredentialsMatcherTest.java
+++ b/core/src/test/java/org/apache/shiro/authc/credential/AbstractHashedCredentialsMatcherTest.java
@@ -18,27 +18,27 @@
*/
package org.apache.shiro.authc.credential;
-import junit.framework.TestCase;
-import org.junit.Test;
-
import org.apache.shiro.authc.AuthenticationInfo;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.AbstractHash;
import org.apache.shiro.lang.util.ClassUtils;
+import org.junit.jupiter.api.Test;
/**
* @since Jun 10, 2008 4:47:09 PM
*/
-public abstract class AbstractHashedCredentialsMatcherTest extends TestCase {
+public abstract class AbstractHashedCredentialsMatcherTest {
public abstract Class<? extends HashedCredentialsMatcher> getMatcherClass();
public abstract AbstractHash hash(Object credentials);
@Test
- public void testBasic() {
+ void testBasic() {
CredentialsMatcher matcher = (CredentialsMatcher) ClassUtils.newInstance(getMatcherClass());
byte[] hashed = hash("password").getBytes();
AuthenticationInfo account = new SimpleAuthenticationInfo("username", hashed, "realmName");
diff --git a/core/src/test/java/org/apache/shiro/authc/credential/AllowAllCredentialsMatcherTest.java b/core/src/test/java/org/apache/shiro/authc/credential/AllowAllCredentialsMatcherTest.java
index 74aa56f24..de8f966af 100644
--- a/core/src/test/java/org/apache/shiro/authc/credential/AllowAllCredentialsMatcherTest.java
+++ b/core/src/test/java/org/apache/shiro/authc/credential/AllowAllCredentialsMatcherTest.java
@@ -18,8 +18,9 @@
*/
package org.apache.shiro.authc.credential;
-import static org.junit.Assert.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -28,7 +29,7 @@ import org.junit.Test;
public class AllowAllCredentialsMatcherTest {
@Test
- public void testBasic() {
+ void testBasic() {
assertTrue(new AllowAllCredentialsMatcher().doCredentialsMatch(null, null));
}
diff --git a/core/src/test/java/org/apache/shiro/authc/credential/HashedCredentialsMatcherTest.java b/core/src/test/java/org/apache/shiro/authc/credential/HashedCredentialsMatcherTest.java
index 100a9c889..73d270d9e 100644
--- a/core/src/test/java/org/apache/shiro/authc/credential/HashedCredentialsMatcherTest.java
+++ b/core/src/test/java/org/apache/shiro/authc/credential/HashedCredentialsMatcherTest.java
@@ -27,9 +27,9 @@ import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.lang.util.ByteSource;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests for the {@link org.apache.shiro.authc.credential.HashedCredentialsMatcher} class.
@@ -41,7 +41,7 @@ public class HashedCredentialsMatcherTest {
* should be. See <a href="https://issues.apache.org/jira/browse/SHIRO-186">SHIRO-186</a>
*/
@Test
- public void testSaltedAuthenticationInfo() {
+ void testSaltedAuthenticationInfo() {
//use SHA-1 hashing in this test:
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Sha512Hash.ALGORITHM_NAME);
@@ -62,7 +62,7 @@ public class HashedCredentialsMatcherTest {
* <a href="https://issues.apache.org/jira/browse/SHIRO-186">SHIRO-186</a> edits.
*/
@Test
- public void testBackwardsCompatibleUnsaltedAuthenticationInfo() {
+ void testBackwardsCompatibleUnsaltedAuthenticationInfo() {
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Sha512Hash.ALGORITHM_NAME);
//simulate an account with SHA-1 hashed password (no salt)
@@ -95,7 +95,7 @@ public class HashedCredentialsMatcherTest {
* <a href="https://issues.apache.org/jira/browse/SHIRO-186">SHIRO-186</a> edits.
*/
@Test
- public void testBackwardsCompatibleSaltedAuthenticationInfo() {
+ void testBackwardsCompatibleSaltedAuthenticationInfo() {
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Sha512Hash.ALGORITHM_NAME);
//enable this for Shiro 1.0 backwards compatibility:
matcher.setHashSalted(true);
diff --git a/core/src/test/java/org/apache/shiro/authc/pam/AllSuccessfulStrategyTest.java b/core/src/test/java/org/apache/shiro/authc/pam/AllSuccessfulStrategyTest.java
index 6417b5ac4..7e9495685 100644
--- a/core/src/test/java/org/apache/shiro/authc/pam/AllSuccessfulStrategyTest.java
+++ b/core/src/test/java/org/apache/shiro/authc/pam/AllSuccessfulStrategyTest.java
@@ -18,11 +18,13 @@
*/
package org.apache.shiro.authc.pam;
-import static org.junit.Assert.assertNotNull;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.shiro.authc.AuthenticationException;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
@@ -36,41 +38,43 @@ public class AllSuccessfulStrategyTest {
private AllSuccessfulStrategy strategy;
- @Before
+ @BeforeEach
public void setUp() {
strategy = new AllSuccessfulStrategy();
}
@Test
- public void beforeAllAttempts() {
+ void beforeAllAttempts() {
AuthenticationInfo info = strategy.beforeAllAttempts(null, null);
assertNotNull(info);
}
@Test
- public void beforeAttemptSupportingToken() {
+ void beforeAttemptSupportingToken() {
new SimpleAccountRealm();
}
- @Test(expected = UnsupportedTokenException.class)
- public void beforeAttemptRealmDoesntSupportToken() {
- Realm notSupportingRealm = new AuthorizingRealm() {
+ @Test
+ void beforeAttemptRealmDoesntSupportToken() {
+ assertThrows(UnsupportedTokenException.class, () -> {
+ Realm notSupportingRealm = new AuthorizingRealm() {
- public boolean supports(AuthenticationToken token) {
- return false;
- }
+ public boolean supports(AuthenticationToken token) {
+ return false;
+ }
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- return null;
- }
+ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
+ return null;
+ }
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
- return null;
- }
+ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
+ return null;
+ }
- };
+ };
- strategy.beforeAttempt(notSupportingRealm, null, null);
+ strategy.beforeAttempt(notSupportingRealm, null, null);
+ });
}
diff --git a/core/src/test/java/org/apache/shiro/authc/pam/FirstSuccessfulStrategyTest.java b/core/src/test/java/org/apache/shiro/authc/pam/FirstSuccessfulStrategyTest.java
index 5f0656602..aac94febb 100644
--- a/core/src/test/java/org/apache/shiro/authc/pam/FirstSuccessfulStrategyTest.java
+++ b/core/src/test/java/org/apache/shiro/authc/pam/FirstSuccessfulStrategyTest.java
@@ -23,30 +23,31 @@ import org.apache.shiro.authc.MergableAuthenticationInfo;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import org.junit.Before;
-import org.junit.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class FirstSuccessfulStrategyTest {
private FirstSuccessfulStrategy strategy;
- @Before
+ @BeforeEach
public void setUp() {
strategy = new FirstSuccessfulStrategy();
strategy.setStopAfterFirstSuccess(true);
}
@Test
- public void beforeAllAttempts() {
+ void beforeAllAttempts() {
AuthenticationInfo authenticationInfo = strategy.beforeAllAttempts(null, null);
assertNull(authenticationInfo);
}
@Test
- public void testMergeWithValidAggregateInfo() {
+ void testMergeWithValidAggregateInfo() {
AuthenticationInfo aggregate = new MergableAuthenticationInfo() {
@Override
public void merge(AuthenticationInfo info) {
@@ -68,7 +69,7 @@ public class FirstSuccessfulStrategyTest {
}
@Test
- public void testMergeWithInvalidAggregateInfo() {
+ void testMergeWithInvalidAggregateInfo() {
AuthenticationInfo aggregate = new MergableAuthenticationInfo() {
@Override
public void merge(AuthenticationInfo info) {
@@ -93,27 +94,29 @@ public class FirstSuccessfulStrategyTest {
assertNull(info);
}
- @Test
- public void testBeforeAttemptNull() {
+ @Test
+ void testBeforeAttemptNull() {
assertNull(strategy.beforeAttempt(null, null, null));
}
@Test
- public void testBeforeAttemptEmptyPrincipal() {
+ void testBeforeAttemptEmptyPrincipal() {
AuthenticationInfo aggregate = new SimpleAuthenticationInfo();
assertEquals(strategy.beforeAttempt(null, null, aggregate), aggregate);
}
@Test
- public void testBeforeAttemptEmptyList() {
+ void testBeforeAttemptEmptyList() {
SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
AuthenticationInfo aggregate = new SimpleAuthenticationInfo(principalCollection, null);
assertEquals(strategy.beforeAttempt(null, null, aggregate), aggregate);
}
- @Test (expected=ShortCircuitIterationException.class)
- public void testBeforeAttemptStopAfterFirstSuccess() {
- AuthenticationInfo aggregate = new SimpleAuthenticationInfo("principal", null, "a-realm-name");
- strategy.beforeAttempt(null, null, aggregate);
+ @Test
+ void testBeforeAttemptStopAfterFirstSuccess() {
+ assertThrows(ShortCircuitIterationException.class, () -> {
+ AuthenticationInfo aggregate = new SimpleAuthenticationInfo("principal", null, "a-realm-name");
+ strategy.beforeAttempt(null, null, aggregate);
+ });
}
}
diff --git a/core/src/test/java/org/apache/shiro/authz/ModularRealmAuthorizerTest.java b/core/src/test/java/org/apache/shiro/authz/ModularRealmAuthorizerTest.java
index 78c0f10a5..15e3ee23c 100644
--- a/core/src/test/java/org/apache/shiro/authz/ModularRealmAuthorizerTest.java
+++ b/core/src/test/java/org/apache/shiro/authz/ModularRealmAuthorizerTest.java
@@ -18,8 +18,8 @@
*/
package org.apache.shiro.authz;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
@@ -31,13 +31,13 @@ import org.apache.shiro.authz.permission.RolePermissionResolver;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class ModularRealmAuthorizerTest
{
-
+
@Test
- public void testSettingOfRolePermissionResolver()
+ void testSettingOfRolePermissionResolver()
{
Collection<Realm> realms = new ArrayList<Realm>();
diff --git a/core/src/test/java/org/apache/shiro/authz/aop/DenyAllAnnotationHandlerTest.java b/core/src/test/java/org/apache/shiro/authz/aop/DenyAllAnnotationHandlerTest.java
index 96f843030..1b895090b 100644
--- a/core/src/test/java/org/apache/shiro/authz/aop/DenyAllAnnotationHandlerTest.java
+++ b/core/src/test/java/org/apache/shiro/authz/aop/DenyAllAnnotationHandlerTest.java
@@ -21,7 +21,7 @@ package org.apache.shiro.authz.aop;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.test.SecurityManagerTestSupport;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.annotation.security.DenyAll;
import java.lang.annotation.Annotation;
@@ -29,6 +29,7 @@ import java.lang.annotation.Annotation;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Test cases for the {@link DenyAllAnnotationHandler} class.
@@ -36,38 +37,42 @@ import static org.easymock.EasyMock.replay;
public class DenyAllAnnotationHandlerTest extends SecurityManagerTestSupport {
private Subject subject;
- @Test(expected = UnauthenticatedException.class)
- public void testGuestSingleRoleAssertion() throws Throwable {
- DenyAllAnnotationHandler handler = new DenyAllAnnotationHandler();
+ @Test
+ void testGuestSingleRoleAssertion() throws Throwable {
+ assertThrows(UnauthenticatedException.class, () -> {
+ DenyAllAnnotationHandler handler = new DenyAllAnnotationHandler();
- Annotation denyAllAnnotation = new DenyAll() {
- @Override
- public Class<? extends Annotation> annotationType() {
- return DenyAll.class;
- }
- };
+ Annotation denyAllAnnotation = new DenyAll() {
+ @Override
+ public Class<? extends Annotation> annotationType() {
+ return DenyAll.class;
+ }
+ };
- handler.assertAuthorized(denyAllAnnotation);
+ handler.assertAuthorized(denyAllAnnotation);
+ });
}
- @Test(expected = UnauthenticatedException.class)
- public void testOneOfTheRolesRequired() throws Throwable {
- subject = createMock(Subject.class);
- expect(subject.hasRole("blah")).andReturn(true);
- replay(subject);
- DenyAllAnnotationHandler handler = new DenyAllAnnotationHandler() {
- @Override
- protected Subject getSubject() {
- return subject;
- }
- };
+ @Test
+ void testOneOfTheRolesRequired() throws Throwable {
+ assertThrows(UnauthenticatedException.class, () -> {
+ subject = createMock(Subject.class);
+ expect(subject.hasRole("blah")).andReturn(true);
+ replay(subject);
+ DenyAllAnnotationHandler handler = new DenyAllAnnotationHandler() {
+ @Override
+ protected Subject getSubject() {
+ return subject;
+ }
+ };
- Annotation denyAllAnnotation = new DenyAll() {
- @Override
- public Class<? extends Annotation> annotationType() {
- return DenyAll.class;
- }
- };
- handler.assertAuthorized(denyAllAnnotation);
+ Annotation denyAllAnnotation = new DenyAll() {
+ @Override
+ public Class<? extends Annotation> annotationType() {
+ return DenyAll.class;
+ }
+ };
+ handler.assertAuthorized(denyAllAnnotation);
+ });
}
}
diff --git a/core/src/test/java/org/apache/shiro/authz/aop/PermitAllAnnotationHandlerTest.java b/core/src/test/java/org/apache/shiro/authz/aop/PermitAllAnnotationHandlerTest.java
index 720f30954..5363df346 100644
--- a/core/src/test/java/org/apache/shiro/authz/aop/PermitAllAnnotationHandlerTest.java
+++ b/core/src/test/java/org/apache/shiro/authz/aop/PermitAllAnnotationHandlerTest.java
@@ -20,7 +20,7 @@ package org.apache.shiro.authz.aop;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.test.SecurityManagerTestSupport;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.annotation.security.PermitAll;
import java.lang.annotation.Annotation;
@@ -30,7 +30,7 @@ import java.lang.annotation.Annotation;
*/
public class PermitAllAnnotationHandlerTest extends SecurityManagerTestSupport {
@Test
- public void testPermitAll() throws Throwable {
+ void testPermitAll() throws Throwable {
PermitAllAnnotationHandler handler = new PermitAllAnnotationHandler();
Annotation permitallAnnotation = new PermitAll() {
diff --git a/core/src/test/java/org/apache/shiro/authz/aop/RolesAllowedAnnotationHandlerTest.java b/core/src/test/java/org/apache/shiro/authz/aop/RolesAllowedAnnotationHandlerTest.java
index ad2daf17b..f642ba205 100644
--- a/core/src/test/java/org/apache/shiro/authz/aop/RolesAllowedAnnotationHandlerTest.java
+++ b/core/src/test/java/org/apache/shiro/authz/aop/RolesAllowedAnnotationHandlerTest.java
@@ -21,10 +21,12 @@ package org.apache.shiro.authz.aop;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.test.SecurityManagerTestSupport;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.annotation.security.RolesAllowed;
import java.lang.annotation.Annotation;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -35,65 +37,69 @@ import static org.mockito.Mockito.when;
public class RolesAllowedAnnotationHandlerTest extends SecurityManagerTestSupport {
private Subject subject;
- @Test(expected = UnauthenticatedException.class)
- public void testGuestSingleRoleAssertion() throws Throwable {
- subject = mock(Subject.class);
- doThrow(new UnauthenticatedException()).when(subject).checkRole("blah");
-
- RolesAllowedAnnotationHandler handler = new RolesAllowedAnnotationHandler() {
- @Override
- protected Subject getSubject() {
- return subject;
- }
- };
-
- Annotation rolesAllowedAnnotation = new RolesAllowed() {
- @Override
- public String[] value() {
- return new String[]{"blah"};
- }
-
- @Override
- public Class<? extends Annotation> annotationType() {
- return RolesAllowed.class;
- }
- };
-
- handler.assertAuthorized(rolesAllowedAnnotation);
+ @Test
+ void testGuestSingleRoleAssertion() throws Throwable {
+ assertThrows(UnauthenticatedException.class, () -> {
+ subject = mock(Subject.class);
+ doThrow(new UnauthenticatedException()).when(subject).checkRole("blah");
+
+ RolesAllowedAnnotationHandler handler = new RolesAllowedAnnotationHandler() {
+ @Override
+ protected Subject getSubject() {
+ return subject;
+ }
+ };
+
+ Annotation rolesAllowedAnnotation = new RolesAllowed() {
+ @Override
+ public String[] value() {
+ return new String[]{"blah"};
+ }
+
+ @Override
+ public Class<? extends Annotation> annotationType() {
+ return RolesAllowed.class;
+ }
+ };
+
+ handler.assertAuthorized(rolesAllowedAnnotation);
+ });
}
- @Test(expected = UnauthenticatedException.class)
- public void testGuestMultipleRolesAssertion() throws Throwable {
- subject = mock(Subject.class);
-
- doThrow(new UnauthenticatedException()).when(subject).checkRole("blah");
- when(subject.hasRole("blah")).thenReturn(false);
- when(subject.hasRole("blah2")).thenReturn(false);
-
- RolesAllowedAnnotationHandler handler = new RolesAllowedAnnotationHandler() {
- @Override
- protected Subject getSubject() {
- return subject;
- }
- };
-
- Annotation rolesAllowedAnnotation = new RolesAllowed() {
- @Override
- public String[] value() {
- return new String[]{"blah", "blah2"};
- }
-
- @Override
- public Class<? extends Annotation> annotationType() {
- return RolesAllowed.class;
- }
- };
-
- handler.assertAuthorized(rolesAllowedAnnotation);
+ @Test
+ void testGuestMultipleRolesAssertion() throws Throwable {
+ assertThrows(UnauthenticatedException.class, () -> {
+ subject = mock(Subject.class);
+
+ doThrow(new UnauthenticatedException()).when(subject).checkRole("blah");
+ when(subject.hasRole("blah")).thenReturn(false);
+ when(subject.hasRole("blah2")).thenReturn(false);
+
+ RolesAllowedAnnotationHandler handler = new RolesAllowedAnnotationHandler() {
+ @Override
+ protected Subject getSubject() {
+ return subject;
+ }
+ };
+
+ Annotation rolesAllowedAnnotation = new RolesAllowed() {
+ @Override
+ public String[] value() {
+ return new String[]{"blah", "blah2"};
+ }
+
+ @Override
+ public Class<? extends Annotation> annotationType() {
+ return RolesAllowed.class;
+ }
+ };
+
+ handler.assertAuthorized(rolesAllowedAnnotation);
+ });
}
@Test
- public void testOneOfTheRolesRequired() throws Throwable {
+ void testOneOfTheRolesRequired() throws Throwable {
subject = mock(Subject.class);
when(subject.hasRole("blah")).thenReturn(true);
when(subject.hasRole("blah2")).thenReturn(false);
diff --git a/core/src/test/java/org/apache/shiro/authz/permission/AllPermissionTest.java b/core/src/test/java/org/apache/shiro/authz/permission/AllPermissionTest.java
index 044c0cc2f..c4aab8127 100644
--- a/core/src/test/java/org/apache/shiro/authz/permission/AllPermissionTest.java
+++ b/core/src/test/java/org/apache/shiro/authz/permission/AllPermissionTest.java
@@ -18,8 +18,9 @@
*/
package org.apache.shiro.authz.permission;
-import static org.junit.Assert.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -27,12 +28,12 @@ import org.junit.Test;
public class AllPermissionTest {
@Test
- public void testNullArgument() {
+ void testNullArgument() {
assertTrue(new AllPermission().implies(null));
}
@Test
- public void testNonNullArgument() {
+ void testNonNullArgument() {
assertTrue(new AllPermission().implies(new AllPermission()));
}
}
diff --git a/core/src/test/java/org/apache/shiro/authz/permission/DomainPermissionTest.java b/core/src/test/java/org/apache/shiro/authz/permission/DomainPermissionTest.java
index f9be06eeb..e25359429 100644
--- a/core/src/test/java/org/apache/shiro/authz/permission/DomainPermissionTest.java
+++ b/core/src/test/java/org/apache/shiro/authz/permission/DomainPermissionTest.java
@@ -18,20 +18,20 @@
*/
package org.apache.shiro.authz.permission;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @since 1.3
*/
public class DomainPermissionTest {
@Test
- public void testDefaultConstructor() {
+ void testDefaultConstructor() {
DomainPermission p;
List<Set<String>> parts;
Set<String> set;
@@ -53,7 +53,7 @@ public class DomainPermissionTest {
// Verify parts
parts = p.getParts();
- assertEquals("Number of parts", 1, parts.size());
+ assertEquals(1, parts.size(), "Number of parts");
set = parts.get(0);
assertEquals(1, set.size());
entry = set.iterator().next();
@@ -61,7 +61,7 @@ public class DomainPermissionTest {
}
@Test
- public void testActionsConstructorWithSingleAction() {
+ void testActionsConstructorWithSingleAction() {
DomainPermission p;
List<Set<String>> parts;
Set<String> set;
@@ -102,7 +102,7 @@ public class DomainPermissionTest {
}
@Test
- public void testActionsConstructorWithMultipleActions() {
+ void testActionsConstructorWithMultipleActions() {
DomainPermission p;
List<Set<String>> parts;
Set<String> set;
@@ -151,7 +151,7 @@ public class DomainPermissionTest {
}
@Test
- public void testActionsTargetsConstructorWithSingleActionAndTarget() {
+ void testActionsTargetsConstructorWithSingleActionAndTarget() {
DomainPermission p;
List<Set<String>> parts;
Set<String> set;
@@ -201,7 +201,7 @@ public class DomainPermissionTest {
}
@Test
- public void testActionsTargetsConstructorWithMultipleActionsAndTargets() {
+ void testActionsTargetsConstructorWithMultipleActionsAndTargets() {
DomainPermission p;
List<Set<String>> parts;
Set<String> set;
diff --git a/core/src/test/java/org/apache/shiro/authz/permission/WildcardPermissionResolverTest.java b/core/src/test/java/org/apache/shiro/authz/permission/WildcardPermissionResolverTest.java
index d42ce6896..66a5b17c4 100644
--- a/core/src/test/java/org/apache/shiro/authz/permission/WildcardPermissionResolverTest.java
+++ b/core/src/test/java/org/apache/shiro/authz/permission/WildcardPermissionResolverTest.java
@@ -18,56 +18,54 @@
*/
package org.apache.shiro.authz.permission;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import org.junit.jupiter.api.Test;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.*;
public class WildcardPermissionResolverTest {
@Test
- public void testDefaultIsNonCaseSensitive()
+ void testDefaultIsNonCaseSensitive()
{
WildcardPermissionResolver resolver = new WildcardPermissionResolver();
- assertFalse( "Default sensitivity should be false", resolver.isCaseSensitive());
+ assertFalse( resolver.isCaseSensitive(), "Default sensitivity should be false");
/* this is a round-about test as permissions don't store case sensitivity just lower case
the string. */
WildcardPermission permission = (WildcardPermission) resolver.resolvePermission( "Foo:*" );
- assertEquals( "string should be lowercase", "foo:*", permission.toString());
+ assertEquals( "foo:*", permission.toString(), "string should be lowercase");
}
-
+
@Test
- public void testCaseSensitive()
+ void testCaseSensitive()
{
WildcardPermissionResolver resolver = new WildcardPermissionResolver(true);
- assertTrue( "Sensitivity should be true", resolver.isCaseSensitive());
+ assertTrue( resolver.isCaseSensitive(), "Sensitivity should be true");
/* this is a round-about test as permissions don't store case sensitivity just lower case
the string. */
WildcardPermission permission = (WildcardPermission) resolver.resolvePermission( "Foo:*" );
- assertEquals( "string should be mixed case", "Foo:*", permission.toString());
+ assertEquals( "Foo:*", permission.toString(), "string should be mixed case");
}
@Test
- public void testCaseInsensitive()
+ void testCaseInsensitive()
{
WildcardPermissionResolver resolver = new WildcardPermissionResolver(false);
- assertFalse( "Sensitivity should be false", resolver.isCaseSensitive());
+ assertFalse( resolver.isCaseSensitive(), "Sensitivity should be false");
/* this is a round-about test as permissions don't store case sensitivity just lower case
the string. */
WildcardPermission permission = (WildcardPermission) resolver.resolvePermission( "Foo:*" );
- assertEquals( "string should be lowercase", "foo:*", permission.toString());
+ assertEquals( "foo:*", permission.toString(), "string should be lowercase");
}
-
+
@Test
- public void testCaseSensitiveToggle()
+ void testCaseSensitiveToggle()
{
WildcardPermissionResolver resolver = new WildcardPermissionResolver();
- assertFalse( "Default sensitivity should be false", resolver.isCaseSensitive());
+ assertFalse( resolver.isCaseSensitive(), "Default sensitivity should be false");
resolver.setCaseSensitive( true );
- assertTrue( "Sensitivity should be true", resolver.isCaseSensitive());
+ assertTrue( resolver.isCaseSensitive(), "Sensitivity should be true");
resolver.setCaseSensitive( false );
- assertFalse( "Sensitivity should be false", resolver.isCaseSensitive());
+ assertFalse( resolver.isCaseSensitive(), "Sensitivity should be false");
}
}
diff --git a/core/src/test/java/org/apache/shiro/authz/permission/WildcardPermissionTest.java b/core/src/test/java/org/apache/shiro/authz/permission/WildcardPermissionTest.java
index 9635f9e5d..b619351d7 100644
--- a/core/src/test/java/org/apache/shiro/authz/permission/WildcardPermissionTest.java
+++ b/core/src/test/java/org/apache/shiro/authz/permission/WildcardPermissionTest.java
@@ -18,9 +18,9 @@
*/
package org.apache.shiro.authz.permission;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -28,28 +28,36 @@ import org.junit.Test;
*/
public class WildcardPermissionTest {
- @Test(expected = IllegalArgumentException.class)
- public void testNull() {
- new WildcardPermission(null);
+ @Test
+ void testNull() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new WildcardPermission(null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void testEmpty() {
- new WildcardPermission("");
+ @Test
+ void testEmpty() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new WildcardPermission("");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void testBlank() {
- new WildcardPermission(" ");
+ @Test
+ void testBlank() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new WildcardPermission(" ");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void testOnlyDelimiters() {
- new WildcardPermission("::,,::,:");
+ @Test
+ void testOnlyDelimiters() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new WildcardPermission("::,,::,:");
+ });
}
@Test
- public void testNamed() {
+ void testNamed() {
WildcardPermission p1, p2;
// Case insensitive, same
@@ -91,7 +99,7 @@ public class WildcardPermissionTest {
}
@Test
- public void testLists() {
+ void testLists() {
WildcardPermission p1, p2, p3;
p1 = new WildcardPermission("one,two");
@@ -132,7 +140,7 @@ public class WildcardPermissionTest {
* Validates WildcardPermissions with that contain the same list parts are equal.
*/
@Test
- public void testListDifferentOrder() {
+ void testListDifferentOrder() {
WildcardPermission p6 = new WildcardPermission("one,two:three,four");
WildcardPermission p6DiffOrder = new WildcardPermission("two,one:four,three");
@@ -140,7 +148,7 @@ public class WildcardPermissionTest {
}
@Test
- public void testWildcards() {
+ void testWildcards() {
WildcardPermission p1, p2, p3, p4, p5, p6, p7, p8, p9;
p1 = new WildcardPermission("*");
@@ -221,7 +229,7 @@ public class WildcardPermissionTest {
}
@Test
- public void testToString() {
+ void testToString() {
WildcardPermission p1 = new WildcardPermission("*");
WildcardPermission p2 = new WildcardPermission("one");
WildcardPermission p3 = new WildcardPermission("one:two");
@@ -241,7 +249,7 @@ public class WildcardPermissionTest {
}
@Test
- public void testWildcardLeftTermination() {
+ void testWildcardLeftTermination() {
WildcardPermission p1, p2, p3, p4;
p1 = new WildcardPermission("one");
diff --git a/core/src/test/java/org/apache/shiro/jndi/JndiObjectFactoryTest.java b/core/src/test/java/org/apache/shiro/jndi/JndiObjectFactoryTest.java
index cd55c70db..737b46e99 100644
--- a/core/src/test/java/org/apache/shiro/jndi/JndiObjectFactoryTest.java
+++ b/core/src/test/java/org/apache/shiro/jndi/JndiObjectFactoryTest.java
@@ -18,11 +18,12 @@
*/
package org.apache.shiro.jndi;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.naming.NamingException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* This test makes the assumption that {@link JndiLocator} is tested elsewhere and only makes an attempt to test the
@@ -30,7 +31,7 @@ import static org.junit.Assert.assertEquals;
*/
public class JndiObjectFactoryTest {
@Test
- public void testGetInstanceWithType() throws Exception {
+ void testGetInstanceWithType() throws Exception {
final String name = "my/jndi/resource";
final String returnValue = "jndiString";
JndiObjectFactory<String> underTest = new JndiObjectFactory<String>() {
@@ -49,7 +50,7 @@ public class JndiObjectFactoryTest {
}
@Test
- public void testGetInstanceNoType() throws Exception {
+ void testGetInstanceNoType() throws Exception {
final String name = "my/jndi/resource";
final String returnValue = "jndiString";
JndiObjectFactory<String> underTest = new JndiObjectFactory<String>() {
@@ -65,34 +66,38 @@ public class JndiObjectFactoryTest {
assertEquals(returnValue, underTest.getInstance());
}
- @Test(expected = IllegalStateException.class)
- public void testJndiLookupFailsWithType() throws Exception {
- final String name = "my/jndi/resource";
- JndiObjectFactory<String> underTest = new JndiObjectFactory<String>() {
- @Override
- protected Object lookup(String jndiName, Class requiredType) throws NamingException {
- throw new NamingException("No resource named " + jndiName);
- }
- };
+ @Test
+ void testJndiLookupFailsWithType() throws Exception {
+ assertThrows(IllegalStateException.class, () -> {
+ final String name = "my/jndi/resource";
+ JndiObjectFactory<String> underTest = new JndiObjectFactory<String>() {
+ @Override
+ protected Object lookup(String jndiName, Class requiredType) throws NamingException {
+ throw new NamingException("No resource named " + jndiName);
+ }
+ };
- underTest.setResourceName(name);
- underTest.setRequiredType(String.class);
+ underTest.setResourceName(name);
+ underTest.setRequiredType(String.class);
- underTest.getInstance();
+ underTest.getInstance();
+ });
}
- @Test(expected = IllegalStateException.class)
- public void testJndiLookupFailsNoType() throws Exception {
- final String name = "my/jndi/resource";
- JndiObjectFactory<String> underTest = new JndiObjectFactory<String>() {
- @Override
- protected Object lookup(String jndiName) throws NamingException {
- throw new NamingException("No resource named " + jndiName);
- }
- };
+ @Test
+ void testJndiLookupFailsNoType() throws Exception {
+ assertThrows(IllegalStateException.class, () -> {
+ final String name = "my/jndi/resource";
+ JndiObjectFactory<String> underTest = new JndiObjectFactory<String>() {
+ @Override
+ protected Object lookup(String jndiName) throws NamingException {
+ throw new NamingException("No resource named " + jndiName);
+ }
+ };
- underTest.setResourceName(name);
+ underTest.setResourceName(name);
- underTest.getInstance();
+ underTest.getInstance();
+ });
}
}
diff --git a/core/src/test/java/org/apache/shiro/mgt/AbstractRememberMeManagerTest.java b/core/src/test/java/org/apache/shiro/mgt/AbstractRememberMeManagerTest.java
index c52a2b280..236fe3a4b 100644
--- a/core/src/test/java/org/apache/shiro/mgt/AbstractRememberMeManagerTest.java
+++ b/core/src/test/java/org/apache/shiro/mgt/AbstractRememberMeManagerTest.java
@@ -22,9 +22,9 @@ import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.SubjectContext;
import org.apache.shiro.subject.support.DefaultSubjectContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Test cases for the {@link AbstractRememberMeManager} implementation.
@@ -38,7 +38,7 @@ public class AbstractRememberMeManagerTest {
* returns null or empty bytes.
*/
@Test
- public void testGetRememberedPrincipalsWithEmptySerializedBytes() {
+ void testGetRememberedPrincipalsWithEmptySerializedBytes() {
AbstractRememberMeManager rmm = new DummyRememberMeManager();
//Since the dummy's getRememberedSerializedIdentity implementation returns an empty byte
//array, we should be ok:
diff --git a/core/src/test/java/org/apache/shiro/mgt/AbstractSecurityManagerTest.java b/core/src/test/java/org/apache/shiro/mgt/AbstractSecurityManagerTest.java
index 7e316f9f9..12a44cfd8 100644
--- a/core/src/test/java/org/apache/shiro/mgt/AbstractSecurityManagerTest.java
+++ b/core/src/test/java/org/apache/shiro/mgt/AbstractSecurityManagerTest.java
@@ -22,7 +22,7 @@ import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.SubjectThreadState;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.util.ThreadState;
-import org.junit.After;
+import org.junit.jupiter.api.AfterEach;
/**
* @since 1.0
@@ -31,7 +31,7 @@ public abstract class AbstractSecurityManagerTest {
protected ThreadState threadState;
- @After
+ @AfterEach
public void tearDown() {
ThreadContext.remove();
}
diff --git a/core/src/test/java/org/apache/shiro/mgt/DefaultSecurityManagerTest.java b/core/src/test/java/org/apache/shiro/mgt/DefaultSecurityManagerTest.java
index d8b96501f..064d9ce96 100644
--- a/core/src/test/java/org/apache/shiro/mgt/DefaultSecurityManagerTest.java
+++ b/core/src/test/java/org/apache/shiro/mgt/DefaultSecurityManagerTest.java
@@ -30,13 +30,13 @@ import org.apache.shiro.session.mgt.AbstractValidatingSessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DelegatingSubject;
import org.apache.shiro.util.ThreadContext;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.Serializable;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -46,7 +46,7 @@ public class DefaultSecurityManagerTest extends AbstractSecurityManagerTest {
DefaultSecurityManager sm = null;
- @Before
+ @BeforeEach
public void setup() {
sm = new DefaultSecurityManager();
Ini ini = new Ini();
@@ -57,7 +57,7 @@ public class DefaultSecurityManagerTest extends AbstractSecurityManagerTest {
SecurityUtils.setSecurityManager(sm);
}
- @After
+ @AfterEach
public void tearDown() {
SecurityUtils.setSecurityManager(null);
sm.destroy();
@@ -65,7 +65,7 @@ public class DefaultSecurityManagerTest extends AbstractSecurityManagerTest {
}
@Test
- public void testDefaultConfig() {
+ void testDefaultConfig() {
Subject subject = SecurityUtils.getSubject();
AuthenticationToken token = new UsernamePasswordToken("guest", "guest");
@@ -90,7 +90,7 @@ public class DefaultSecurityManagerTest extends AbstractSecurityManagerTest {
* <a href="https://issues.apache.org/jira/browse/JSEC-46">JSEC-46</a>
*/
@Test
- public void testAutoCreateSessionAfterInvalidation() {
+ void testAutoCreateSessionAfterInvalidation() {
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
Serializable origSessionId = session.getId();
@@ -119,7 +119,7 @@ public class DefaultSecurityManagerTest extends AbstractSecurityManagerTest {
* <a href="https://issues.apache.org/jira/browse/JSEC-22">JSEC-22</a>
*/
@Test
- public void testSubjectReuseAfterLogout() {
+ void testSubjectReuseAfterLogout() {
Subject subject = SecurityUtils.getSubject();
@@ -165,7 +165,7 @@ public class DefaultSecurityManagerTest extends AbstractSecurityManagerTest {
* <a href="https://issues.apache.org/jira/browse/SHIRO-457">SHIRO-457</a>
*/
@Test
- public void testNewSubjectWithoutThreadSecurityManager() {
+ void testNewSubjectWithoutThreadSecurityManager() {
// Ensure no fallback sm exists in thread context or statically
SecurityUtils.setSecurityManager(null);
try {
diff --git a/core/src/test/java/org/apache/shiro/mgt/VMSingletonDefaultSecurityManagerTest.java b/core/src/test/java/org/apache/shiro/mgt/VMSingletonDefaultSecurityManagerTest.java
index 0de2a6513..3e46b60c4 100644
--- a/core/src/test/java/org/apache/shiro/mgt/VMSingletonDefaultSecurityManagerTest.java
+++ b/core/src/test/java/org/apache/shiro/mgt/VMSingletonDefaultSecurityManagerTest.java
@@ -25,11 +25,11 @@ import org.apache.shiro.config.Ini;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -37,18 +37,18 @@ import static org.junit.Assert.assertTrue;
*/
public class VMSingletonDefaultSecurityManagerTest {
- @Before
+ @BeforeEach
public void setUp() {
ThreadContext.remove();
}
- @After
+ @AfterEach
public void tearDown() {
ThreadContext.remove();
}
@Test
- public void testVMSingleton() {
+ void testVMSingleton() {
DefaultSecurityManager sm = new DefaultSecurityManager();
Ini ini = new Ini();
Ini.Section section = ini.addSection(IniRealm.USERS_SECTION_NAME);
diff --git a/core/src/test/java/org/apache/shiro/realm/AuthorizingRealmTest.java b/core/src/test/java/org/apache/shiro/realm/AuthorizingRealmTest.java
index c78d66919..d53c9f36a 100644
--- a/core/src/test/java/org/apache/shiro/realm/AuthorizingRealmTest.java
+++ b/core/src/test/java/org/apache/shiro/realm/AuthorizingRealmTest.java
@@ -40,15 +40,11 @@ import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.authz.permission.WildcardPermissionResolver;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -66,19 +62,19 @@ public class AuthorizingRealmTest {
private static final String ROLE = "admin";
private String localhost = "localhost";
- @Before
+ @BeforeEach
public void setup() {
realm = new AllowAllRealm();
}
- @After
+ @AfterEach
public void tearDown() {
realm = null;
}
@Test
- public void testDefaultConfig() {
+ void testDefaultConfig() {
AuthenticationInfo info = realm.getAuthenticationInfo(new UsernamePasswordToken(USERNAME, PASSWORD, localhost));
assertNotNull(info);
@@ -98,7 +94,7 @@ public class AuthorizingRealmTest {
}
@Test
- public void testCreateAccountOverride() {
+ void testCreateAccountOverride() {
AuthorizingRealm realm = new AllowAllRealm() {
@Override
@@ -120,7 +116,7 @@ public class AuthorizingRealmTest {
}
@Test
- public void testNullAuthzInfo() {
+ void testNullAuthzInfo() {
AuthorizingRealm realm = new AuthorizingRealm() {
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
@@ -198,9 +194,9 @@ public class AuthorizingRealmTest {
assertFalse(realm.isPermittedAll(pCollection, "perm1", "perm2"));
assertFalse(realm.isPermittedAll(pCollection, permList));
}
-
+
@Test
- public void testRealmWithRolePermissionResolver()
+ void testRealmWithRolePermissionResolver()
{
Principal principal = new UsernamePrincipal("rolePermResolver");
PrincipalCollection pCollection = new SimplePrincipalCollection(principal, "testRealmWithRolePermissionResolver");
@@ -229,7 +225,7 @@ public class AuthorizingRealmTest {
}
@Test
- public void testRealmWithEmptyOrNullPermissions() {
+ void testRealmWithEmptyOrNullPermissions() {
Principal principal = new UsernamePrincipal("rolePermResolver");
PrincipalCollection pCollection = new SimplePrincipalCollection(principal, "testRealmWithRolePermissionResolver");
diff --git a/core/src/test/java/org/apache/shiro/realm/activedirectory/ActiveDirectoryRealmTest.java b/core/src/test/java/org/apache/shiro/realm/activedirectory/ActiveDirectoryRealmTest.java
index 824dcb4a6..4fe9e415e 100644
--- a/core/src/test/java/org/apache/shiro/realm/activedirectory/ActiveDirectoryRealmTest.java
+++ b/core/src/test/java/org/apache/shiro/realm/activedirectory/ActiveDirectoryRealmTest.java
@@ -35,10 +35,10 @@ import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.easymock.Capture;
import org.easymock.CaptureType;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
@@ -56,7 +56,7 @@ import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -78,7 +78,7 @@ public class ActiveDirectoryRealmTest {
private static final int USER_ID = 12345;
private static final String ROLE = "admin";
- @Before
+ @BeforeEach
public void setup() {
ThreadContext.remove();
realm = new TestActiveDirectoryRealm();
@@ -86,7 +86,7 @@ public class ActiveDirectoryRealmTest {
SecurityUtils.setSecurityManager(securityManager);
}
- @After
+ @AfterEach
public void tearDown() {
SecurityUtils.setSecurityManager(null);
securityManager.destroy();
@@ -94,7 +94,7 @@ public class ActiveDirectoryRealmTest {
}
@Test
- public void testDefaultConfig() {
+ void testDefaultConfig() {
String localhost = "localhost";
Subject subject = SecurityUtils.getSubject();
subject.login(new UsernamePasswordToken(USERNAME, PASSWORD, localhost));
@@ -114,7 +114,7 @@ public class ActiveDirectoryRealmTest {
}
@Test
- public void testExistingUserSuffix() throws Exception {
+ void testExistingUserSuffix() throws Exception {
assertExistingUserSuffix(USERNAME, "testuser@ExAmple.COM"); // suffix case matches configure suffix
// suffix matches user entry
@@ -141,7 +141,7 @@ public class ActiveDirectoryRealmTest {
try {
activeDirectoryRealm.getRoleNamesForUser(username, ldapContext);
} catch (NamingException e) {
- Assert.fail("Unexpected NamingException thrown during test");
+ Assertions.fail("Unexpected NamingException thrown during test");
}
});
diff --git a/core/src/test/java/org/apache/shiro/realm/jdbc/JDBCRealmTest.java b/core/src/test/java/org/apache/shiro/realm/jdbc/JDBCRealmTest.java
index 7a485e3d7..04f911083 100644
--- a/core/src/test/java/org/apache/shiro/realm/jdbc/JDBCRealmTest.java
+++ b/core/src/test/java/org/apache/shiro/realm/jdbc/JDBCRealmTest.java
@@ -33,14 +33,22 @@ import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.JdbcUtils;
import org.apache.shiro.util.ThreadContext;
import org.hsqldb.jdbc.JDBCDataSource;
-import org.junit.*;
-import org.junit.rules.TestName;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.TestInfo;
import javax.sql.DataSource;
+
+import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
+import java.util.Optional;
/**
@@ -60,38 +68,42 @@ public class JDBCRealmTest {
protected HashMap<String, JdbcRealm> realmMap = new HashMap<String, JdbcRealm>();
protected HashMap<String, DataSource> dsMap = new HashMap<String, DataSource>();
- @Rule
- public TestName name = new TestName();
+
+ public String name;
- @Before
- public void setup() {
+ @BeforeEach
+ public void setup(TestInfo testInfo) {
+ Optional<Method> testMethod = testInfo.getTestMethod();
+ if (testMethod.isPresent()) {
+ this.name = testMethod.get().getName();
+ }
ThreadContext.remove();
Ini config = new Ini();
config.setSectionProperty("main", "myRealm", "org.apache.shiro.realm.jdbc.JdbcRealm");
config.setSectionProperty("main", "myRealmCredentialsMatcher", "org.apache.shiro.authc.credential.Sha256CredentialsMatcher");
config.setSectionProperty("main", "myRealm.credentialsMatcher", "$myRealmCredentialsMatcher");
config.setSectionProperty("main", "securityManager.sessionManager.sessionValidationSchedulerEnabled", "false");
-
+
IniSecurityManagerFactory factory = new IniSecurityManagerFactory(config);
securityManager = (DefaultSecurityManager) factory.createInstance();
SecurityUtils.setSecurityManager(securityManager);
-
+
// Create a database and realm for the test
- createRealm(name.getMethodName());
+ createRealm( name);
}
- @After
+ @AfterEach
public void tearDown() {
- final String testName = name.getMethodName();
+ final String testName = name;
shutDown(testName);
SecurityUtils.setSecurityManager(null);
securityManager.destroy();
ThreadContext.remove();
}
-
+
@Test
- public void testUnSaltedSuccess() throws Exception {
- String testMethodName = name.getMethodName();
+ void testUnSaltedSuccess() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createDefaultSchema(testMethodName, false);
realm.setSaltStyle(JdbcRealm.SaltStyle.NO_SALT);
@@ -102,10 +114,10 @@ public class JDBCRealmTest {
currentUser.login(token);
currentUser.logout();
}
-
+
@Test
- public void testUnSaltedWrongPassword() throws Exception {
- String testMethodName = name.getMethodName();
+ void testUnSaltedWrongPassword() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createDefaultSchema(testMethodName, false);
realm.setSaltStyle(JdbcRealm.SaltStyle.NO_SALT);
@@ -119,10 +131,10 @@ public class JDBCRealmTest {
// Expected
}
}
-
+
@Test
- public void testUnSaltedMultipleRows() throws Exception {
- String testMethodName = name.getMethodName();
+ void testUnSaltedMultipleRows() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createDefaultSchema(testMethodName, false);
realm.setSaltStyle(JdbcRealm.SaltStyle.NO_SALT);
@@ -139,10 +151,10 @@ public class JDBCRealmTest {
// Expected
}
}
-
+
@Test
- public void testSaltColumnSuccess() throws Exception {
- String testMethodName = name.getMethodName();
+ void testSaltColumnSuccess() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createSaltColumnSchema(testMethodName, false);
realm.setSaltStyle(JdbcRealm.SaltStyle.COLUMN);
@@ -154,10 +166,10 @@ public class JDBCRealmTest {
currentUser.login(token);
currentUser.logout();
}
-
+
@Test
- public void testBase64EncodedSaltColumnSuccess() throws Exception {
- String testMethodName = name.getMethodName();
+ void testBase64EncodedSaltColumnSuccess() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createSaltColumnSchema(testMethodName, true);
realm.setSaltStyle(JdbcRealm.SaltStyle.COLUMN);
@@ -170,8 +182,8 @@ public class JDBCRealmTest {
}
@Test
- public void testSaltColumnWrongPassword() throws Exception {
- String testMethodName = name.getMethodName();
+ void testSaltColumnWrongPassword() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createSaltColumnSchema(testMethodName, false);
realm.setSaltStyle(JdbcRealm.SaltStyle.COLUMN);
@@ -188,8 +200,8 @@ public class JDBCRealmTest {
}
@Test
- public void testBase64SaltColumnWrongPassword() throws Exception {
- String testMethodName = name.getMethodName();
+ void testBase64SaltColumnWrongPassword() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createSaltColumnSchema(testMethodName, true);
realm.setSaltStyle(JdbcRealm.SaltStyle.COLUMN);
@@ -204,10 +216,10 @@ public class JDBCRealmTest {
// Expected
}
}
-
+
@Test
- public void testExternalSuccess() throws Exception {
- String testMethodName = name.getMethodName();
+ void testExternalSuccess() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createDefaultSchema(testMethodName, true);
realm.setSaltStyle(JdbcRealm.SaltStyle.EXTERNAL);
@@ -218,10 +230,10 @@ public class JDBCRealmTest {
currentUser.login(token);
currentUser.logout();
}
-
+
@Test
- public void testExternalWrongPassword() throws Exception {
- String testMethodName = name.getMethodName();
+ void testExternalWrongPassword() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createDefaultSchema(testMethodName, true);
realm.setSaltStyle(JdbcRealm.SaltStyle.EXTERNAL);
@@ -235,10 +247,10 @@ public class JDBCRealmTest {
// Expected
}
}
-
+
@Test
- public void testRolePresent() throws Exception {
- String testMethodName = name.getMethodName();
+ void testRolePresent() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createDefaultSchema(testMethodName, false);
realm.setSaltStyle(JdbcRealm.SaltStyle.NO_SALT);
@@ -247,12 +259,12 @@ public class JDBCRealmTest {
Subject currentUser = builder.buildSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, plainTextPassword);
currentUser.login(token);
- Assert.assertTrue(currentUser.hasRole(testRole));
+ Assertions.assertTrue(currentUser.hasRole(testRole));
}
-
+
@Test
- public void testRoleNotPresent() throws Exception {
- String testMethodName = name.getMethodName();
+ void testRoleNotPresent() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createDefaultSchema(testMethodName, false);
realm.setSaltStyle(JdbcRealm.SaltStyle.NO_SALT);
@@ -261,12 +273,12 @@ public class JDBCRealmTest {
Subject currentUser = builder.buildSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, plainTextPassword);
currentUser.login(token);
- Assert.assertFalse(currentUser.hasRole("Game Overall Director"));
+ Assertions.assertFalse(currentUser.hasRole("Game Overall Director"));
}
-
+
@Test
- public void testPermissionPresent() throws Exception {
- String testMethodName = name.getMethodName();
+ void testPermissionPresent() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createDefaultSchema(testMethodName, false);
realm.setSaltStyle(JdbcRealm.SaltStyle.NO_SALT);
@@ -276,12 +288,12 @@ public class JDBCRealmTest {
Subject currentUser = builder.buildSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, plainTextPassword);
currentUser.login(token);
- Assert.assertTrue(currentUser.isPermitted(testPermissionString));
+ Assertions.assertTrue(currentUser.isPermitted(testPermissionString));
}
-
+
@Test
- public void testPermissionNotPresent() throws Exception {
- String testMethodName = name.getMethodName();
+ void testPermissionNotPresent() throws Exception {
+ String testMethodName = name;
JdbcRealm realm = realmMap.get(testMethodName);
createDefaultSchema(testMethodName, false);
realm.setSaltStyle(JdbcRealm.SaltStyle.NO_SALT);
@@ -291,7 +303,7 @@ public class JDBCRealmTest {
Subject currentUser = builder.buildSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, plainTextPassword);
currentUser.login(token);
- Assert.assertFalse(currentUser.isPermitted("testDomain:testTarget:specialAction"));
+ Assertions.assertFalse(currentUser.isPermitted("testDomain:testTarget:specialAction"));
}
/**
@@ -345,7 +357,7 @@ public class JDBCRealmTest {
String password = sha256Hash.toHex();
sql.executeUpdate("insert into users values ('" + username + "', '" + password + "')");
} catch (SQLException ex) {
- Assert.fail("Exception creating test database");
+ Assertions.fail("Exception creating test database");
} finally {
JdbcUtils.closeStatement(sql);
JdbcUtils.closeConnection(conn);
@@ -378,7 +390,7 @@ public class JDBCRealmTest {
String maybeBase64EncodedSalt = base64EncodeSalt ? Base64.encodeToString(CodecSupport.toBytes(salt)) : salt;
sql.executeUpdate("insert into users values ('" + username + "', '" + password + "', '" + maybeBase64EncodedSalt + "')");
} catch (SQLException ex) {
- Assert.fail("Exception creating test database");
+ Assertions.fail("Exception creating test database");
} finally {
JdbcUtils.closeStatement(sql);
JdbcUtils.closeConnection(conn);
@@ -403,7 +415,7 @@ public class JDBCRealmTest {
sql.executeUpdate(
"insert into roles_permissions values ('" + testRole + "', '" + testPermissionString + "')");
} catch (SQLException ex) {
- Assert.fail("Exception adding test role and permission");
+ Assertions.fail("Exception adding test role and permission");
} finally {
JdbcUtils.closeStatement(sql);
JdbcUtils.closeConnection(conn);
diff --git a/core/src/test/java/org/apache/shiro/realm/ldap/DefaultLdapRealmTest.java b/core/src/test/java/org/apache/shiro/realm/ldap/DefaultLdapRealmTest.java
index a94927d79..9974a2ca2 100644
--- a/core/src/test/java/org/apache/shiro/realm/ldap/DefaultLdapRealmTest.java
+++ b/core/src/test/java/org/apache/shiro/realm/ldap/DefaultLdapRealmTest.java
@@ -21,9 +21,9 @@ package org.apache.shiro.realm.ldap;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
-import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
-import org.junit.Before;
-import org.junit.Test;
+import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;
@@ -31,8 +31,8 @@ import javax.naming.ldap.LdapContext;
import java.util.UUID;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.*;
-
+import static org.junit.jupiter.api.Assertions.*;
+
/**
* Tests for the {@link DefaultLdapRealm} class.
*
@@ -48,42 +48,48 @@ public class DefaultLdapRealmTest {
return new DefaultLdapRealm();
}
- @Before
+ @BeforeEach
public void setUp() {
realm = getNewRealmUnderTest();
- }
-
- @Test
- public void testDefaultInstance() {
+ }
+
+ @Test
+ void testDefaultInstance() {
assertTrue(realm.getCredentialsMatcher() instanceof AllowAllCredentialsMatcher);
assertEquals(AuthenticationToken.class, realm.getAuthenticationTokenClass());
assertTrue(realm.getContextFactory() instanceof JndiLdapContextFactory);
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void testSetUserDnTemplateNull() {
- realm.setUserDnTemplate(null);
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void testSetUserDnTemplateEmpty() {
- realm.setUserDnTemplate(" ");
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void testSetUserDnTemplateWithoutToken() {
- realm.setUserDnTemplate("uid=,ou=users,dc=mycompany,dc=com");
- }
-
- @Test
- public void testUserDnTemplate() {
+ }
+
+ @Test
+ void testSetUserDnTemplateNull() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ realm.setUserDnTemplate(null);
+ });
+ }
+
+ @Test
+ void testSetUserDnTemplateEmpty() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ realm.setUserDnTemplate(" ");
+ });
+ }
+
+ @Test
+ void testSetUserDnTemplateWithoutToken() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ realm.setUserDnTemplate("uid=,ou=users,dc=mycompany,dc=com");
+ });
+ }
+
+ @Test
+ void testUserDnTemplate() {
String template = "uid={0},ou=users,dc=mycompany,dc=com";
realm.setUserDnTemplate(template);
assertEquals(template, realm.getUserDnTemplate());
- }
-
- @Test
- public void testUserDnTemplateSubstitution() throws NamingException {
+ }
+
+ @Test
+ void testUserDnTemplateSubstitution() throws NamingException {
realm.setUserDnTemplate("uid={0},ou=users,dc=mycompany,dc=com");
LdapContextFactory factory = createMock(LdapContextFactory.class);
realm.setContextFactory(factory);
@@ -95,43 +101,47 @@ public class DefaultLdapRealmTest {
realm.getAuthenticationInfo(new UsernamePasswordToken("jsmith", "secret") );
verify(factory);
- }
-
- @Test(expected= AuthenticationException.class)
- public void testGetAuthenticationInfoNamingAuthenticationException() throws NamingException {
- realm.setUserDnTemplate("uid={0},ou=users,dc=mycompany,dc=com");
- LdapContextFactory factory = createMock(LdapContextFactory.class);
- realm.setContextFactory(factory);
-
- expect(factory.getLdapContext(isA(Object.class), isA(Object.class)))
- .andThrow(new javax.naming.AuthenticationException("LDAP Authentication failed."));
- replay(factory);
-
- realm.getAuthenticationInfo(new UsernamePasswordToken("jsmith", "secret") );
- }
-
- @Test(expected= AuthenticationException.class)
- public void testGetAuthenticationInfoNamingException() throws NamingException {
- realm.setUserDnTemplate("uid={0},ou=users,dc=mycompany,dc=com");
- LdapContextFactory factory = createMock(LdapContextFactory.class);
- realm.setContextFactory(factory);
-
- expect(factory.getLdapContext(isA(Object.class), isA(Object.class)))
- .andThrow(new NamingException("Communication error."));
- replay(factory);
-
- realm.getAuthenticationInfo(new UsernamePasswordToken("jsmith", "secret") );
- }
-
- /**
- * This test simulates that if a non-String principal (i.e. not a username) is passed as the LDAP principal, that
- * it is not altered into a User DN and is passed as-is. This will allow principals to be things like X.509
- * certificates as well instead of only strings.
- *
- * @throws NamingException not thrown
- */
- @Test
- public void testGetAuthenticationInfoNonSimpleToken() throws NamingException {
+ }
+
+ @Test
+ void testGetAuthenticationInfoNamingAuthenticationException() throws NamingException {
+ assertThrows(AuthenticationException.class, () -> {
+ realm.setUserDnTemplate("uid={0},ou=users,dc=mycompany,dc=com");
+ LdapContextFactory factory = createMock(LdapContextFactory.class);
+ realm.setContextFactory(factory);
+
+ expect(factory.getLdapContext(isA(Object.class), isA(Object.class)))
+ .andThrow(new javax.naming.AuthenticationException("LDAP Authentication failed."));
+ replay(factory);
+
+ realm.getAuthenticationInfo(new UsernamePasswordToken("jsmith", "secret"));
+ });
+ }
+
+ @Test
+ void testGetAuthenticationInfoNamingException() throws NamingException {
+ assertThrows(AuthenticationException.class, () -> {
+ realm.setUserDnTemplate("uid={0},ou=users,dc=mycompany,dc=com");
+ LdapContextFactory factory = createMock(LdapContextFactory.class);
+ realm.setContextFactory(factory);
+
+ expect(factory.getLdapContext(isA(Object.class), isA(Object.class)))
+ .andThrow(new NamingException("Communication error."));
+ replay(factory);
+
+ realm.getAuthenticationInfo(new UsernamePasswordToken("jsmith", "secret"));
+ });
+ }
+
+ /**
+ * This test simulates that if a non-String principal (i.e. not a username) is passed as the LDAP principal, that
+ * it is not altered into a User DN and is passed as-is. This will allow principals to be things like X.509
+ * certificates as well instead of only strings.
+ *
+ * @throws NamingException not thrown
+ */
+ @Test
+ void testGetAuthenticationInfoNonSimpleToken() throws NamingException {
realm.setUserDnTemplate("uid={0},ou=users,dc=mycompany,dc=com");
LdapContextFactory factory = createMock(LdapContextFactory.class);
realm.setContextFactory(factory);
@@ -152,15 +162,17 @@ public class DefaultLdapRealmTest {
}
});
verify(factory);
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void testGetUserDnNullArgument() {
- realm.getUserDn(null);
- }
-
- @Test
- public void testGetUserDnWithOutPrefixAndSuffix() {
+ }
+
+ @Test
+ void testGetUserDnNullArgument() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ realm.getUserDn(null);
+ });
+ }
+
+ @Test
+ void testGetUserDnWithOutPrefixAndSuffix() {
realm = new DefaultLdapRealm() {
@Override
protected String getUserDnPrefix() {
diff --git a/core/src/test/java/org/apache/shiro/realm/ldap/JndiLdapContextFactoryTest.java b/core/src/test/java/org/apache/shiro/realm/ldap/JndiLdapContextFactoryTest.java
index a1e0ee70e..fa3955696 100644
--- a/core/src/test/java/org/apache/shiro/realm/ldap/JndiLdapContextFactoryTest.java
+++ b/core/src/test/java/org/apache/shiro/realm/ldap/JndiLdapContextFactoryTest.java
@@ -18,8 +18,8 @@
*/
package org.apache.shiro.realm.ldap;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.naming.AuthenticationException;
import javax.naming.Context;
@@ -31,10 +31,8 @@ import java.util.Map;
import java.util.UUID;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
+import static org.junit.jupiter.api.Assertions.*;
+
/**
* Tests for the {@link JndiLdapContextFactory} class.
*
@@ -44,7 +42,7 @@ public class JndiLdapContextFactoryTest {
private JndiLdapContextFactory factory;
- @Before
+ @BeforeEach
public void setUp() {
factory = new JndiLdapContextFactory() {
//Fake a JNDI environment for the tests:
@@ -53,63 +51,67 @@ public class JndiLdapContextFactoryTest {
return createNiceMock(LdapContext.class);
}
};
- }
-
- /**
- * This is the only test that does not fake the JNDI environment. It is provided for 100% test coverage.
- *
- * @throws NamingException thrown because the host is always broken.
- */
- @Test(expected = NamingException.class)
- public void testGetLdapContext() throws NamingException {
- factory = new JndiLdapContextFactory();
- //garbage URL to test that the context is being created, but fails:
- String brokenHost = UUID.randomUUID().toString();
- factory.setUrl("ldap://" + brokenHost + ":389");
- factory.getLdapContext("foo", "bar");
- }
-
- @Test
- public void testAuthenticationMechanism() {
+ }
+
+ /**
+ * This is the only test that does not fake the JNDI environment. It is provided for 100% test coverage.
+ *
+ * @throws NamingException thrown because the host is always broken.
+ */
+ @Test
+ void testGetLdapContext() throws NamingException {
+ assertThrows(NamingException.class, () -> {
+ factory = new JndiLdapContextFactory();
+ //garbage URL to test that the context is being created, but fails:
+ String brokenHost = UUID.randomUUID().toString();
+ factory.setUrl("ldap://" + brokenHost + ":389");
+ factory.getLdapContext("foo", "bar");
+ });
+ }
+
+ @Test
+ void testAuthenticationMechanism() {
String mech = "MD5-DIGEST";
factory.setAuthenticationMechanism(mech);
assertEquals(mech, factory.getAuthenticationMechanism());
- }
-
- @Test
- public void testReferral() {
+ }
+
+ @Test
+ void testReferral() {
String referral = "throw";
factory.setReferral(referral);
assertEquals(referral, factory.getReferral());
- }
-
- @Test
- public void testGetContextFactoryClassName() {
+ }
+
+ @Test
+ void testGetContextFactoryClassName() {
assertEquals(JndiLdapContextFactory.DEFAULT_CONTEXT_FACTORY_CLASS_NAME, factory.getContextFactoryClassName());
- }
-
- @Test
- public void testSetEnvironmentPropertyNull() {
+ }
+
+ @Test
+ void testSetEnvironmentPropertyNull() {
factory.setAuthenticationMechanism("MD5-DIGEST");
factory.setAuthenticationMechanism(null);
assertNull(factory.getAuthenticationMechanism());
- }
-
- @Test
- public void testCustomEnvironment() {
+ }
+
+ @Test
+ void testCustomEnvironment() {
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
factory.setEnvironment(map);
assertEquals("bar", factory.getEnvironment().get("foo"));
- }
-
- @Test(expected = IllegalStateException.class)
- public void testGetLdapContextWithoutUrl() throws NamingException {
- factory.getLdapContext("foo", "bar");
- }
-
- @Test
- public void testGetLdapContextDefault() throws NamingException {
+ }
+
+ @Test
+ void testGetLdapContextWithoutUrl() throws NamingException {
+ assertThrows(IllegalStateException.class, () -> {
+ factory.getLdapContext("foo", "bar");
+ });
+ }
+
+ @Test
+ void testGetLdapContextDefault() throws NamingException {
factory = new JndiLdapContextFactory() {
@Override
protected LdapContext createLdapContext(Hashtable env) throws NamingException {
@@ -124,11 +126,11 @@ public class JndiLdapContextFactoryTest {
factory.setUrl("ldap://localhost:389");
factory.getLdapContext("foo", "bar");
- }
-
- @SuppressWarnings({"deprecation"})
- @Test
- public void testGetLdapContextStringArguments() throws NamingException {
+ }
+
+ @SuppressWarnings({"deprecation"})
+ @Test
+ void testGetLdapContextStringArguments() throws NamingException {
factory = new JndiLdapContextFactory() {
@Override
protected LdapContext createLdapContext(Hashtable env) throws NamingException {
@@ -143,10 +145,10 @@ public class JndiLdapContextFactoryTest {
factory.setUrl("ldap://localhost:389");
factory.getLdapContext("foo", "bar");
- }
-
- @Test
- public void testGetSystemLdapContext() throws NamingException {
+ }
+
+ @Test
+ void testGetSystemLdapContext() throws NamingException {
factory = new JndiLdapContextFactory() {
@Override
protected LdapContext createLdapContext(Hashtable env) throws NamingException {
@@ -163,10 +165,10 @@ public class JndiLdapContextFactoryTest {
factory.setSystemPassword("bar");
factory.setUrl("ldap://localhost:389");
factory.getSystemLdapContext();
- }
-
- @Test
- public void testGetSystemLdapContextPoolingDisabled() throws NamingException {
+ }
+
+ @Test
+ void testGetSystemLdapContextPoolingDisabled() throws NamingException {
factory = new JndiLdapContextFactory() {
@Override
protected LdapContext createLdapContext(Hashtable env) throws NamingException {
@@ -184,30 +186,38 @@ public class JndiLdapContextFactoryTest {
factory.setPoolingEnabled(false);
factory.setUrl("ldap://localhost:389");
factory.getSystemLdapContext();
- }
-
- @Test(expected = AuthenticationException.class)
- public void testEmptyStringCredentials() throws NamingException {
- factory.setUrl("ldap://localhost:389");
- factory.getLdapContext("jcoder", "");
- }
-
- @Test(expected = AuthenticationException.class)
- public void testEmptyCharArrayCredentials() throws NamingException {
- factory.setUrl("ldap://localhost:389");
- factory.getLdapContext("jcoder", new char[0]);
- }
-
- @Test(expected = AuthenticationException.class)
- public void testEmptyByteArrayCredentials() throws NamingException {
- factory.setUrl("ldap://localhost:389");
- factory.getLdapContext("jcoder", new byte[0]);
- }
-
- @Test(expected = AuthenticationException.class)
- public void testEmptyNullCredentials() throws NamingException {
- factory.setUrl("ldap://localhost:389");
- factory.getLdapContext("jcoder", null);
+ }
+
+ @Test
+ void testEmptyStringCredentials() throws NamingException {
+ assertThrows(AuthenticationException.class, () -> {
+ factory.setUrl("ldap://localhost:389");
+ factory.getLdapContext("jcoder", "");
+ });
+ }
+
+ @Test
+ void testEmptyCharArrayCredentials() throws NamingException {
+ assertThrows(AuthenticationException.class, () -> {
+ factory.setUrl("ldap://localhost:389");
+ factory.getLdapContext("jcoder", new char[0]);
+ });
+ }
+
+ @Test
+ void testEmptyByteArrayCredentials() throws NamingException {
+ assertThrows(AuthenticationException.class, () -> {
+ factory.setUrl("ldap://localhost:389");
+ factory.getLdapContext("jcoder", new byte[0]);
+ });
+ }
+
+ @Test
+ void testEmptyNullCredentials() throws NamingException {
+ assertThrows(AuthenticationException.class, () -> {
+ factory.setUrl("ldap://localhost:389");
+ factory.getLdapContext("jcoder", null);
+ });
}
diff --git a/core/src/test/java/org/apache/shiro/realm/ldap/JndiLdapRealmTest.java b/core/src/test/java/org/apache/shiro/realm/ldap/JndiLdapRealmTest.java
index b8a6b9412..80bae44e7 100644
--- a/core/src/test/java/org/apache/shiro/realm/ldap/JndiLdapRealmTest.java
+++ b/core/src/test/java/org/apache/shiro/realm/ldap/JndiLdapRealmTest.java
@@ -18,9 +18,10 @@
*/
package org.apache.shiro.realm.ldap;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Tests for the {@link JndiLdapRealm} class.
*
diff --git a/core/src/test/java/org/apache/shiro/realm/text/IniRealmTest.java b/core/src/test/java/org/apache/shiro/realm/text/IniRealmTest.java
index 78cca77d8..76430f172 100644
--- a/core/src/test/java/org/apache/shiro/realm/text/IniRealmTest.java
+++ b/core/src/test/java/org/apache/shiro/realm/text/IniRealmTest.java
@@ -21,9 +21,9 @@ package org.apache.shiro.realm.text;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.Ini;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for the {@link IniRealm} class.
@@ -33,22 +33,24 @@ import org.junit.Test;
public class IniRealmTest {
@Test
- public void testNullIni() {
+ void testNullIni() {
IniRealm realm = new IniRealm((Ini) null);
}
@Test
- public void testEmptyIni() {
+ void testEmptyIni() {
new IniRealm(new Ini());
}
- @Test(expected = IllegalStateException.class)
- public void testInitWithoutIniResource() {
- new IniRealm().init();
+ @Test
+ void testInitWithoutIniResource() {
+ assertThrows(IllegalStateException.class, () -> {
+ new IniRealm().init();
+ });
}
@Test
- public void testIniFile() {
+ void testIniFile() {
IniRealm realm = new IniRealm();
realm.setResourcePath("classpath:org/apache/shiro/realm/text/IniRealmTest.simple.ini");
realm.init();
@@ -60,7 +62,7 @@ public class IniRealmTest {
}
@Test
- public void testIniFileWithoutUsers() {
+ void testIniFileWithoutUsers() {
IniRealm realm = new IniRealm();
realm.setResourcePath("classpath:org/apache/shiro/realm/text/IniRealmTest.noUsers.ini");
realm.init();
diff --git a/core/src/test/java/org/apache/shiro/realm/text/TextConfigurationRealmTest.java b/core/src/test/java/org/apache/shiro/realm/text/TextConfigurationRealmTest.java
index cd11e7591..86d1cb4b8 100644
--- a/core/src/test/java/org/apache/shiro/realm/text/TextConfigurationRealmTest.java
+++ b/core/src/test/java/org/apache/shiro/realm/text/TextConfigurationRealmTest.java
@@ -21,12 +21,12 @@ package org.apache.shiro.realm.text;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.text.ParseException;
import java.util.Arrays;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class TextConfigurationRealmTest {
@@ -93,12 +93,12 @@ public class TextConfigurationRealmTest {
* Tests that roles and account can't be tested while the realm is being loaded.
*/
@Test
- public void testRoleAndUserAccount() throws InterruptedException {
+ void testRoleAndUserAccount() throws InterruptedException {
setUpForReadConfigurationTest();
executeTest(new Runnable() {
public void run() {
- assertTrue("role not found when it was expected", realm.roleExists("role1"));
- assertTrue("user not found when it was expected", realm.accountExists("user1"));
+ assertTrue(realm.roleExists("role1"), "role not found when it was expected");
+ assertTrue(realm.accountExists("user1"), "user not found when it was expected");
}
});
}
@@ -107,15 +107,15 @@ public class TextConfigurationRealmTest {
* Tests that roles can't be read while the realm is being loaded.
*/
@Test
- public void testHasRole() throws InterruptedException {
+ void testHasRole() throws InterruptedException {
setUpForReadConfigurationTest();
executeTest(new Runnable() {
public void run() {
PrincipalCollection principalCollection = new SimplePrincipalCollection("user1", "realm1");
- assertTrue("principal doesn't have role when it should",
- realm.hasRole(principalCollection, "role2"));
- assertTrue("principal doesn't have all roles when it should",
- realm.hasAllRoles(principalCollection, Arrays.asList(new String[]{"role1", "role2"})));
+ assertTrue(realm.hasRole(principalCollection, "role2"),
+ "principal doesn't have role when it should");
+ assertTrue(realm.hasAllRoles(principalCollection, Arrays.asList(new String[]{"role1", "role2"})),
+ "principal doesn't have all roles when it should");
}
});
}
@@ -124,7 +124,7 @@ public class TextConfigurationRealmTest {
* Tests that roles can't be checked while the realm is being loaded.
*/
@Test
- public void testCheckRole() throws InterruptedException {
+ void testCheckRole() throws InterruptedException {
setUpForReadConfigurationTest();
executeTest(new Runnable() {
public void run() {
@@ -142,7 +142,7 @@ public class TextConfigurationRealmTest {
* Tests that a principal's permissions can't be checked while the realm is being loaded.
*/
@Test
- public void testCheckPermission() throws InterruptedException {
+ void testCheckPermission() throws InterruptedException {
setUpForReadConfigurationTest();
executeTest(new Runnable() {
public void run() {
@@ -161,14 +161,14 @@ public class TextConfigurationRealmTest {
* Tests that a principal's permissions can't be checked while the realm is being loaded.
*/
@Test
- public void testIsPermitted() throws InterruptedException {
+ void testIsPermitted() throws InterruptedException {
setUpForReadConfigurationTest();
executeTest(new Runnable() {
public void run() {
PrincipalCollection principalCollection = new SimplePrincipalCollection("user1", "realm1");
- assertTrue("permission not permitted when it should be", realm.isPermitted(principalCollection, "role1_permission1"));
- assertTrue("permission not permitted when it should be",
- realm.isPermittedAll(principalCollection, new String[]{"role1_permission1", "role2_permission2"}));
+ assertTrue(realm.isPermitted(principalCollection, "role1_permission1"), "permission not permitted when it should be");
+ assertTrue(realm.isPermittedAll(principalCollection, new String[]{"role1_permission1", "role2_permission2"}),
+ "permission not permitted when it should be");
}
});
}
@@ -177,7 +177,7 @@ public class TextConfigurationRealmTest {
* Test that role definitions cannot be updated when a read thread holds the realm's lock.
*/
@Test
- public void testProcessRoleDefinitions() throws InterruptedException {
+ void testProcessRoleDefinitions() throws InterruptedException {
realm = new TestRealm() {
public void test(Thread runnable) throws InterruptedException {
// While the realm's lock is held by this thread role definitions cannot be processed
@@ -187,7 +187,7 @@ public class TextConfigurationRealmTest {
runnable.start();
Thread.sleep(500);
// No role until lock is released and role definitions are processed
- assertFalse("role exists when it shouldn't", realm.roleExists("role1"));
+ assertFalse(realm.roleExists("role1"), "role exists when it shouldn't");
} finally {
ROLES_LOCK.writeLock().unlock();
}
@@ -207,7 +207,7 @@ public class TextConfigurationRealmTest {
Thread testTask = new Thread(testThread);
realm.test(testTask);
testTask.join(500);
- assertTrue("role doesn't exist when it should", realm.roleExists("role1"));
+ assertTrue(realm.roleExists("role1"), "role doesn't exist when it should");
testThread.test();
}
@@ -215,7 +215,7 @@ public class TextConfigurationRealmTest {
* Test that user definitions cannot be updated when a read thread holds the realm's lock.
*/
@Test
- public void testProcessUserDefinitions() throws InterruptedException {
+ void testProcessUserDefinitions() throws InterruptedException {
realm = new TestRealm() {
public void test(Thread runnable) throws InterruptedException {
// While the realm's lock is held by this thread user definitions cannot be processed
@@ -225,7 +225,7 @@ public class TextConfigurationRealmTest {
runnable.start();
Thread.sleep(500);
// No account until lock is released and user definitions are processed
- assertFalse("account exists when it shouldn't", realm.accountExists("user1"));
+ assertFalse(realm.accountExists("user1"), "account exists when it shouldn't");
} finally {
USERS_LOCK.writeLock().unlock();
}
@@ -244,7 +244,7 @@ public class TextConfigurationRealmTest {
Thread testTask = new Thread(testThread);
realm.test(testTask);
testTask.join(500);
- assertTrue("account doesn't exist when it should", realm.accountExists("user1"));
+ assertTrue(realm.accountExists("user1"), "account doesn't exist when it should");
testThread.test();
}
diff --git a/core/src/test/java/org/apache/shiro/session/mgt/AbstractValidatingSessionManagerTest.java b/core/src/test/java/org/apache/shiro/session/mgt/AbstractValidatingSessionManagerTest.java
index 3700db33b..46662d80f 100644
--- a/core/src/test/java/org/apache/shiro/session/mgt/AbstractValidatingSessionManagerTest.java
+++ b/core/src/test/java/org/apache/shiro/session/mgt/AbstractValidatingSessionManagerTest.java
@@ -22,8 +22,8 @@ import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.session.SessionListenerAdapter;
-import org.apache.shiro.session.UnknownSessionException;
-import org.junit.Test;
+import org.apache.shiro.session.UnknownSessionException;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -32,19 +32,19 @@ import java.util.Collection;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.*;
-
+import static org.junit.jupiter.api.Assertions.*;
+
/**
* Unit tests for the {@link org.apache.shiro.session.mgt.AbstractValidatingSessionManager} class.
*/
-public class AbstractValidatingSessionManagerTest {
-
- /**
- * Tests that both SessionListeners are called and that invalid sessions are deleted by default.
- * Verifies <a href="https://issues.apache.org/jira/browse/SHIRO-199">SHIRO-199</a>.
- */
- @Test
- public void testValidateSessions() {
+public class AbstractValidatingSessionManagerTest {
+
+ /**
+ * Tests that both SessionListeners are called and that invalid sessions are deleted by default.
+ * Verifies <a href="https://issues.apache.org/jira/browse/SHIRO-199">SHIRO-199</a>.
+ */
+ @Test
+ void testValidateSessions() {
final SimpleSession validSession = new SimpleSession();
validSession.setId(1);
@@ -91,15 +91,15 @@ public class AbstractValidatingSessionManagerTest {
sessionManager.validateSessions();
assertEquals(1, expirationCount.intValue());
- }
-
-
- /**
- * Tests that no memory leak exists on invalid sessions: expired or stopped
- * Verifies <a href="https://issues.apache.org/jira/browse/SHIRO-399">SHIRO-399</a>.
- */
- @Test
- public void testNoMemoryLeakOnInvalidSessions() throws Exception {
+ }
+
+
+ /**
+ * Tests that no memory leak exists on invalid sessions: expired or stopped
+ * Verifies <a href="https://issues.apache.org/jira/browse/SHIRO-399">SHIRO-399</a>.
+ */
+ @Test
+ void testNoMemoryLeakOnInvalidSessions() throws Exception {
SessionListener sessionListener = new SessionListener() {
public void onStart(Session session) {
session.setAttribute("I love", "Romania");
diff --git a/core/src/test/java/org/apache/shiro/session/mgt/DefaultSessionManagerTest.java b/core/src/test/java/org/apache/shiro/session/mgt/DefaultSessionManagerTest.java
index 41875eadd..42554f2d9 100644
--- a/core/src/test/java/org/apache/shiro/session/mgt/DefaultSessionManagerTest.java
+++ b/core/src/test/java/org/apache/shiro/session/mgt/DefaultSessionManagerTest.java
@@ -27,14 +27,14 @@ import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.util.ThreadContext;
import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.UUID;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit test for the {@link DefaultSessionManager DefaultSessionManager} implementation.
@@ -43,13 +43,13 @@ public class DefaultSessionManagerTest {
DefaultSessionManager sm = null;
- @Before
+ @BeforeEach
public void setup() {
ThreadContext.remove();
sm = new DefaultSessionManager();
}
- @After
+ @AfterEach
public void tearDown() {
sm.destroy();
ThreadContext.remove();
@@ -64,7 +64,7 @@ public class DefaultSessionManagerTest {
}
@Test
- public void testGlobalTimeout() {
+ void testGlobalTimeout() {
long timeout = 1000;
sm.setGlobalSessionTimeout(timeout);
Session session = sm.start(null);
@@ -74,7 +74,7 @@ public class DefaultSessionManagerTest {
}
@Test
- public void testSessionListenerStartNotification() {
+ void testSessionListenerStartNotification() {
final boolean[] started = new boolean[1];
SessionListener listener = new SessionListenerAdapter() {
public void onStart(Session session) {
@@ -87,7 +87,7 @@ public class DefaultSessionManagerTest {
}
@Test
- public void testSessionListenerStopNotification() {
+ void testSessionListenerStopNotification() {
final boolean[] stopped = new boolean[1];
SessionListener listener = new SessionListenerAdapter() {
public void onStop(Session session) {
@@ -104,7 +104,7 @@ public class DefaultSessionManagerTest {
//Ensures that a session attribute can be accessed in the listener without
//causing a stack overflow exception.
@Test
- public void testSessionListenerStopNotificationWithReadAttribute() {
+ void testSessionListenerStopNotificationWithReadAttribute() {
final boolean[] stopped = new boolean[1];
final String[] value = new String[1];
SessionListener listener = new SessionListenerAdapter() {
@@ -124,7 +124,7 @@ public class DefaultSessionManagerTest {
}
@Test
- public void testSessionListenerExpiredNotification() {
+ void testSessionListenerExpiredNotification() {
final boolean[] expired = new boolean[1];
SessionListener listener = new SessionListenerAdapter() {
public void onExpiration(Session session) {
@@ -145,7 +145,7 @@ public class DefaultSessionManagerTest {
}
@Test
- public void testSessionDeleteOnExpiration() {
+ void testSessionDeleteOnExpiration() {
sm.setGlobalSessionTimeout(100);
SessionDAO sessionDAO = createMock(SessionDAO.class);
@@ -200,7 +200,7 @@ public class DefaultSessionManagerTest {
* Tests a bug introduced by SHIRO-443, where a custom sessionValidationScheduler would not be started.
*/
@Test
- public void testEnablingOfCustomSessionValidationScheduler() {
+ void testEnablingOfCustomSessionValidationScheduler() {
// using the default impl of sessionValidationScheduler, as the but effects any scheduler we set directly via
// sessionManager.setSessionValidationScheduler(), commonly used in INI configuration.
@@ -213,7 +213,7 @@ public class DefaultSessionManagerTest {
Session session = sessionManager.start(null);
// now sessionValidationScheduler should be enabled
- assertTrue("sessionValidationScheduler was not enabled", sessionValidationScheduler.isEnabled());
+ assertTrue(sessionValidationScheduler.isEnabled(), "sessionValidationScheduler was not enabled");
}
finally {
// cleanup after test
diff --git a/core/src/test/java/org/apache/shiro/session/mgt/DelegatingSessionTest.java b/core/src/test/java/org/apache/shiro/session/mgt/DelegatingSessionTest.java
index b28c4d46d..8df9bb22e 100644
--- a/core/src/test/java/org/apache/shiro/session/mgt/DelegatingSessionTest.java
+++ b/core/src/test/java/org/apache/shiro/session/mgt/DelegatingSessionTest.java
@@ -20,14 +20,14 @@ package org.apache.shiro.session.mgt;
import org.apache.shiro.session.ExpiredSessionException;
import org.apache.shiro.util.ThreadContext;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.Serializable;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Unit test for the {@link DelegatingSession} class.
@@ -37,14 +37,14 @@ public class DelegatingSessionTest {
DelegatingSession session = null;
DefaultSessionManager sm = null;
- @Before
+ @BeforeEach
public void setup() {
ThreadContext.remove();
sm = new DefaultSessionManager();
this.session = new DelegatingSession(sm, new DefaultSessionKey(sm.start(null).getId()));
}
- @After
+ @AfterEach
public void tearDown() {
sm.destroy();
ThreadContext.remove();
@@ -59,7 +59,7 @@ public class DelegatingSessionTest {
}
@Test
- public void testTimeout() {
+ void testTimeout() {
Serializable origId = session.getId();
assertEquals(session.getTimeout(), AbstractSessionManager.DEFAULT_GLOBAL_SESSION_TIMEOUT);
session.touch();
diff --git a/core/src/test/java/org/apache/shiro/session/mgt/ExecutorServiceSessionValidationSchedulerTest.java b/core/src/test/java/org/apache/shiro/session/mgt/ExecutorServiceSessionValidationSchedulerTest.java
index 8ae53a621..6694b18f5 100644
--- a/core/src/test/java/org/apache/shiro/session/mgt/ExecutorServiceSessionValidationSchedulerTest.java
+++ b/core/src/test/java/org/apache/shiro/session/mgt/ExecutorServiceSessionValidationSchedulerTest.java
@@ -19,17 +19,17 @@
package org.apache.shiro.session.mgt;
import org.apache.shiro.session.Session;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class ExecutorServiceSessionValidationSchedulerTest {
ExecutorServiceSessionValidationScheduler executorServiceSessionValidationScheduler;
DefaultSessionManager defaultSessionManager;
- @Before
+ @BeforeEach
public void setUp() {
defaultSessionManager = new DefaultSessionManager();
defaultSessionManager.setDeleteInvalidSessions(true);
@@ -41,40 +41,40 @@ public class ExecutorServiceSessionValidationSchedulerTest {
}
@Test
- public void timeoutSessionValidate() throws InterruptedException {
+ void timeoutSessionValidate() throws InterruptedException {
Session session = new SimpleSession();
session.setTimeout(2000L);
defaultSessionManager.create(session);
Thread.sleep(5000L);
- Assert.assertTrue(defaultSessionManager.getActiveSessions().isEmpty());
- Assert.assertTrue(executorServiceSessionValidationScheduler.isEnabled());
+ Assertions.assertTrue(defaultSessionManager.getActiveSessions().isEmpty());
+ Assertions.assertTrue(executorServiceSessionValidationScheduler.isEnabled());
}
@Test
- public void stopSessionValidate() throws InterruptedException {
+ void stopSessionValidate() throws InterruptedException {
Session session = new SimpleSession();
session.setTimeout(10000L);
defaultSessionManager.create(session);
Thread.sleep(1000L);
session.stop();
Thread.sleep(3000L);
- Assert.assertTrue(defaultSessionManager.getActiveSessions().isEmpty());
- Assert.assertTrue(executorServiceSessionValidationScheduler.isEnabled());
+ Assertions.assertTrue(defaultSessionManager.getActiveSessions().isEmpty());
+ Assertions.assertTrue(executorServiceSessionValidationScheduler.isEnabled());
}
@Test
- public void enableSessionValidation() throws InterruptedException {
- Assert.assertTrue(executorServiceSessionValidationScheduler.isEnabled());
+ void enableSessionValidation() throws InterruptedException {
+ Assertions.assertTrue(executorServiceSessionValidationScheduler.isEnabled());
executorServiceSessionValidationScheduler.disableSessionValidation();
Thread.sleep(2000L);
- Assert.assertFalse(executorServiceSessionValidationScheduler.isEnabled());
+ Assertions.assertFalse(executorServiceSessionValidationScheduler.isEnabled());
executorServiceSessionValidationScheduler.enableSessionValidation();
Thread.sleep(2000L);
- Assert.assertTrue(executorServiceSessionValidationScheduler.isEnabled());
+ Assertions.assertTrue(executorServiceSessionValidationScheduler.isEnabled());
}
@Test
- public void threadException() throws InterruptedException {
+ void threadException() throws InterruptedException {
Session session = new SimpleSession();
defaultSessionManager = new FakeDefaultSessionManager();
defaultSessionManager.setDeleteInvalidSessions(true);
@@ -87,11 +87,11 @@ public class ExecutorServiceSessionValidationSchedulerTest {
Thread.sleep(2000L);
session.stop();
Thread.sleep(2000L);
- Assert.assertFalse(defaultSessionManager.getActiveSessions().isEmpty());
- Assert.assertTrue(executorServiceSessionValidationScheduler.isEnabled());
+ Assertions.assertFalse(defaultSessionManager.getActiveSessions().isEmpty());
+ Assertions.assertTrue(executorServiceSessionValidationScheduler.isEnabled());
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
executorServiceSessionValidationScheduler.disableSessionValidation();
}
diff --git a/core/src/test/java/org/apache/shiro/session/mgt/SimpleSessionTest.java b/core/src/test/java/org/apache/shiro/session/mgt/SimpleSessionTest.java
index db7344874..81c9675ad 100644
--- a/core/src/test/java/org/apache/shiro/session/mgt/SimpleSessionTest.java
+++ b/core/src/test/java/org/apache/shiro/session/mgt/SimpleSessionTest.java
@@ -18,18 +18,18 @@
*/
package org.apache.shiro.session.mgt;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.Date;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-public class SimpleSessionTest {
-
- @Test
- public void testDefaultSerialization() throws Exception {
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class SimpleSessionTest {
+
+ @Test
+ void testDefaultSerialization() throws Exception {
SimpleSession session = new SimpleSession();
long timeout = session.getTimeout();
@@ -41,16 +41,16 @@ public class SimpleSessionTest {
assertEquals(timeout, deserialized.getTimeout());
assertEquals(start, deserialized.getStartTimestamp());
assertEquals(lastAccess, deserialized.getLastAccessTime());
- }
-
- @Test
- public void serializeHost() throws IOException, ClassNotFoundException {
+ }
+
+ @Test
+ void serializeHost() throws IOException, ClassNotFoundException {
SimpleSession session = new SimpleSession("localhost");
assertEquals("localhost", serializeAndDeserialize(session).getHost());
- }
-
- @Test
- public void serializeExpired() throws IOException, ClassNotFoundException {
+ }
+
+ @Test
+ void serializeExpired() throws IOException, ClassNotFoundException {
SimpleSession session = new SimpleSession();
session.setExpired(true);
assertTrue(serializeAndDeserialize(session).isExpired());
diff --git a/core/src/test/java/org/apache/shiro/subject/DelegatingSubjectTest.java b/core/src/test/java/org/apache/shiro/subject/DelegatingSubjectTest.java
index 847aab629..748e0507b 100644
--- a/core/src/test/java/org/apache/shiro/subject/DelegatingSubjectTest.java
+++ b/core/src/test/java/org/apache/shiro/subject/DelegatingSubjectTest.java
@@ -28,15 +28,15 @@ import org.apache.shiro.session.Session;
import org.apache.shiro.subject.support.DelegatingSubject;
import org.apache.shiro.lang.util.LifecycleUtils;
import org.apache.shiro.util.ThreadContext;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.Serializable;
import java.util.concurrent.Callable;
import static org.easymock.EasyMock.createNiceMock;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -44,18 +44,18 @@ import static org.junit.Assert.*;
*/
public class DelegatingSubjectTest {
- @Before
+ @BeforeEach
public void setup() {
ThreadContext.remove();
}
- @After
+ @AfterEach
public void tearDown() {
ThreadContext.remove();
}
@Test
- public void testSessionStopThenStart() {
+ void testSessionStopThenStart() {
String key = "testKey";
String value = "testValue";
DefaultSecurityManager sm = new DefaultSecurityManager();
@@ -83,7 +83,7 @@ public class DelegatingSubjectTest {
}
@Test
- public void testExecuteCallable() {
+ void testExecuteCallable() {
String username = "jsmith";
@@ -113,7 +113,7 @@ public class DelegatingSubjectTest {
}
@Test
- public void testExecuteRunnable() {
+ void testExecuteRunnable() {
String username = "jsmith";
@@ -139,7 +139,7 @@ public class DelegatingSubjectTest {
}
@Test
- public void testRunAs() {
+ void testRunAs() {
Ini ini = new Ini();
Ini.Section users = ini.addSection("users");
@@ -218,7 +218,7 @@ public class DelegatingSubjectTest {
}
@Test
- public void testToString() {
+ void testToString() {
// given
String username = "jsmith";
@@ -233,8 +233,8 @@ public class DelegatingSubjectTest {
// then
final Session session = sourceSubject.getSession(true);
String sessionId = (String) session.getId();
- assertFalse("toString must not leak sessionId", subjectToString.contains(sessionId));
- assertFalse("toString must not leak host", subjectToString.contains(hostname));
+ assertFalse(subjectToString.contains(sessionId), "toString must not leak sessionId");
+ assertFalse(subjectToString.contains(hostname), "toString must not leak host");
}
}
diff --git a/core/src/test/java/org/apache/shiro/subject/SimplePrincipalCollectionTest.java b/core/src/test/java/org/apache/shiro/subject/SimplePrincipalCollectionTest.java
index 668ae5b1e..5aec0f635 100644
--- a/core/src/test/java/org/apache/shiro/subject/SimplePrincipalCollectionTest.java
+++ b/core/src/test/java/org/apache/shiro/subject/SimplePrincipalCollectionTest.java
@@ -18,7 +18,7 @@
*/
package org.apache.shiro.subject;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -30,7 +30,7 @@ public class SimplePrincipalCollectionTest {
private static final Logger LOG = LoggerFactory.getLogger(SimplePrincipalCollectionTest.class);
@Test
- public void multiplePrincipalsTest()
+ void multiplePrincipalsTest()
{
SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
principalCollection.add("frank", "realm1");
diff --git a/core/src/test/java/org/apache/shiro/test/AbstractShiroTest.java b/core/src/test/java/org/apache/shiro/test/AbstractShiroTest.java
index 0a3f6421f..93944074b 100644
--- a/core/src/test/java/org/apache/shiro/test/AbstractShiroTest.java
+++ b/core/src/test/java/org/apache/shiro/test/AbstractShiroTest.java
@@ -24,9 +24,9 @@ import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.SubjectThreadState;
import org.apache.shiro.lang.util.LifecycleUtils;
-import org.apache.shiro.util.ThreadState;
-import org.junit.AfterClass;
-
+import org.apache.shiro.util.ThreadState;
+import org.junit.jupiter.api.AfterAll;
+
/**
* Abstract test case showing how to use Shiro in testing environments.
*
@@ -80,7 +80,7 @@ public abstract class AbstractShiroTest {
return SecurityUtils.getSecurityManager();
}
- @AfterClass
+ @AfterAll
public static void tearDownShiro() {
doClearSubject();
try {
diff --git a/core/src/test/java/org/apache/shiro/test/ExampleShiroIntegrationTest.java b/core/src/test/java/org/apache/shiro/test/ExampleShiroIntegrationTest.java
index 8b106fbf1..c01b9b80a 100644
--- a/core/src/test/java/org/apache/shiro/test/ExampleShiroIntegrationTest.java
+++ b/core/src/test/java/org/apache/shiro/test/ExampleShiroIntegrationTest.java
@@ -21,11 +21,11 @@ package org.apache.shiro.test;
import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
-import org.apache.shiro.lang.util.Factory;
-import org.junit.After;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
+import org.apache.shiro.lang.util.Factory;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
/**
* Simple example test class to be used to show how one might write Shiro-compatible unit tests.
*
@@ -33,17 +33,17 @@ import org.junit.Test;
*/
public class ExampleShiroIntegrationTest extends AbstractShiroTest {
- @BeforeClass
+ @BeforeAll
public static void beforeClass() {
//0. Build and set the SecurityManager used to build Subject instances used in your tests
// This typically only needs to be done once per class if your shiro.ini doesn't change,
// otherwise, you'll need to do this logic in each test that is different
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:test.shiro.ini");
setSecurityManager(factory.getInstance());
- }
-
- @Test
- public void testSimple() {
+ }
+
+ @Test
+ void testSimple() {
//1. Build the Subject instance for the test to run:
Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
@@ -55,7 +55,7 @@ public class ExampleShiroIntegrationTest extends AbstractShiroTest {
//call stack) will work properly.
}
- @After
+ @AfterEach
public void tearDownSubject() {
//3. Unbind the subject from the current thread:
clearSubject();
diff --git a/core/src/test/java/org/apache/shiro/test/ExampleShiroUnitTest.java b/core/src/test/java/org/apache/shiro/test/ExampleShiroUnitTest.java
index d9dd47376..806431f3a 100644
--- a/core/src/test/java/org/apache/shiro/test/ExampleShiroUnitTest.java
+++ b/core/src/test/java/org/apache/shiro/test/ExampleShiroUnitTest.java
@@ -19,8 +19,8 @@
package org.apache.shiro.test;
import org.apache.shiro.subject.Subject;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
@@ -33,7 +33,7 @@ import static org.easymock.EasyMock.expect;
public class ExampleShiroUnitTest extends AbstractShiroTest {
@Test
- public void testSimple() {
+ void testSimple() {
//1. Create a mock Subject instance for the test to run
// (for example, as an authenticated Subject):
Subject subjectUnderTest = createNiceMock(Subject.class);
@@ -48,7 +48,7 @@ public class ExampleShiroUnitTest extends AbstractShiroTest {
//call stack) will work properly.
}
- @After
+ @AfterEach
public void tearDownSubject() {
//3. Unbind the subject from the current thread:
clearSubject();
diff --git a/core/src/test/java/org/apache/shiro/util/AntPathMatcherTests.java b/core/src/test/java/org/apache/shiro/util/AntPathMatcherTests.java
index e1c62919b..12046c30a 100644
--- a/core/src/test/java/org/apache/shiro/util/AntPathMatcherTests.java
+++ b/core/src/test/java/org/apache/shiro/util/AntPathMatcherTests.java
@@ -19,11 +19,9 @@
package org.apache.shiro.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for {@link AntPathMatcher}.
@@ -33,9 +31,9 @@ import static org.junit.Assert.assertFalse;
public class AntPathMatcherTests {
private final AntPathMatcher pathMatcher = new AntPathMatcher();
-
+
@Test
- public void match() {
+ void match() {
// test exact matching
assertTrue(pathMatcher.match("test", "test"));
assertTrue(pathMatcher.match("/test", "/test"));
@@ -121,14 +119,14 @@ public class AntPathMatcherTests {
}
@Test
- public void matchWithNullPath() {
+ void matchWithNullPath() {
assertFalse(pathMatcher.match("/test", null));
assertFalse(pathMatcher.match("/", null));
assertFalse(pathMatcher.match(null, null));
}
@Test
- public void matchStart() {
+ void matchStart() {
// test exact matching
assertTrue(pathMatcher.matchStart("test", "test"));
assertTrue(pathMatcher.matchStart("/test", "/test"));
@@ -215,7 +213,7 @@ public class AntPathMatcherTests {
}
@Test
- public void uniqueDelimiter() {
+ void uniqueDelimiter() {
pathMatcher.setPathSeparator(".");
// test exact matching
@@ -277,7 +275,7 @@ public class AntPathMatcherTests {
}
@Test
- public void extractPathWithinPattern() throws Exception {
+ void extractPathWithinPattern() throws Exception {
assertEquals(pathMatcher.extractPathWithinPattern("/docs/commit.html", "/docs/commit.html"), "");
assertEquals(pathMatcher.extractPathWithinPattern("/docs/*", "/docs/cvs/commit"), "cvs/commit");
@@ -302,13 +300,13 @@ public class AntPathMatcherTests {
}
@Test
- public void spaceInTokens() {
+ void spaceInTokens() {
assertTrue(pathMatcher.match("/group/sales/members", "/group/sales/members"));
assertFalse(pathMatcher.match("/group/sales/members", "/Group/ sales/Members"));
}
@Test
- public void isPattern() {
+ void isPattern() {
assertTrue(pathMatcher.isPattern("/test/*"));
assertTrue(pathMatcher.isPattern("/test/**/name"));
assertTrue(pathMatcher.isPattern("/test?"));
@@ -319,12 +317,12 @@ public class AntPathMatcherTests {
}
@Test
- public void matches() {
+ void matches() {
assertTrue(pathMatcher.matches("/foo/*", "/foo/"));
}
@Test
- public void isPatternWithNullPath() {
+ void isPatternWithNullPath() {
assertFalse(pathMatcher.isPattern(null));
}
}
\ No newline at end of file
diff --git a/core/src/test/java/org/apache/shiro/util/RegExPatternMatcherTest.java b/core/src/test/java/org/apache/shiro/util/RegExPatternMatcherTest.java
index dc42368de..9bf0315f3 100644
--- a/core/src/test/java/org/apache/shiro/util/RegExPatternMatcherTest.java
+++ b/core/src/test/java/org/apache/shiro/util/RegExPatternMatcherTest.java
@@ -18,8 +18,9 @@
*/
package org.apache.shiro.util;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for the {@link RegExPatternMatcher}.
@@ -29,29 +30,29 @@ import static org.junit.Assert.*;
public class RegExPatternMatcherTest {
@Test
- public void testSimplePattern() {
+ void testSimplePattern() {
assertPatternMatch("a*b", "aaaaaaab");
}
@Test
- public void testMatchesWithCarriageReturn() {
+ void testMatchesWithCarriageReturn() {
assertPatternMatch(".*", "/blah\n");
}
@Test
- public void testMatchesWithLineFeed() {
+ void testMatchesWithLineFeed() {
assertPatternMatch(".*", "/blah\r");
}
@Test
- public void testCaseInsensitive() {
+ void testCaseInsensitive() {
RegExPatternMatcher pm = new RegExPatternMatcher();
pm.setCaseInsensitive(true);
assertPatternMatch("/blah", "/BlaH", pm);
}
@Test
- public void testCaseSensitive() {
+ void testCaseSensitive() {
assertPatternNotMatch("/blah", "/BlaH");
}
@@ -60,7 +61,7 @@ public class RegExPatternMatcherTest {
}
private void assertPatternMatch(String pattern, String path, PatternMatcher pm) {
- assertTrue("Expected path '" + path + "' to match pattern '" + pattern + "'" , pm.matches(pattern, path));
+ assertTrue(pm.matches(pattern, path), "Expected path '" + path + "' to match pattern '" + pattern + "'" );
}
private void assertPatternNotMatch(String pattern, String path) {
@@ -68,6 +69,6 @@ public class RegExPatternMatcherTest {
}
private void assertPatternNotMatch(String pattern, String path, PatternMatcher pm) {
- assertFalse("Expected path '" + path + "' to NOT match pattern '" + pattern + "'" , pm.matches(pattern, path));
+ assertFalse(pm.matches(pattern, path), "Expected path '" + path + "' to NOT match pattern '" + pattern + "'" );
}
}
diff --git a/core/src/test/java/org/apache/shiro/util/StringUtilsTest.java b/core/src/test/java/org/apache/shiro/util/StringUtilsTest.java
index e6c447a96..66bc89491 100644
--- a/core/src/test/java/org/apache/shiro/util/StringUtilsTest.java
+++ b/core/src/test/java/org/apache/shiro/util/StringUtilsTest.java
@@ -18,10 +18,10 @@
*/
package org.apache.shiro.util;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import org.apache.shiro.lang.util.StringUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
@@ -30,14 +30,14 @@ import org.junit.Test;
public class StringUtilsTest {
@Test
- public void splitWithNullInput() {
+ void splitWithNullInput() {
String line = null;
String[] split = StringUtils.split(line);
assertNull(split);
}
@Test
- public void splitWithCommas() {
+ void splitWithCommas() {
String line = "shall,we,play,a,game?";
String[] split = StringUtils.split(line);
assertNotNull(split);
@@ -50,7 +50,7 @@ public class StringUtilsTest {
}
@Test
- public void splitWithCommasAndSpaces() {
+ void splitWithCommasAndSpaces() {
String line = "shall,we , play, a,game?";
String[] split = StringUtils.split(line);
assertNotNull(split);
@@ -63,7 +63,7 @@ public class StringUtilsTest {
}
@Test
- public void splitWithQuotedCommasAndSpaces() {
+ void splitWithQuotedCommasAndSpaces() {
String line = "shall, \"we, play\", a, game?";
String[] split = StringUtils.split(line);
assertNotNull(split);
@@ -75,7 +75,7 @@ public class StringUtilsTest {
}
@Test
- public void splitWithQuotedCommasAndSpacesAndDifferentQuoteChars() {
+ void splitWithQuotedCommasAndSpacesAndDifferentQuoteChars() {
String line = "authc, test[blah], test[1,2,3], test[]";
String[] split = StringUtils.split(line, ',', '[', ']', false, true);
assertNotNull(split);
@@ -87,7 +87,7 @@ public class StringUtilsTest {
}
@Test
- public void splitWithQuotedCommasAndSpacesAndDifferentQuoteCharsWhileRetainingQuotes() {
+ void splitWithQuotedCommasAndSpacesAndDifferentQuoteCharsWhileRetainingQuotes() {
String line = "authc, test[blah], test[1,2,3], test[]";
String[] split = StringUtils.split(line, ',', '[', ']', true, true);
assertNotNull(split);
@@ -99,7 +99,7 @@ public class StringUtilsTest {
}
@Test
- public void splitTestWithQuotedCommas() {
+ void splitTestWithQuotedCommas() {
String line = "authc, test[blah], test[\"1,2,3\"], test[]";
String[] split = StringUtils.split(line);
assertNotNull(split);
@@ -111,7 +111,7 @@ public class StringUtilsTest {
}
@Test
- public void splitWithQuotedCommasAndSpacesAndEscapedQuotes() {
+ void splitWithQuotedCommasAndSpacesAndEscapedQuotes() {
String line = "shall, \"\"\"we, play\", a, \"\"\"game?";
String[] split = StringUtils.split(line);
assertNotNull(split);
diff --git a/integration-tests/guice3/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java b/integration-tests/guice3/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java
index 96dbbab50..2a259671a 100644
--- a/integration-tests/guice3/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java
+++ b/integration-tests/guice3/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java
@@ -27,15 +27,15 @@ import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.MalformedURLException;
public class ContainerIntegrationIT extends AbstractContainerIT {
- @Before
+ @BeforeEach
public void logOut() throws IOException {
// Make sure we are logged out
final HtmlPage homePage = webClient.getPage(getBaseUri());
@@ -48,7 +48,7 @@ public class ContainerIntegrationIT extends AbstractContainerIT {
}
@Test
- public void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
+ void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
HtmlPage page = webClient.getPage(getBaseUri() + "login.jsp");
HtmlForm form = page.getFormByName("loginform");
@@ -60,7 +60,7 @@ public class ContainerIntegrationIT extends AbstractContainerIT {
}
@Test
- public void logInAndRememberMe() throws Exception {
+ void logInAndRememberMe() throws Exception {
HtmlPage page = webClient.getPage(getBaseUri() + "login.jsp");
HtmlForm form = page.getFormByName("loginform");
form.<HtmlInput>getInputByName("username").setValueAttribute("root");
diff --git a/integration-tests/guice4/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java b/integration-tests/guice4/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java
index 96dbbab50..2a259671a 100644
--- a/integration-tests/guice4/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java
+++ b/integration-tests/guice4/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java
@@ -27,15 +27,15 @@ import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.MalformedURLException;
public class ContainerIntegrationIT extends AbstractContainerIT {
- @Before
+ @BeforeEach
public void logOut() throws IOException {
// Make sure we are logged out
final HtmlPage homePage = webClient.getPage(getBaseUri());
@@ -48,7 +48,7 @@ public class ContainerIntegrationIT extends AbstractContainerIT {
}
@Test
- public void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
+ void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
HtmlPage page = webClient.getPage(getBaseUri() + "login.jsp");
HtmlForm form = page.getFormByName("loginform");
@@ -60,7 +60,7 @@ public class ContainerIntegrationIT extends AbstractContainerIT {
}
@Test
- public void logInAndRememberMe() throws Exception {
+ void logInAndRememberMe() throws Exception {
HtmlPage page = webClient.getPage(getBaseUri() + "login.jsp");
HtmlForm form = page.getFormByName("loginform");
form.<HtmlInput>getInputByName("username").setValueAttribute("root");
diff --git a/integration-tests/support/pom.xml b/integration-tests/support/pom.xml
index 0595de9e9..177d695fa 100644
--- a/integration-tests/support/pom.xml
+++ b/integration-tests/support/pom.xml
@@ -115,9 +115,8 @@
</exclusions>
</dependency>
<dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <version>${junit.version}</version>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
<scope>compile</scope>
</dependency>
diff --git a/integration-tests/support/src/main/java/org/apache/shiro/testing/web/AbstractContainerIT.java b/integration-tests/support/src/main/java/org/apache/shiro/testing/web/AbstractContainerIT.java
index fe54c0e2e..87e16aa5d 100644
--- a/integration-tests/support/src/main/java/org/apache/shiro/testing/web/AbstractContainerIT.java
+++ b/integration-tests/support/src/main/java/org/apache/shiro/testing/web/AbstractContainerIT.java
@@ -40,9 +40,9 @@ import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.webapp.WebXmlConfiguration;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
import java.io.File;
import java.io.FilenameFilter;
@@ -56,8 +56,8 @@ import java.nio.file.StandardCopyOption;
import static com.github.mjeanroy.junit.servers.commons.Strings.isNotBlank;
import static org.eclipse.jetty.util.resource.Resource.newResource;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public abstract class AbstractContainerIT {
@@ -70,7 +70,7 @@ public abstract class AbstractContainerIT {
protected static final File TEST_KEYSTORE_PATH = setupKeyStore();
protected static final String TEST_KEYSTORE_PASSWORD = "password";
- @BeforeClass
+ @BeforeAll
public static void startContainer() throws Exception {
EmbeddedJettyConfiguration config = EmbeddedJettyConfiguration.builder()
@@ -169,7 +169,7 @@ public abstract class AbstractContainerIT {
}
});
- assertEquals("Expected only one war file in target directory, run 'mvn clean' and try again", 1, warFiles.length);
+ assertEquals(1, warFiles.length, "Expected only one war file in target directory, run 'mvn clean' and try again");
return warFiles[0].getAbsolutePath().replaceFirst("\\.war$", "");
}
@@ -182,12 +182,12 @@ public abstract class AbstractContainerIT {
return "Basic " + authorizationHeader;
}
- @Before
+ @BeforeEach
public void beforeTest() {
webClient.getOptions().setThrowExceptionOnFailingStatusCode(true);
}
- @AfterClass
+ @AfterAll
public static void stopContainer() {
if (jetty != null) {
jetty.stop();
diff --git a/pom.xml b/pom.xml
index cd9db33e2..a5af5687d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -450,9 +450,9 @@
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.14.0</version>
<configuration>
- <source>${maven.compiler.source}</source>
- <target>${maven.compiler.target}</target>
- <complianceLevel>${maven.compiler.target}</complianceLevel>
+ <source>${maven.compiler.release}</source>
+ <target>${maven.compiler.release}</target>
+ <complianceLevel>${maven.compiler.release}</complianceLevel>
<showWeaveInfo>true</showWeaveInfo>
</configuration>
<executions>
@@ -852,8 +852,8 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
diff --git a/samples/aspectj/src/test/java/org/apache/shiro/samples/aspectj/bank/SecureBankServiceTest.java b/samples/aspectj/src/test/java/org/apache/shiro/samples/aspectj/bank/SecureBankServiceTest.java
index 9b35bbb43..123f631c3 100644
--- a/samples/aspectj/src/test/java/org/apache/shiro/samples/aspectj/bank/SecureBankServiceTest.java
+++ b/samples/aspectj/src/test/java/org/apache/shiro/samples/aspectj/bank/SecureBankServiceTest.java
@@ -25,22 +25,19 @@ import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.lang.util.Factory;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
public class SecureBankServiceTest {
private static Logger logger = LoggerFactory.getLogger(SecureBankServiceTest.class);
private static SecureBankService service;
private static int testCounter;
- @BeforeClass
+ @BeforeAll
public static void setUpClass() throws Exception {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiroBankServiceTest.ini");
SecurityManager securityManager = factory.getInstance();
@@ -50,7 +47,7 @@ public class SecureBankServiceTest {
service.start();
}
- @AfterClass
+ @AfterAll
public static void tearDownClass() {
if (service != null) {
service.dispose();
@@ -59,13 +56,13 @@ public class SecureBankServiceTest {
private Subject _subject;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
logger.info("\n\n#########################\n### STARTING TEST CASE " + (++testCounter) + "\n");
Thread.sleep(50);
}
- @After
+ @AfterEach
public void tearDown() {
if (_subject != null) {
_subject.logout();
@@ -97,20 +94,20 @@ public class SecureBankServiceTest {
}
@Test
- public void testCreateAccount() throws Exception {
+ void testCreateAccount() throws Exception {
loginAsUser();
createAndValidateAccountFor("Bob Smith");
}
@Test
- public void testDepositInto_singleTx() throws Exception {
+ void testDepositInto_singleTx() throws Exception {
loginAsUser();
long accountId = createAndValidateAccountFor("Joe Smith");
makeDepositAndValidateAccount(accountId, 250, "Joe Smith");
}
@Test
- public void testDepositInto_multiTxs() throws Exception {
+ void testDepositInto_multiTxs() throws Exception {
loginAsUser();
long accountId = createAndValidateAccountFor("Everett Smith");
makeDepositAndValidateAccount(accountId, 50, "Everett Smith");
@@ -119,23 +116,27 @@ public class SecureBankServiceTest {
assertAccount("Everett Smith", true, 435, 3, accountId);
}
- @Test(expected = NotEnoughFundsException.class)
- public void testWithdrawFrom_emptyAccount() throws Exception {
- loginAsUser();
- long accountId = createAndValidateAccountFor("Wally Smith");
- service.withdrawFrom(accountId, 100);
+ @Test
+ void testWithdrawFrom_emptyAccount() throws Exception {
+ assertThrows(NotEnoughFundsException.class, () -> {
+ loginAsUser();
+ long accountId = createAndValidateAccountFor("Wally Smith");
+ service.withdrawFrom(accountId, 100);
+ });
}
- @Test(expected = NotEnoughFundsException.class)
- public void testWithdrawFrom_notEnoughFunds() throws Exception {
- loginAsUser();
- long accountId = createAndValidateAccountFor("Frank Smith");
- makeDepositAndValidateAccount(accountId, 50, "Frank Smith");
- service.withdrawFrom(accountId, 100);
+ @Test
+ void testWithdrawFrom_notEnoughFunds() throws Exception {
+ assertThrows(NotEnoughFundsException.class, () -> {
+ loginAsUser();
+ long accountId = createAndValidateAccountFor("Frank Smith");
+ makeDepositAndValidateAccount(accountId, 50, "Frank Smith");
+ service.withdrawFrom(accountId, 100);
+ });
}
@Test
- public void testWithdrawFrom_singleTx() throws Exception {
+ void testWithdrawFrom_singleTx() throws Exception {
loginAsUser();
long accountId = createAndValidateAccountFor("Al Smith");
makeDepositAndValidateAccount(accountId, 500, "Al Smith");
@@ -144,7 +145,7 @@ public class SecureBankServiceTest {
}
@Test
- public void testWithdrawFrom_manyTxs() throws Exception {
+ void testWithdrawFrom_manyTxs() throws Exception {
loginAsUser();
long accountId = createAndValidateAccountFor("Zoe Smith");
makeDepositAndValidateAccount(accountId, 500, "Zoe Smith");
@@ -155,7 +156,7 @@ public class SecureBankServiceTest {
}
@Test
- public void testWithdrawFrom_upToZero() throws Exception {
+ void testWithdrawFrom_upToZero() throws Exception {
loginAsUser();
long accountId = createAndValidateAccountFor("Zoe Smith");
makeDepositAndValidateAccount(accountId, 500, "Zoe Smith");
@@ -164,19 +165,19 @@ public class SecureBankServiceTest {
}
@Test
- public void testCloseAccount_zeroBalance() throws Exception {
+ void testCloseAccount_zeroBalance() throws Exception {
loginAsUser();
long accountId = createAndValidateAccountFor("Chris Smith");
logoutCurrentSubject();
loginAsSuperviser();
double closingBalance = service.closeAccount(accountId);
- Assert.assertEquals(0, (int)closingBalance);
+ Assertions.assertEquals(0, (int)closingBalance);
assertAccount("Chris Smith", false, 0, 1, accountId);
}
@Test
- public void testCloseAccount_withBalance() throws Exception {
+ void testCloseAccount_withBalance() throws Exception {
loginAsUser();
long accountId = createAndValidateAccountFor("Gerry Smith");
makeDepositAndValidateAccount(accountId, 385, "Gerry Smith");
@@ -184,28 +185,32 @@ public class SecureBankServiceTest {
logoutCurrentSubject();
loginAsSuperviser();
double closingBalance = service.closeAccount(accountId);
- Assert.assertEquals(385, (int)closingBalance);
+ Assertions.assertEquals(385, (int)closingBalance);
assertAccount("Gerry Smith", false, 0, 2, accountId);
}
- @Test(expected = InactiveAccountException.class)
- public void testCloseAccount_alreadyClosed() throws Exception {
- loginAsUser();
- long accountId = createAndValidateAccountFor("Chris Smith");
+ @Test
+ void testCloseAccount_alreadyClosed() throws Exception {
+ assertThrows(InactiveAccountException.class, () -> {
+ loginAsUser();
+ long accountId = createAndValidateAccountFor("Chris Smith");
- logoutCurrentSubject();
- loginAsSuperviser();
- double closingBalance = service.closeAccount(accountId);
- Assert.assertEquals(0, (int)closingBalance);
- assertAccount("Chris Smith", false, 0, 1, accountId);
- service.closeAccount(accountId);
+ logoutCurrentSubject();
+ loginAsSuperviser();
+ double closingBalance = service.closeAccount(accountId);
+ Assertions.assertEquals(0, (int) closingBalance);
+ assertAccount("Chris Smith", false, 0, 1, accountId);
+ service.closeAccount(accountId);
+ });
}
- @Test(expected = UnauthorizedException.class)
- public void testCloseAccount_unauthorizedAttempt() throws Exception {
- loginAsUser();
- long accountId = createAndValidateAccountFor("Chris Smith");
- service.closeAccount(accountId);
+ @Test
+ void testCloseAccount_unauthorizedAttempt() throws Exception {
+ assertThrows(UnauthorizedException.class, () -> {
+ loginAsUser();
+ long accountId = createAndValidateAccountFor("Chris Smith");
+ service.closeAccount(accountId);
+ });
}
protected long createAndValidateAccountFor(String anOwner) throws Exception {
@@ -218,7 +223,7 @@ public class SecureBankServiceTest {
double previousBalance = service.getBalanceOf(anAccountId);
int previousTxCount = service.getTxHistoryFor(anAccountId).length;
double newBalance = service.depositInto(anAccountId, anAmount);
- Assert.assertEquals((int)previousBalance + anAmount, (int)newBalance);
+ Assertions.assertEquals((int)previousBalance + anAmount, (int)newBalance);
assertAccount(eOwnerName, true, (int)newBalance, 1 + previousTxCount, anAccountId);
return newBalance;
}
@@ -227,16 +232,16 @@ public class SecureBankServiceTest {
double previousBalance = service.getBalanceOf(anAccountId);
int previousTxCount = service.getTxHistoryFor(anAccountId).length;
double newBalance = service.withdrawFrom(anAccountId, anAmount);
- Assert.assertEquals((int)previousBalance - anAmount, (int)newBalance);
+ Assertions.assertEquals((int)previousBalance - anAmount, (int)newBalance);
assertAccount(eOwnerName, true, (int)newBalance, 1 + previousTxCount, anAccountId);
return newBalance;
}
public static void assertAccount(String eOwnerName, boolean eIsActive, int eBalance, int eTxLogCount, long actualAccountId) throws Exception {
- Assert.assertEquals(eOwnerName, service.getOwnerOf(actualAccountId));
- Assert.assertEquals(eIsActive, service.isAccountActive(actualAccountId));
- Assert.assertEquals(eBalance, (int)service.getBalanceOf(actualAccountId));
- Assert.assertEquals(eTxLogCount, service.getTxHistoryFor(actualAccountId).length);
+ Assertions.assertEquals(eOwnerName, service.getOwnerOf(actualAccountId));
+ Assertions.assertEquals(eIsActive, service.isAccountActive(actualAccountId));
+ Assertions.assertEquals(eBalance, (int)service.getBalanceOf(actualAccountId));
+ Assertions.assertEquals(eTxLogCount, service.getTxHistoryFor(actualAccountId).length);
}
}
diff --git a/samples/guice/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java b/samples/guice/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java
index 7ad30f5d7..8d76d2d91 100644
--- a/samples/guice/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java
+++ b/samples/guice/src/test/java/org/apache/shiro/samples/guice/ContainerIntegrationIT.java
@@ -26,15 +26,15 @@ import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.apache.shiro.testing.web.AbstractContainerIT;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.MalformedURLException;
public class ContainerIntegrationIT extends AbstractContainerIT {
- @Before
+ @BeforeEach
public void logOut() throws IOException {
// Make sure we are logged out
final HtmlPage homePage = webClient.getPage(getBaseUri());
@@ -47,7 +47,7 @@ public class ContainerIntegrationIT extends AbstractContainerIT {
}
@Test
- public void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
+ void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
HtmlPage page = webClient.getPage(getBaseUri() + "login.jsp");
HtmlForm form = page.getFormByName("loginform");
@@ -59,7 +59,7 @@ public class ContainerIntegrationIT extends AbstractContainerIT {
}
@Test
- public void logInAndRememberMe() throws Exception {
+ void logInAndRememberMe() throws Exception {
HtmlPage page = webClient.getPage(getBaseUri() + "login.jsp");
HtmlForm form = page.getFormByName("loginform");
form.<HtmlInput>getInputByName("username").setValueAttribute("root");
diff --git a/samples/servlet-plugin/src/test/java/org/apache/shiro/test/ContainerIntegrationIT.java b/samples/servlet-plugin/src/test/java/org/apache/shiro/test/ContainerIntegrationIT.java
index 376f98f3a..be78865e8 100644
--- a/samples/servlet-plugin/src/test/java/org/apache/shiro/test/ContainerIntegrationIT.java
+++ b/samples/servlet-plugin/src/test/java/org/apache/shiro/test/ContainerIntegrationIT.java
@@ -24,15 +24,15 @@ import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.apache.shiro.testing.web.AbstractContainerIT;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.MalformedURLException;
public class ContainerIntegrationIT extends AbstractContainerIT {
- @Before
+ @BeforeEach
public void logOut() throws IOException {
// Make sure we are logged out
final HtmlPage homePage = webClient.getPage(getBaseUri());
@@ -45,7 +45,7 @@ public class ContainerIntegrationIT extends AbstractContainerIT {
}
@Test
- public void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
+ void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
HtmlPage page = webClient.getPage(getBaseUri() + "login.jsp");
HtmlForm form = page.getFormByName("loginform");
diff --git a/samples/spring-hibernate/src/test/java/org/apache/shiro/samples/ContainerIntegrationIT.java b/samples/spring-hibernate/src/test/java/org/apache/shiro/samples/ContainerIntegrationIT.java
index a2563732a..753d270b9 100644
--- a/samples/spring-hibernate/src/test/java/org/apache/shiro/samples/ContainerIntegrationIT.java
+++ b/samples/spring-hibernate/src/test/java/org/apache/shiro/samples/ContainerIntegrationIT.java
@@ -25,8 +25,8 @@ import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.apache.shiro.testing.web.AbstractContainerIT;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.MalformedURLException;
@@ -36,7 +36,7 @@ public class ContainerIntegrationIT extends AbstractContainerIT {
protected final WebClient webClient = new WebClient();
- @Before
+ @BeforeEach
public void logOut() throws IOException {
// Make sure we are logged out
final HtmlPage homePage = webClient.getPage(getBaseUri());
@@ -49,7 +49,7 @@ public class ContainerIntegrationIT extends AbstractContainerIT {
}
@Test
- public void logIn() throws FailingHttpStatusCodeException, IOException, InterruptedException {
+ void logIn() throws FailingHttpStatusCodeException, IOException, InterruptedException {
HtmlPage page = webClient.getPage(getBaseUri() + "s/login");
HtmlForm form = page.getFormByName("loginForm");
diff --git a/samples/web-jakarta/src/test/java/org/apache/shiro/test/web/jakarta/JakartaAbstractContainerIT.java b/samples/web-jakarta/src/test/java/org/apache/shiro/test/web/jakarta/JakartaAbstractContainerIT.java
index bba953855..1f099addd 100644
--- a/samples/web-jakarta/src/test/java/org/apache/shiro/test/web/jakarta/JakartaAbstractContainerIT.java
+++ b/samples/web-jakarta/src/test/java/org/apache/shiro/test/web/jakarta/JakartaAbstractContainerIT.java
@@ -25,7 +25,7 @@ import org.junit.jupiter.api.BeforeAll;
import java.io.File;
import java.io.FilenameFilter;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public abstract class JakartaAbstractContainerIT {
@@ -56,7 +56,7 @@ public abstract class JakartaAbstractContainerIT {
}
});
- assertEquals("Expected only one war file in target directory, run 'mvn clean' and try again", 1, warFiles.length);
+ assertEquals(1, warFiles.length, "Expected only one war file in target directory, run 'mvn clean' and try again");
return warFiles[0].getAbsolutePath().replaceFirst("\\.war$", "");
}
diff --git a/samples/web/src/test/java/org/apache/shiro/test/WebAppContainerIntegrationIT.java b/samples/web/src/test/java/org/apache/shiro/test/WebAppContainerIntegrationIT.java
index cfaa354f6..31dd4e177 100644
--- a/samples/web/src/test/java/org/apache/shiro/test/WebAppContainerIntegrationIT.java
+++ b/samples/web/src/test/java/org/apache/shiro/test/WebAppContainerIntegrationIT.java
@@ -25,8 +25,8 @@ import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.apache.shiro.testing.web.AbstractContainerIT;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.MalformedURLException;
@@ -35,7 +35,7 @@ public class WebAppContainerIntegrationIT extends AbstractContainerIT {
protected final WebClient webClient = new WebClient();
- @Before
+ @BeforeEach
public void logOut() throws IOException {
// Make sure we are logged out
final HtmlPage homePage = webClient.getPage(getTlsBaseUri());
@@ -48,7 +48,7 @@ public class WebAppContainerIntegrationIT extends AbstractContainerIT {
}
@Test
- public void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
+ void logIn() throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException {
HtmlPage page = webClient.getPage(getTlsBaseUri() + "login.jsp");
HtmlForm form = page.getFormByName("loginform");
diff --git a/support/aspectj/src/test/java/org/apache/shiro/aspectj/DummyServiceTest.java b/support/aspectj/src/test/java/org/apache/shiro/aspectj/DummyServiceTest.java
index eed24aa7b..9a7bec791 100644
--- a/support/aspectj/src/test/java/org/apache/shiro/aspectj/DummyServiceTest.java
+++ b/support/aspectj/src/test/java/org/apache/shiro/aspectj/DummyServiceTest.java
@@ -26,7 +26,13 @@ import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.lang.util.Factory;
-import org.junit.*;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
*/
@@ -35,7 +41,7 @@ public class DummyServiceTest {
private static DummyService SECURED_SERVICE;
private static DummyService RESTRICTED_SERVICE;
- @BeforeClass
+ @BeforeAll
public static void setUpClass() throws Exception {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiroDummyServiceTest.ini");
SecurityManager securityManager = factory.getInstance();
@@ -45,7 +51,7 @@ public class DummyServiceTest {
RESTRICTED_SERVICE = new RestrictedDummyService();
}
- @AfterClass
+ @AfterAll
public static void tearDownClass() throws Exception {
//don't corrupt other test cases since this is static memory:
SecurityUtils.setSecurityManager(null);
@@ -53,12 +59,12 @@ public class DummyServiceTest {
private Subject subject;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
subject = SecurityUtils.getSubject();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
subject.logout();
}
@@ -73,111 +79,127 @@ public class DummyServiceTest {
// TEST ANONYMOUS
@Test
- public void testAnonymous_asAnonymous() throws Exception {
+ void testAnonymous_asAnonymous() throws Exception {
SECURED_SERVICE.anonymous();
}
@Test
- public void testAnonymous_asUser() throws Exception {
+ void testAnonymous_asUser() throws Exception {
loginAsUser();
SECURED_SERVICE.anonymous();
}
@Test
- public void testAnonymous_asAdmin() throws Exception {
+ void testAnonymous_asAdmin() throws Exception {
loginAsAdmin();
SECURED_SERVICE.anonymous();
}
// TEST GUEST
@Test
- public void testGuest_asAnonymous() throws Exception {
+ void testGuest_asAnonymous() throws Exception {
SECURED_SERVICE.guest();
}
- @Test(expected = UnauthenticatedException.class)
- public void testGuest_asUser() throws Exception {
- loginAsUser();
- SECURED_SERVICE.guest();
+ @Test
+ void testGuest_asUser() throws Exception {
+ assertThrows(UnauthenticatedException.class, () -> {
+ loginAsUser();
+ SECURED_SERVICE.guest();
+ });
}
- @Test(expected = UnauthenticatedException.class)
- public void testGuest_asAdmin() throws Exception {
- loginAsAdmin();
- SECURED_SERVICE.guest();
+ @Test
+ void testGuest_asAdmin() throws Exception {
+ assertThrows(UnauthenticatedException.class, () -> {
+ loginAsAdmin();
+ SECURED_SERVICE.guest();
+ });
}
// TEST PEEK
- @Test(expected = UnauthenticatedException.class)
- public void testPeek_asAnonymous() throws Exception {
- SECURED_SERVICE.peek();
+ @Test
+ void testPeek_asAnonymous() throws Exception {
+ assertThrows(UnauthenticatedException.class, () -> {
+ SECURED_SERVICE.peek();
+ });
}
@Test
- public void testPeek_asUser() throws Exception {
+ void testPeek_asUser() throws Exception {
loginAsUser();
SECURED_SERVICE.peek();
}
@Test
- public void testPeek_asAdmin() throws Exception {
+ void testPeek_asAdmin() throws Exception {
loginAsAdmin();
SECURED_SERVICE.peek();
}
// TEST RETRIEVE
- @Test(expected = UnauthenticatedException.class)
//UnauthenticatedException per SHIRO-146
- public void testRetrieve_asAnonymous() throws Exception {
- SECURED_SERVICE.retrieve();
+ @Test
+ void testRetrieve_asAnonymous() throws Exception {
+ assertThrows(UnauthenticatedException.class, () -> {
+ SECURED_SERVICE.retrieve();
+ });
}
@Test
- public void testRetrieve_asUser() throws Exception {
+ void testRetrieve_asUser() throws Exception {
loginAsUser();
SECURED_SERVICE.retrieve();
}
@Test
- public void testRetrieve_asAdmin() throws Exception {
+ void testRetrieve_asAdmin() throws Exception {
loginAsAdmin();
SECURED_SERVICE.retrieve();
}
// TEST CHANGE
- @Test(expected = UnauthenticatedException.class)
//UnauthenticatedException per SHIRO-146
- public void testChange_asAnonymous() throws Exception {
- SECURED_SERVICE.change();
+ @Test
+ void testChange_asAnonymous() throws Exception {
+ assertThrows(UnauthenticatedException.class, () -> {
+ SECURED_SERVICE.change();
+ });
}
- @Test(expected = UnauthorizedException.class)
- public void testChange_asUser() throws Exception {
- loginAsUser();
- SECURED_SERVICE.change();
+ @Test
+ void testChange_asUser() throws Exception {
+ assertThrows(UnauthorizedException.class, () -> {
+ loginAsUser();
+ SECURED_SERVICE.change();
+ });
}
@Test
- public void testChange_asAdmin() throws Exception {
+ void testChange_asAdmin() throws Exception {
loginAsAdmin();
SECURED_SERVICE.change();
}
// TEST RETRIEVE RESTRICTED
- @Test(expected = UnauthenticatedException.class)
//UnauthenticatedException per SHIRO-146
- public void testRetrieveRestricted_asAnonymous() throws Exception {
- RESTRICTED_SERVICE.retrieve();
+ @Test
+ void testRetrieveRestricted_asAnonymous() throws Exception {
+ assertThrows(UnauthenticatedException.class, () -> {
+ RESTRICTED_SERVICE.retrieve();
+ });
}
- @Test(expected = UnauthorizedException.class)
- public void testRetrieveRestricted_asUser() throws Exception {
- loginAsUser();
- RESTRICTED_SERVICE.retrieve();
+ @Test
+ void testRetrieveRestricted_asUser() throws Exception {
+ assertThrows(UnauthorizedException.class, () -> {
+ loginAsUser();
+ RESTRICTED_SERVICE.retrieve();
+ });
}
@Test
- public void testRetrieveRestricted_asAdmin() throws Exception {
+ void testRetrieveRestricted_asAdmin() throws Exception {
loginAsAdmin();
RESTRICTED_SERVICE.retrieve();
}
diff --git a/support/ehcache/src/test/java/org/apache/shiro/cache/ehcache/EhCacheManagerTest.java b/support/ehcache/src/test/java/org/apache/shiro/cache/ehcache/EhCacheManagerTest.java
index 965c26202..7817f615a 100644
--- a/support/ehcache/src/test/java/org/apache/shiro/cache/ehcache/EhCacheManagerTest.java
+++ b/support/ehcache/src/test/java/org/apache/shiro/cache/ehcache/EhCacheManagerTest.java
@@ -20,11 +20,11 @@ package org.apache.shiro.cache.ehcache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.lang.util.LifecycleUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.util.Collection;
import java.util.Set;
@@ -38,18 +38,18 @@ public class EhCacheManagerTest {
private EhCacheManager cacheManager;
- @Before
+ @BeforeEach
public void setUp() {
cacheManager = new EhCacheManager();
}
- @After
+ @AfterEach
public void tearDown() {
LifecycleUtils.destroy(cacheManager);
}
@Test
- public void testCacheManagerCreationDuringInit() {
+ void testCacheManagerCreationDuringInit() {
net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager();
assertNull(ehCacheManager);
cacheManager.init();
@@ -59,7 +59,7 @@ public class EhCacheManagerTest {
}
@Test
- public void testLazyCacheManagerCreationWithoutCallingInit() {
+ void testLazyCacheManagerCreationWithoutCallingInit() {
net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager();
assertNull(ehCacheManager);
@@ -79,7 +79,7 @@ public class EhCacheManagerTest {
}
@Test
- public void testRemove() {
+ void testRemove() {
net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager();
assertNull(ehCacheManager);
@@ -106,7 +106,7 @@ public class EhCacheManagerTest {
}
@Test
- public void testClear() {
+ void testClear() {
net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager();
assertNull(ehCacheManager);
@@ -131,7 +131,7 @@ public class EhCacheManagerTest {
}
@Test
- public void testKeys() {
+ void testKeys() {
net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager();
assertNull(ehCacheManager);
@@ -165,7 +165,7 @@ public class EhCacheManagerTest {
}
@Test
- public void testValues() {
+ void testValues() {
net.sf.ehcache.CacheManager ehCacheManager = cacheManager.getCacheManager();
assertNull(ehCacheManager);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/BeanTypeListenerTest.java b/support/guice/src/test/java/org/apache/shiro/guice/BeanTypeListenerTest.java
index 421ae325a..3805259f2 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/BeanTypeListenerTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/BeanTypeListenerTest.java
@@ -31,21 +31,18 @@ import org.apache.shiro.SecurityUtils;
import org.apache.shiro.aop.DefaultAnnotationResolver;
import org.apache.shiro.crypto.cipher.BlowfishCipherService;
import org.apache.shiro.guice.aop.ShiroAopModule;
-import org.apache.shiro.guice.web.ShiroWebModule;
-import org.junit.Test;
+import org.apache.shiro.guice.web.ShiroWebModule;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.Collections;
import java.util.Map;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
+import static org.mockito.Mockito.when;
+
/**
* Test Cases::
* Test package matching
@@ -56,23 +53,23 @@ import static org.mockito.Mockito.when;
* ensure property names are correct
* ensure "named" properties require a name, and unnamed do not
*/
-public class BeanTypeListenerTest {
- @Test
- public void testUnmatchedPackage() throws Exception {
+public class BeanTypeListenerTest {
+ @Test
+ void testUnmatchedPackage() throws Exception {
assertFalse(BeanTypeListener.MATCHER.matches(TypeLiteral.get(GuiceEnvironment.class)));
assertFalse(BeanTypeListener.MATCHER.matches(TypeLiteral.get(ShiroWebModule.class)));
assertFalse(BeanTypeListener.MATCHER.matches(TypeLiteral.get(ShiroAopModule.class)));
- }
-
- @Test
- public void testMatchedPackage() throws Exception {
+ }
+
+ @Test
+ void testMatchedPackage() throws Exception {
assertTrue(BeanTypeListener.MATCHER.matches(TypeLiteral.get(SecurityUtils.class)));
assertTrue(BeanTypeListener.MATCHER.matches(TypeLiteral.get(DefaultAnnotationResolver.class)));
assertTrue(BeanTypeListener.MATCHER.matches(TypeLiteral.get(BlowfishCipherService.class)));
- }
-
- @Test
- public void testPropertySetting() throws Exception {
+ }
+
+ @Test
+ void testPropertySetting() throws Exception {
TypeEncounter<SomeInjectableBean> encounter = mock(TypeEncounter.class);
Provider<Injector> injectorProvider = mock(Provider.class);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/DestroyableInjectionListenerTest.java b/support/guice/src/test/java/org/apache/shiro/guice/DestroyableInjectionListenerTest.java
index 414ea54fd..0fa0a5a82 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/DestroyableInjectionListenerTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/DestroyableInjectionListenerTest.java
@@ -18,14 +18,14 @@
*/
package org.apache.shiro.guice;
-import org.apache.shiro.lang.util.Destroyable;
-import org.junit.Test;
+import org.apache.shiro.lang.util.Destroyable;
+import org.junit.jupiter.api.Test;
-import static org.easymock.EasyMock.*;
-
-public class DestroyableInjectionListenerTest {
- @Test
- public void testAfterInjection() throws Exception {
+import static org.easymock.EasyMock.*;
+
+public class DestroyableInjectionListenerTest {
+ @Test
+ void testAfterInjection() throws Exception {
DestroyableInjectionListener.DestroyableRegistry registry = createMock(DestroyableInjectionListener.DestroyableRegistry.class);
Destroyable destroyable = createMock(Destroyable.class);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/GuiceEnvironmentTest.java b/support/guice/src/test/java/org/apache/shiro/guice/GuiceEnvironmentTest.java
index c91fd1845..72001f1b9 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/GuiceEnvironmentTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/GuiceEnvironmentTest.java
@@ -19,24 +19,24 @@
package org.apache.shiro.guice;
import com.google.inject.spi.InjectionPoint;
-import org.apache.shiro.mgt.SecurityManager;
-import org.junit.Test;
+import org.apache.shiro.mgt.SecurityManager;
+import org.junit.jupiter.api.Test;
import static org.easymock.EasyMock.createMock;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
-
-public class GuiceEnvironmentTest {
- @Test
- public void testGetSecurityManager() throws Exception {
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
+
+public class GuiceEnvironmentTest {
+ @Test
+ void testGetSecurityManager() throws Exception {
SecurityManager securityManager = createMock(SecurityManager.class);
GuiceEnvironment underTest = new GuiceEnvironment(securityManager);
assertSame(securityManager, underTest.getSecurityManager());
- }
-
- @Test
- public void ensureInjectable() {
+ }
+
+ @Test
+ void ensureInjectable() {
try {
InjectionPoint ip = InjectionPoint.forConstructorOf(GuiceEnvironment.class);
} catch (Exception e) {
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/InitializableInjectionListenerTest.java b/support/guice/src/test/java/org/apache/shiro/guice/InitializableInjectionListenerTest.java
index 6e8807cd5..df6a0c14b 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/InitializableInjectionListenerTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/InitializableInjectionListenerTest.java
@@ -18,14 +18,14 @@
*/
package org.apache.shiro.guice;
-import org.apache.shiro.lang.util.Initializable;
-import org.junit.Test;
+import org.apache.shiro.lang.util.Initializable;
+import org.junit.jupiter.api.Test;
-import static org.easymock.EasyMock.*;
-
-public class InitializableInjectionListenerTest {
- @Test
- public void testAfterInjection() throws Exception {
+import static org.easymock.EasyMock.*;
+
+public class InitializableInjectionListenerTest {
+ @Test
+ void testAfterInjection() throws Exception {
Initializable initializable = createMock(Initializable.class);
initializable.init();
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/LifecycleTypeListenerTest.java b/support/guice/src/test/java/org/apache/shiro/guice/LifecycleTypeListenerTest.java
index 174153e6e..a445a2ca4 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/LifecycleTypeListenerTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/LifecycleTypeListenerTest.java
@@ -22,14 +22,14 @@ import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import org.apache.shiro.lang.ShiroException;
import org.apache.shiro.lang.util.Destroyable;
-import org.apache.shiro.lang.util.Initializable;
-import org.junit.Test;
-
-import static org.easymock.EasyMock.*;
-
-public class LifecycleTypeListenerTest {
- @Test
- public void testHearInitializable() throws Exception {
+import org.apache.shiro.lang.util.Initializable;
+import org.junit.jupiter.api.Test;
+
+import static org.easymock.EasyMock.*;
+
+public class LifecycleTypeListenerTest {
+ @Test
+ void testHearInitializable() throws Exception {
TypeEncounter encounter = createMock(TypeEncounter.class);
encounter.register(anyObject(InitializableInjectionListener.class));
@@ -41,10 +41,10 @@ public class LifecycleTypeListenerTest {
underTest.hear(TypeLiteral.get(MyInitializable.class), encounter);
verify(encounter);
- }
-
- @Test
- public void testHearDestroyable() throws Exception {
+ }
+
+ @Test
+ void testHearDestroyable() throws Exception {
TypeEncounter encounter = createMock(TypeEncounter.class);
encounter.register(anyObject(DestroyableInjectionListener.class));
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/ShiroMatchersTest.java b/support/guice/src/test/java/org/apache/shiro/guice/ShiroMatchersTest.java
index 19b028cd5..33cb70fea 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/ShiroMatchersTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/ShiroMatchersTest.java
@@ -19,16 +19,16 @@
package org.apache.shiro.guice;
import com.google.inject.TypeLiteral;
-import com.google.inject.matcher.Matcher;
-import org.junit.Test;
-
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-public class ShiroMatchersTest {
- @Test
- public void testTypeLiteral() throws Exception {
+import com.google.inject.matcher.Matcher;
+import org.junit.jupiter.api.Test;
+
+import static org.easymock.EasyMock.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ShiroMatchersTest {
+ @Test
+ void testTypeLiteral() throws Exception {
Matcher<Class> classMatcher = createMock(Matcher.class);
expect(classMatcher.matches(MatchingClass.class)).andReturn(true);
expect(classMatcher.matches(NotMatchingClass.class)).andReturn(false);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/ShiroModuleTest.java b/support/guice/src/test/java/org/apache/shiro/guice/ShiroModuleTest.java
index 03aeb2852..d63c7d9e7 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/ShiroModuleTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/ShiroModuleTest.java
@@ -36,19 +36,19 @@ import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.SessionManager;
-import org.apache.shiro.subject.Subject;
+import org.apache.shiro.subject.Subject;
+import org.junit.jupiter.api.Test;
import org.apache.shiro.lang.util.Destroyable;
-import org.junit.Test;
import java.util.Collection;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.*;
-
-public class ShiroModuleTest {
-
- @Test
- public void basicInstantiation() {
+import static org.junit.jupiter.api.Assertions.*;
+
+public class ShiroModuleTest {
+
+ @Test
+ void basicInstantiation() {
final MockRealm mockRealm = createMock(MockRealm.class);
@@ -65,10 +65,10 @@ public class ShiroModuleTest {
});
SecurityManager securityManager = injector.getInstance(SecurityManager.class);
assertNotNull(securityManager);
- }
-
- @Test
- public void testConfigure() {
+ }
+
+ @Test
+ void testConfigure() {
final MockRealm mockRealm = createMock(MockRealm.class);
AuthenticationToken authToken = createMock(AuthenticationToken.class);
AuthenticationInfo info = new SimpleAuthenticationInfo("mockUser", "password", "mockRealm");
@@ -97,10 +97,10 @@ public class ShiroModuleTest {
securityManager.login(subject, authToken);
verify(mockRealm);
- }
-
- @Test
- public void testBindSecurityManager() {
+ }
+
+ @Test
+ void testBindSecurityManager() {
final MockRealm mockRealm = createMock(MockRealm.class);
Injector injector = Guice.createInjector(new ShiroModule() {
@@ -122,10 +122,10 @@ public class ShiroModuleTest {
SecurityManager securityManager = injector.getInstance(SecurityManager.class);
assertNotNull(securityManager);
assertTrue(securityManager instanceof MyDefaultSecurityManager);
- }
-
- @Test
- public void testBindSessionManager() {
+ }
+
+ @Test
+ void testBindSessionManager() {
final MockRealm mockRealm = createMock(MockRealm.class);
Injector injector = Guice.createInjector(new ShiroModule() {
@@ -148,10 +148,10 @@ public class ShiroModuleTest {
assertNotNull(securityManager);
assertNotNull(securityManager.getSessionManager());
assertTrue(securityManager.getSessionManager() instanceof MyDefaultSessionManager);
- }
-
- @Test
- public void testBindEnvironment() {
+ }
+
+ @Test
+ void testBindEnvironment() {
final MockRealm mockRealm = createMock(MockRealm.class);
Injector injector = Guice.createInjector(new ShiroModule() {
@@ -174,10 +174,10 @@ public class ShiroModuleTest {
Environment environment = injector.getInstance(Environment.class);
assertNotNull(environment);
assertTrue(environment instanceof MyEnvironment);
- }
-
- @Test
- public void testDestroy() throws Exception {
+ }
+
+ @Test
+ void testDestroy() throws Exception {
final MockRealm mockRealm = createMock(MockRealm.class);
final MyDestroyable myDestroyable = createMock(MyDestroyable.class);
@@ -204,14 +204,14 @@ public class ShiroModuleTest {
shiroModule.destroy();
verify(myDestroyable);
- }
-
- /**
- * @since 1.4
- * @throws Exception
- */
- @Test
- public void testEventListener() throws Exception {
+ }
+
+ /**
+ * @since 1.4
+ * @throws Exception
+ */
+ @Test
+ void testEventListener() throws Exception {
final MockRealm mockRealm = createMock(MockRealm.class);
final EventBus eventBus = createMock(EventBus.class);
@@ -246,14 +246,14 @@ public class ShiroModuleTest {
verify(eventBus);
- }
-
- /**
- * @since 1.4
- * @throws Exception
- */
- @Test
- public void testEventBusAware() throws Exception {
+ }
+
+ /**
+ * @since 1.4
+ * @throws Exception
+ */
+ @Test
+ void testEventBusAware() throws Exception {
final MockRealm mockRealm = createMock(MockRealm.class);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/ShiroSessionScopeTest.java b/support/guice/src/test/java/org/apache/shiro/guice/ShiroSessionScopeTest.java
index 9b84dc2e9..c1d9e7f32 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/ShiroSessionScopeTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/ShiroSessionScopeTest.java
@@ -23,15 +23,16 @@ import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
-import org.apache.shiro.util.ThreadContext;
-import org.junit.Test;
-
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertSame;
-
-public class ShiroSessionScopeTest {
- @Test
- public void testScope() throws Exception {
+import org.apache.shiro.util.ThreadContext;
+import org.junit.jupiter.api.Test;
+
+import static org.easymock.EasyMock.*;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class ShiroSessionScopeTest {
+ @Test
+ void testScope() throws Exception {
Subject subject = createMock(Subject.class);
try {
ThreadContext.bind(subject);
@@ -64,17 +65,19 @@ public class ShiroSessionScopeTest {
ThreadContext.unbindSubject();
}
- }
-
- @Test(expected = OutOfScopeException.class)
- public void testOutOfScope() throws Exception {
- ShiroSessionScope underTest = new ShiroSessionScope();
-
- Provider<SomeClass> mockProvider = createMock(Provider.class);
-
- replay(mockProvider);
-
- underTest.scope(Key.get(SomeClass.class), mockProvider).get();
+ }
+
+ @Test
+ void testOutOfScope() throws Exception {
+ assertThrows(OutOfScopeException.class, () -> {
+ ShiroSessionScope underTest = new ShiroSessionScope();
+
+ Provider<SomeClass> mockProvider = createMock(Provider.class);
+
+ replay(mockProvider);
+
+ underTest.scope(Key.get(SomeClass.class), mockProvider).get();
+ });
}
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/aop/AopAllianceMethodInterceptorAdapterTest.java b/support/guice/src/test/java/org/apache/shiro/guice/aop/AopAllianceMethodInterceptorAdapterTest.java
index ce4b65d14..a0ad8009a 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/aop/AopAllianceMethodInterceptorAdapterTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/aop/AopAllianceMethodInterceptorAdapterTest.java
@@ -20,16 +20,16 @@ package org.apache.shiro.guice.aop;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.shiro.aop.MethodInterceptor;
-import org.easymock.IAnswer;
-import org.junit.Test;
-
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertSame;
-
-
-public class AopAllianceMethodInterceptorAdapterTest {
- @Test
- public void testInvoke() throws Throwable {
+import org.easymock.IAnswer;
+import org.junit.jupiter.api.Test;
+
+import static org.easymock.EasyMock.*;
+import static org.junit.jupiter.api.Assertions.assertSame;
+
+
+public class AopAllianceMethodInterceptorAdapterTest {
+ @Test
+ void testInvoke() throws Throwable {
MethodInvocation allianceInvocation = createMock(MethodInvocation.class);
MethodInterceptor mockShiroInterceptor = createMock(MethodInterceptor.class);
expect(mockShiroInterceptor.invoke(anyObject(AopAllianceMethodInvocationAdapter.class))).andAnswer(new IAnswer<Object>() {
@@ -46,7 +46,7 @@ public class AopAllianceMethodInterceptorAdapterTest {
Object invocation = underTest.invoke(allianceInvocation);
Object value = ((AopAllianceMethodInvocationAdapter) invocation).proceed();
- assertSame("Adapter invocation returned a different value.", expectedValue, value);
+ assertSame(expectedValue, value, "Adapter invocation returned a different value.");
verify(mockShiroInterceptor, allianceInvocation);
}
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/aop/AopAllianceMethodInvocationAdapterTest.java b/support/guice/src/test/java/org/apache/shiro/guice/aop/AopAllianceMethodInvocationAdapterTest.java
index 54be9273b..817e5717f 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/aop/AopAllianceMethodInvocationAdapterTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/aop/AopAllianceMethodInvocationAdapterTest.java
@@ -18,14 +18,14 @@
*/
package org.apache.shiro.guice.aop;
-import org.aopalliance.intercept.MethodInvocation;
-import org.junit.Test;
+import org.aopalliance.intercept.MethodInvocation;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertSame;
-
+import static org.easymock.EasyMock.*;
+import static org.junit.jupiter.api.Assertions.assertSame;
+
/**
* Created by IntelliJ IDEA.
* User: jbunting
@@ -33,9 +33,9 @@ import static org.junit.Assert.assertSame;
* Time: 5:02 PM
* To change this template use File | Settings | File Templates.
*/
-public class AopAllianceMethodInvocationAdapterTest {
- @Test
- public void testGetMethod() throws Exception {
+public class AopAllianceMethodInvocationAdapterTest {
+ @Test
+ void testGetMethod() throws Exception {
MethodInvocation mock = createMock(MethodInvocation.class);
Method method = AopAllianceMethodInvocationAdapterTest.class.getMethod("testGetMethod");
expect(mock.getMethod()).andReturn(method);
@@ -46,10 +46,10 @@ public class AopAllianceMethodInvocationAdapterTest {
assertSame(method, underTest.getMethod());
verify(mock);
- }
-
- @Test
- public void testGetArguments() throws Exception {
+ }
+
+ @Test
+ void testGetArguments() throws Exception {
MethodInvocation mock = createMock(MethodInvocation.class);
Object[] args = new Object[0];
expect(mock.getArguments()).andReturn(args);
@@ -60,10 +60,10 @@ public class AopAllianceMethodInvocationAdapterTest {
assertSame(args, underTest.getArguments());
verify(mock);
- }
-
- @Test
- public void testProceed() throws Throwable {
+ }
+
+ @Test
+ void testProceed() throws Throwable {
MethodInvocation mock = createMock(MethodInvocation.class);
Object value = new Object();
expect(mock.proceed()).andReturn(value);
@@ -74,10 +74,10 @@ public class AopAllianceMethodInvocationAdapterTest {
assertSame(value, underTest.proceed());
verify(mock);
- }
-
- @Test
- public void testGetThis() throws Exception {
+ }
+
+ @Test
+ void testGetThis() throws Exception {
MethodInvocation mock = createMock(MethodInvocation.class);
Object value = new Object();
expect(mock.getThis()).andReturn(value);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/aop/ShiroAopModuleTest.java b/support/guice/src/test/java/org/apache/shiro/guice/aop/ShiroAopModuleTest.java
index d4748249d..90846da88 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/aop/ShiroAopModuleTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/aop/ShiroAopModuleTest.java
@@ -28,9 +28,9 @@ import com.google.inject.spi.InterceptorBinding;
import org.aopalliance.intercept.MethodInterceptor;
import org.apache.shiro.aop.*;
import org.apache.shiro.authz.annotation.*;
-import org.apache.shiro.authz.aop.*;
-import org.junit.Before;
-import org.junit.Test;
+import org.apache.shiro.authz.aop.*;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.lang.annotation.*;
import java.lang.reflect.Method;
@@ -38,11 +38,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.*;
-
-public class ShiroAopModuleTest {
- @Test
- public void testGetAnnotationResolver() {
+import static org.junit.jupiter.api.Assertions.*;
+
+public class ShiroAopModuleTest {
+ @Test
+ void testGetAnnotationResolver() {
final AnnotationResolver annotationResolver = new DefaultAnnotationResolver();
@@ -84,10 +84,10 @@ public class ShiroAopModuleTest {
}
}
}
- }
-
- @Test
- public void testBindShiroInterceptor() {
+ }
+
+ @Test
+ void testBindShiroInterceptor() {
ShiroAopModule underTest = new ShiroAopModule() {
@@ -127,7 +127,7 @@ public class ShiroAopModuleTest {
}
}
- assertTrue("Not all interceptors were bound.", protectedMethods.isEmpty());
+ assertTrue(protectedMethods.isEmpty(), "Not all interceptors were bound.");
}
@Target({ElementType.TYPE, ElementType.METHOD})
@@ -192,7 +192,7 @@ public class ShiroAopModuleTest {
private Map<Class<? extends Annotation>, Method> protectedMethods;
private Map<Class<? extends Annotation>, Class<? extends AnnotationMethodInterceptor>> interceptorTypes;
- @Before
+ @BeforeEach
public void setup() throws NoSuchMethodException {
protectedMethods = new HashMap<Class<? extends Annotation>, Method>();
protectedMethods.put(RequiresRoles.class, getClass().getMethod("roleProtected"));
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/AbstractInjectionProviderTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/AbstractInjectionProviderTest.java
index af7f4a4ba..54420d8c8 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/AbstractInjectionProviderTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/AbstractInjectionProviderTest.java
@@ -23,8 +23,8 @@ import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
-import com.google.inject.spi.Dependency;
-import org.junit.Test;
+import com.google.inject.spi.Dependency;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
@@ -32,12 +32,12 @@ import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.*;
-
-public class AbstractInjectionProviderTest {
-
- @Test
- public void testGet() throws Exception {
+import static org.junit.jupiter.api.Assertions.*;
+
+public class AbstractInjectionProviderTest {
+
+ @Test
+ void testGet() throws Exception {
Injector mockInjector = createMock(Injector.class);
Object c1 = new Object();
@@ -63,16 +63,16 @@ public class AbstractInjectionProviderTest {
SomeInjectedClass got = underTest.get();
- assertEquals("Wrong parameter passed to constructor (index 0).", c1, got.c1);
- assertEquals("Wrong parameter passed to constructor (index 1).", c2, got.c2);
+ assertEquals(c1, got.c1, "Wrong parameter passed to constructor (index 0).");
+ assertEquals(c2, got.c2, "Wrong parameter passed to constructor (index 1).");
- assertTrue("postProcess method was not called.", postProcessCalled.get());
+ assertTrue(postProcessCalled.get(), "postProcess method was not called.");
verify(mockInjector);
- }
-
- @Test
- public void testGetDependencies() throws Exception {
+ }
+
+ @Test
+ void testGetDependencies() throws Exception {
AbstractInjectionProvider<SomeInjectedClass> underTest =
new AbstractInjectionProvider<SomeInjectedClass>(Key.get(SomeInjectedClass.class));
@@ -110,11 +110,11 @@ public class AbstractInjectionProviderTest {
}
}
- assertTrue("Did not find dependency C1", foundC1);
- assertTrue("Did not find dependency C2", foundC2);
- assertTrue("Did not find dependency V1", foundV1);
- assertTrue("Did not find dependency V2", foundV2);
- assertTrue("Did not find dependency F1", foundF1);
+ assertTrue(foundC1, "Did not find dependency C1");
+ assertTrue(foundC2, "Did not find dependency C2");
+ assertTrue(foundV1, "Did not find dependency V1");
+ assertTrue(foundV2, "Did not find dependency V2");
+ assertTrue(foundF1, "Did not find dependency F1");
}
static Key keyC1 = Key.get(Object.class, Names.named("constructor1"));
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/DefaultFiltersTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/DefaultFiltersTest.java
index 22a5ff15a..af2a9a777 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/DefaultFiltersTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/DefaultFiltersTest.java
@@ -19,19 +19,19 @@
package org.apache.shiro.guice.web;
import com.google.inject.Key;
-import org.apache.shiro.web.filter.mgt.DefaultFilter;
-import org.junit.Test;
+import org.apache.shiro.web.filter.mgt.DefaultFilter;
+import org.junit.jupiter.api.Test;
import javax.servlet.Filter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
-import java.util.EnumSet;
-
-import static org.junit.Assert.fail;
-
-public class DefaultFiltersTest {
- @Test
- public void checkDefaultFilters() throws Exception {
+import java.util.EnumSet;
+
+import static org.junit.jupiter.api.Assertions.fail;
+
+public class DefaultFiltersTest {
+ @Test
+ void checkDefaultFilters() throws Exception {
EnumSet<DefaultFilter> defaultFilters = EnumSet.allOf(DefaultFilter.class);
for(Field field: ShiroWebModule.class.getFields()) {
if(Modifier.isStatic(field.getModifiers()) && Key.class.isAssignableFrom(field.getType())) {
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/FilterChainResolverProviderTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/FilterChainResolverProviderTest.java
index 03b132a14..86ea707de 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/FilterChainResolverProviderTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/FilterChainResolverProviderTest.java
@@ -23,9 +23,9 @@ import com.google.inject.Key;
import com.google.inject.name.Names;
import com.google.inject.spi.Dependency;
import org.apache.shiro.util.PatternMatcher;
-import org.apache.shiro.web.filter.mgt.FilterChainResolver;
-import org.junit.Before;
-import org.junit.Test;
+import org.apache.shiro.web.filter.mgt.FilterChainResolver;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.servlet.Filter;
import java.lang.reflect.Field;
@@ -34,8 +34,8 @@ import java.util.Map;
import java.util.Set;
import static org.easymock.EasyMock.createMock;
-import static org.junit.Assert.*;
-
+import static org.junit.jupiter.api.Assertions.*;
+
/**
* This test relies on the internal structure of FilterChainResolver in order to check that it got created correctly.
*/
@@ -48,7 +48,7 @@ public class FilterChainResolverProviderTest {
private Key<? extends Filter> key2a;
private FilterChainResolverProvider underTest;
- @Before
+ @BeforeEach
public void setup() {
chains = new LinkedHashMap<String, Key<? extends Filter>[]>();
@@ -61,23 +61,23 @@ public class FilterChainResolverProviderTest {
chains.put("two", new Key[]{key2a});
underTest = new FilterChainResolverProvider(chains);
- }
-
- @Test
- public void testGetDependencies() throws Exception {
+ }
+
+ @Test
+ void testGetDependencies() throws Exception {
Set<Dependency<?>> dependencySet = underTest.getDependencies();
assertEquals(4, dependencySet.size());
- assertTrue("Dependency set doesn't contain key1a.", dependencySet.contains(Dependency.get(key1a)));
- assertTrue("Dependency set doesn't contain key1b.", dependencySet.contains(Dependency.get(key1b)));
- assertTrue("Dependency set doesn't contain key1c.", dependencySet.contains(Dependency.get(key1c)));
- assertTrue("Dependency set doesn't contain key2a.", dependencySet.contains(Dependency.get(key2a)));
- }
-
-
- @Test
- public void testGet() throws Exception {
+ assertTrue(dependencySet.contains(Dependency.get(key1a)), "Dependency set doesn't contain key1a.");
+ assertTrue(dependencySet.contains(Dependency.get(key1b)), "Dependency set doesn't contain key1b.");
+ assertTrue(dependencySet.contains(Dependency.get(key1c)), "Dependency set doesn't contain key1c.");
+ assertTrue(dependencySet.contains(Dependency.get(key2a)), "Dependency set doesn't contain key2a.");
+ }
+
+
+ @Test
+ void testGet() throws Exception {
Injector injector = createMock(Injector.class);
PatternMatcher patternMatcher = createMock(PatternMatcher.class);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/FilterConfigTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/FilterConfigTest.java
index 39192072b..f9f88c350 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/FilterConfigTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/FilterConfigTest.java
@@ -23,17 +23,17 @@ import com.google.inject.Injector;
import com.google.inject.Provides;
import org.apache.shiro.guice.ShiroModuleTest;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
-import org.apache.shiro.web.util.WebUtils;
-import org.junit.Test;
+import org.apache.shiro.web.util.WebUtils;
+import org.junit.jupiter.api.Test;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertNotNull;
-
+import static org.easymock.EasyMock.*;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
public class FilterConfigTest {
private FilterChainResolver setupResolver() {
final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
@@ -56,10 +56,10 @@ public class FilterConfigTest {
});
GuiceShiroFilter filter = injector.getInstance(GuiceShiroFilter.class);
return filter.getFilterChainResolver();
- }
-
- @Test
- public void testSimple() throws Exception {
+ }
+
+ @Test
+ void testSimple() throws Exception {
FilterChainResolver resolver = setupResolver();
HttpServletResponse response = createNiceMock(HttpServletResponse.class);
FilterChain chain = createNiceMock(FilterChain.class);
@@ -68,10 +68,10 @@ public class FilterConfigTest {
FilterChain resolved = resolver.getChain(request, response, chain);
assertNotNull(resolved);
verify(request);
- }
-
- @Test
- public void testWithConfig() throws Exception {
+ }
+
+ @Test
+ void testWithConfig() throws Exception {
FilterChainResolver resolver = setupResolver();
HttpServletResponse response = createNiceMock(HttpServletResponse.class);
FilterChain chain = createNiceMock(FilterChain.class);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/GuiceShiroFilterTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/GuiceShiroFilterTest.java
index 464ed55d1..f91e995f2 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/GuiceShiroFilterTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/GuiceShiroFilterTest.java
@@ -21,29 +21,26 @@ package org.apache.shiro.guice.web;
import com.google.inject.spi.InjectionPoint;
import org.apache.shiro.web.config.ShiroFilterConfiguration;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
-import org.apache.shiro.web.mgt.WebSecurityManager;
-import org.junit.Test;
-
+import org.apache.shiro.web.mgt.WebSecurityManager;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.mockito.Mockito.when;
-
-public class GuiceShiroFilterTest {
-
- @Test
- public void ensureInjectable() {
+import static org.mockito.Mockito.when;
+
+public class GuiceShiroFilterTest {
+
+ @Test
+ void ensureInjectable() {
try {
InjectionPoint.forConstructorOf(GuiceShiroFilter.class);
} catch (Exception e) {
fail("Could not create constructor injection point.");
}
- }
-
- @Test
- public void testConstructor() {
+ }
+
+ @Test
+ void testConstructor() {
WebSecurityManager securityManager = mock(WebSecurityManager.class);
FilterChainResolver filterChainResolver = mock(FilterChainResolver.class);
ShiroFilterConfiguration filterConfiguration = mock(ShiroFilterConfiguration.class);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/PathMatchingFilterProviderTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/PathMatchingFilterProviderTest.java
index 93e1522cd..021985a13 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/PathMatchingFilterProviderTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/PathMatchingFilterProviderTest.java
@@ -19,17 +19,17 @@
package org.apache.shiro.guice.web;
import com.google.inject.Key;
-import org.apache.shiro.web.filter.PathMatchingFilter;
-import org.junit.Test;
+import org.apache.shiro.web.filter.PathMatchingFilter;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-import static org.easymock.EasyMock.*;
-
-public class PathMatchingFilterProviderTest {
- @Test
- public void testPostProcess() {
+import static org.easymock.EasyMock.*;
+
+public class PathMatchingFilterProviderTest {
+ @Test
+ void testPostProcess() {
PathMatchingFilter filter = createMock(PathMatchingFilter.class);
expect(filter.processPathConfig("/1", "first")).andReturn(filter);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java
index 598e9f2e6..ac0dc6272 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java
@@ -43,9 +43,9 @@ import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.ServletContainerSessionManager;
-import org.easymock.EasyMock;
-import org.junit.Assume;
-import org.junit.Test;
+import org.easymock.EasyMock;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.Test;
import javax.inject.Named;
import javax.servlet.Filter;
@@ -62,16 +62,17 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.List;
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.*;
-import static org.hamcrest.Matchers.*;
-
-
-public class ShiroWebModuleTest {
-
-
- @Test
- public void basicInstantiation() {
+import static org.easymock.EasyMock.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.hamcrest.Matchers.*;
+
+
+public class ShiroWebModuleTest {
+
+
+ @Test
+ void basicInstantiation() {
final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
ServletContext servletContext = createMock(ServletContext.class);
@@ -97,15 +98,15 @@ public class ShiroWebModuleTest {
assertNotNull(sessionManager);
assertTrue(sessionManager instanceof ServletContainerSessionManager);
assertTrue(((DefaultWebSecurityManager)securityManager).getSessionManager() instanceof ServletContainerSessionManager);
- }
-
- @Test
- public void testBindGuiceFilter() throws Exception {
-
- }
-
- @Test
- public void testBindWebSecurityManager() throws Exception {
+ }
+
+ @Test
+ void testBindGuiceFilter() throws Exception {
+
+ }
+
+ @Test
+ void testBindWebSecurityManager() throws Exception {
final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
ServletContext servletContext = createMock(ServletContext.class);
@@ -134,10 +135,10 @@ public class ShiroWebModuleTest {
assertTrue(webSecurityManager instanceof MyDefaultWebSecurityManager);
// SHIRO-435: Check both keys SecurityManager and WebSecurityManager are bound to the same instance
assertTrue( securityManager == webSecurityManager );
- }
-
- @Test
- public void testBindWebEnvironment() throws Exception {
+ }
+
+ @Test
+ void testBindWebEnvironment() throws Exception {
final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
ServletContext servletContext = createMock(ServletContext.class);
@@ -167,13 +168,13 @@ public class ShiroWebModuleTest {
assertTrue(webEnvironment instanceof MyWebEnvironment);
// SHIRO-435: Check both keys Environment and WebEnvironment are bound to the same instance
assertTrue( environment == webEnvironment );
- }
-
- /**
- * @since 1.4
- */
- @Test
- public void testAddFilterChainGuice3and4() {
+ }
+
+ /**
+ * @since 1.4
+ */
+ @Test
+ void testAddFilterChainGuice3and4() {
final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
ServletContext servletContext = createMock(ServletContext.class);
@@ -254,15 +255,15 @@ public class ShiroWebModuleTest {
assertThat(getNextFilter((SimpleFilterChain) filterChain), instanceOf(PermissionsAuthorizationFilter.class));
verify(servletContext, request);
- }
+ }
+
+ /**
+ * @since 1.4
+ */
+ @Test
+ void testAddFilterChainGuice3Only() {
- /**
- * @since 1.4
- */
- @Test
- public void testAddFilterChainGuice3Only() {
-
- Assume.assumeTrue("This test only runs against Guice 3.x", ShiroWebModule.isGuiceVersion3());
+ Assumptions.assumeTrue(ShiroWebModule.isGuiceVersion3(), "This test only runs against Guice 3.x");
final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
ServletContext servletContext = createMock(ServletContext.class);
@@ -324,10 +325,10 @@ public class ShiroWebModuleTest {
assertThat(getNextFilter((SimpleFilterChain) filterChain), instanceOf(PermissionsAuthorizationFilter.class));
verify(servletContext, request);
- }
-
- @Test
- public void testDefaultPath() {
+ }
+
+ @Test
+ void testDefaultPath() {
final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
ServletContext servletContext = createMock(ServletContext.class);
@@ -367,10 +368,10 @@ public class ShiroWebModuleTest {
assertThat(getNextFilter((SimpleFilterChain) filterChain), nullValue());
verify(servletContext, request);
- }
-
- @Test
- public void testDisableGlobalFilters() {
+ }
+
+ @Test
+ void testDisableGlobalFilters() {
final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
ServletContext servletContext = createMock(ServletContext.class);
@@ -415,10 +416,10 @@ public class ShiroWebModuleTest {
assertThat(getNextFilter((SimpleFilterChain) filterChain), nullValue());
verify(servletContext, request);
- }
-
- @Test
- public void testChangeInvalidFilterConfig() {
+ }
+
+ @Test
+ void testChangeInvalidFilterConfig() {
final ShiroModuleTest.MockRealm mockRealm = createMock(ShiroModuleTest.MockRealm.class);
ServletContext servletContext = createMock(ServletContext.class);
@@ -459,7 +460,7 @@ public class ShiroWebModuleTest {
Filter invalidRequestFilter = getNextFilter((SimpleFilterChain) filterChain);
assertThat(invalidRequestFilter, instanceOf(InvalidRequestFilter.class));
- assertFalse("Expected 'blockBackslash' to be false", ((InvalidRequestFilter) invalidRequestFilter).isBlockBackslash());
+ assertFalse(((InvalidRequestFilter) invalidRequestFilter).isBlockBackslash(), "Expected 'blockBackslash' to be false");
assertThat(getNextFilter((SimpleFilterChain) filterChain), instanceOf(FormAuthenticationFilter.class));
assertThat(getNextFilter((SimpleFilterChain) filterChain), nullValue());
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainResolverTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainResolverTest.java
index 586a2b978..99435df4c 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainResolverTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainResolverTest.java
@@ -23,8 +23,8 @@ import com.google.inject.Key;
import com.google.inject.name.Names;
import org.apache.shiro.util.PatternMatcher;
import org.apache.shiro.web.util.WebUtils;
-import org.easymock.IMocksControl;
-import org.junit.Test;
+import org.easymock.IMocksControl;
+import org.junit.jupiter.api.Test;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
@@ -35,17 +35,17 @@ import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertNull;
-
-
+import static org.easymock.EasyMock.*;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+
/**
* Note that this test is highly dependent on the implementation of SimpleFilterChain. There's really no way around that
* that I can see. We determine that the resolver has created it correctly by observing it's behavior.
*/
-public class SimpleFilterChainResolverTest {
- @Test
- public void testGetChain() throws Exception {
+public class SimpleFilterChainResolverTest {
+ @Test
+ void testGetChain() throws Exception {
// test that it uses the pattern matcher - check
// test that the FIRST chain found is the one that gets returned - check
// test that the chain returned actually contains the filters returned by the injector - check
@@ -119,7 +119,7 @@ public class SimpleFilterChainResolverTest {
ctrl.replay();
- assertNull("Expected no chain to match, did not get a null value in return.", underTest.getChain(request, response, originalChain));
+ assertNull(underTest.getChain(request, response, originalChain), "Expected no chain to match, did not get a null value in return.");
ctrl.verify();
}
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainTest.java
index 1ae4ca542..1db04bfc3 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainTest.java
@@ -26,18 +26,18 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.easymock.Capture;
-import org.easymock.IMocksControl;
-import org.junit.Test;
+import org.easymock.IMocksControl;
+import org.junit.jupiter.api.Test;
import static org.easymock.EasyMock.and;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.createStrictControl;
-import static org.easymock.EasyMock.same;
-
-public class SimpleFilterChainTest {
- @Test
- public void testDoFilter() throws Exception {
+import static org.easymock.EasyMock.same;
+
+public class SimpleFilterChainTest {
+ @Test
+ void testDoFilter() throws Exception {
IMocksControl ctrl = createStrictControl();
FilterChain originalChain = ctrl.createMock(FilterChain.class);
diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/WebGuiceEnvironmentTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/WebGuiceEnvironmentTest.java
index f5189f2e3..dc5f62666 100644
--- a/support/guice/src/test/java/org/apache/shiro/guice/web/WebGuiceEnvironmentTest.java
+++ b/support/guice/src/test/java/org/apache/shiro/guice/web/WebGuiceEnvironmentTest.java
@@ -23,28 +23,28 @@ import org.apache.shiro.web.config.ShiroFilterConfiguration;
import org.apache.shiro.web.env.EnvironmentLoaderListener;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.mgt.WebSecurityManager;
-import org.easymock.Capture;
-import org.junit.Test;
+import org.easymock.Capture;
+import org.junit.jupiter.api.Test;
import javax.servlet.ServletContext;
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
-
-public class WebGuiceEnvironmentTest {
-
- @Test
- public void ensureInjectable() {
+import static org.easymock.EasyMock.*;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
+
+public class WebGuiceEnvironmentTest {
+
+ @Test
+ void ensureInjectable() {
try {
InjectionPoint ip = InjectionPoint.forConstructorOf(WebGuiceEnvironment.class);
} catch (Exception e) {
fail("Could not create constructor injection point.");
}
- }
-
- @Test
- public void testConstructor() {
+ }
+
+ @Test
+ void testConstructor() {
WebSecurityManager securityManager = createMock(WebSecurityManager.class);
FilterChainResolver filterChainResolver = createMock(FilterChainResolver.class);
ServletContext servletContext = createMock(ServletContext.class);
diff --git a/support/spring/src/test/java/org/apache/shiro/spring/remoting/SecureRemoteInvocationFactoryTest.java b/support/spring/src/test/java/org/apache/shiro/spring/remoting/SecureRemoteInvocationFactoryTest.java
index 921211215..274fc3ab0 100644
--- a/support/spring/src/test/java/org/apache/shiro/spring/remoting/SecureRemoteInvocationFactoryTest.java
+++ b/support/spring/src/test/java/org/apache/shiro/spring/remoting/SecureRemoteInvocationFactoryTest.java
@@ -23,17 +23,17 @@ import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.util.ThreadContext;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.springframework.remoting.support.RemoteInvocation;
import java.lang.reflect.Method;
import java.util.UUID;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* //TODO - Class JavaDoc!
@@ -41,12 +41,12 @@ import static org.junit.Assert.assertNull;
*/
public class SecureRemoteInvocationFactoryTest {
- @Before
+ @BeforeEach
public void setup() {
ThreadContext.remove();
}
- @After
+ @AfterEach
public void tearDown() {
ThreadContext.remove();
}
@@ -62,7 +62,7 @@ public class SecureRemoteInvocationFactoryTest {
}
@Test
- public void testSessionManagerProxyStartRemoteInvocation() throws Exception {
+ void testSessionManagerProxyStartRemoteInvocation() throws Exception {
SecureRemoteInvocationFactory factory = new SecureRemoteInvocationFactory();
@@ -83,7 +83,7 @@ public class SecureRemoteInvocationFactoryTest {
}
@Test
- public void testSessionManagerProxyNonStartRemoteInvocation() throws Exception {
+ void testSessionManagerProxyNonStartRemoteInvocation() throws Exception {
SecureRemoteInvocationFactory factory = new SecureRemoteInvocationFactory();
diff --git a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AbstractAuthorizationAnnotationTest.java b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AbstractAuthorizationAnnotationTest.java
index 5da049379..5e54cfb37 100644
--- a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AbstractAuthorizationAnnotationTest.java
+++ b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AbstractAuthorizationAnnotationTest.java
@@ -24,14 +24,16 @@ import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.SubjectThreadState;
-import org.apache.shiro.util.ThreadState;
-import org.junit.After;
-import org.junit.Test;
+import org.apache.shiro.util.ThreadState;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
/**
* Common method tests across implementations. In actuality, the methods don't change across
* subclasses - only the mechanism that enables AOP pointcuts and applies advice. Those differences
@@ -58,7 +60,7 @@ public abstract class AbstractAuthorizationAnnotationTest {
this.threadState.bind();
}
- @After
+ @AfterEach
public void clearSubject() {
if (threadState != null) {
threadState.clear();
@@ -78,74 +80,82 @@ public abstract class AbstractAuthorizationAnnotationTest {
PrincipalCollection principals = new SimplePrincipalCollection("test", realm.getName());
bind(new Subject.Builder(securityManager).
principals(principals).authenticated(true).buildSubject());
- }
-
- // GUEST OPERATIONS:
-
- @Test
- public void testGuestImplementation() {
+ }
+
+ // GUEST OPERATIONS:
+
+ @Test
+ void testGuestImplementation() {
bindGuest();
testService.guestImplementation();
- }
-
- @Test(expected = UnauthenticatedException.class)
- public void testGuestImplementationFailure() {
- bindUser();
- testService.guestImplementation();
- }
-
- @Test
- public void testGuestInterface() {
+ }
+
+ @Test
+ void testGuestImplementationFailure() {
+ assertThrows(UnauthenticatedException.class, () -> {
+ bindUser();
+ testService.guestImplementation();
+ });
+ }
+
+ @Test
+ void testGuestInterface() {
bindGuest();
testService.guestInterface();
- }
- //testGuestInterfaceFailure() cannot be in this class - the SchemaAuthorizationAnnotationTest
- //subclass does not support annotations on interfaces (Spring AspectJ pointcut expressions
- //do not support annotations on interface methods). It is instead in the
- //DapcAuthorizationAnnotationTest subclass
-
-
- // USER OPERATIONS
-
- @Test
- public void testUserImplementation() {
+ }
+
+ //testGuestInterfaceFailure() cannot be in this class - the SchemaAuthorizationAnnotationTest
+ //subclass does not support annotations on interfaces (Spring AspectJ pointcut expressions
+ //do not support annotations on interface methods). It is instead in the
+ //DapcAuthorizationAnnotationTest subclass
+
+
+ // USER OPERATIONS
+
+ @Test
+ void testUserImplementation() {
bindUser();
testService.userImplementation();
- }
-
- @Test(expected = UnauthenticatedException.class)
- public void testUserImplementationFailure() {
- bindGuest();
- testService.userImplementation();
- }
-
- @Test
- public void testUserInterface() {
+ }
+
+ @Test
+ void testUserImplementationFailure() {
+ assertThrows(UnauthenticatedException.class, () -> {
+ bindGuest();
+ testService.userImplementation();
+ });
+ }
+
+ @Test
+ void testUserInterface() {
bindUser();
testService.userInterface();
- }
- //testUserInterfaceFailure() cannot be in this class - the SchemaAuthorizationAnnotationTest
- //subclass does not support annotations on interfaces (Spring AspectJ pointcut expressions
- //do not support annotations on interface methods). It is instead in the
- //DapcAuthorizationAnnotationTest subclass
-
-
- // AUTHENTICATED USER OPERATIONS
-
- @Test
- public void testAuthenticatedImplementation() {
+ }
+
+ //testUserInterfaceFailure() cannot be in this class - the SchemaAuthorizationAnnotationTest
+ //subclass does not support annotations on interfaces (Spring AspectJ pointcut expressions
+ //do not support annotations on interface methods). It is instead in the
+ //DapcAuthorizationAnnotationTest subclass
+
+
+ // AUTHENTICATED USER OPERATIONS
+
+ @Test
+ void testAuthenticatedImplementation() {
bindAuthenticatedUser();
testService.authenticatedImplementation();
- }
-
- @Test(expected = UnauthenticatedException.class)
- public void testAuthenticatedImplementationFailure() {
- bindUser();
- testService.authenticatedImplementation();
- }
-
- @Test
- public void testAuthenticatedInterface() {
+ }
+
+ @Test
+ void testAuthenticatedImplementationFailure() {
+ assertThrows(UnauthenticatedException.class, () -> {
+ bindUser();
+ testService.authenticatedImplementation();
+ });
+ }
+
+ @Test
+ void testAuthenticatedInterface() {
bindAuthenticatedUser();
testService.authenticatedInterface();
}
diff --git a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AuthorizationAttributeSourceAdvisorTest.java b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AuthorizationAttributeSourceAdvisorTest.java
index 5294f02dc..c1cddd50f 100644
--- a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AuthorizationAttributeSourceAdvisorTest.java
+++ b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/AuthorizationAttributeSourceAdvisorTest.java
@@ -19,10 +19,10 @@
package org.apache.shiro.spring.security.interceptor;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class AuthorizationAttributeSourceAdvisorTest {
@@ -69,39 +69,39 @@ public class AuthorizationAttributeSourceAdvisorTest {
}
@Test
- public void matches() throws NoSuchMethodException {
+ void matches() throws NoSuchMethodException {
assertTrue(
- "the method is annotated, should match",
new AuthorizationAttributeSourceAdvisor().matches(
Secured.class.getDeclaredMethod("secureMethod"), Secured.class
- ));
+ ),
+ "the method is annotated, should match");
assertFalse(
- "the method is not annotated, should not match",
new AuthorizationAttributeSourceAdvisor().matches(
Secured.class.getDeclaredMethod("unsecuredMethod"), Secured.class
- ));
+ ),
+ "the method is not annotated, should not match");
assertTrue(
- "the method declaration is annotated in the interface, should match",
new AuthorizationAttributeSourceAdvisor().matches(
ServiceInterface.class.getDeclaredMethod("secureMethod"), ServiceImpl.class
- ));
+ ),
+ "the method declaration is annotated in the interface, should match");
assertFalse(
- "not annotated method, should not match",
new AuthorizationAttributeSourceAdvisor().matches(
ServiceInterface.class.getDeclaredMethod("unsecuredMethod"), ServiceImpl.class
- ));
+ ),
+ "not annotated method, should not match");
assertTrue(
- "the method declaration is in the interface with type-annotation, should match",
new AuthorizationAttributeSourceAdvisor().matches(
SafeServiceInterface.class.getDeclaredMethod("someMethod"), SafeServiceInterface.class
- ));
+ ),
+ "the method declaration is in the interface with type-annotation, should match");
assertTrue(
- "the method declaration is in the interface with type-annotation, should match",
new AuthorizationAttributeSourceAdvisor().matches(
SafeServiceImpl.class.getDeclaredMethod("someMethod"), SafeServiceImpl.class
- ));
+ ),
+ "the method declaration is in the interface with type-annotation, should match");
}
diff --git a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/DapcAuthorizationAnnotationTest.java b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/DapcAuthorizationAnnotationTest.java
index 669067dcb..e362299db 100644
--- a/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/DapcAuthorizationAnnotationTest.java
+++ b/support/spring/src/test/java/org/apache/shiro/spring/security/interceptor/DapcAuthorizationAnnotationTest.java
@@ -18,12 +18,14 @@
*/
package org.apache.shiro.spring.security.interceptor;
-import org.apache.shiro.authz.UnauthenticatedException;
-import org.junit.Test;
+import org.apache.shiro.authz.UnauthenticatedException;
+import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
/**
* All the tests in the parent class are run. This class only exists to ensure that a
* DefaultAutoProxyCreator Spring AOP environment exists and enables annotations correctly as
@@ -35,23 +37,29 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
-public class DapcAuthorizationAnnotationTest extends AbstractAuthorizationAnnotationTest {
-
- @Test(expected = UnauthenticatedException.class)
- public void testGuestInterfaceFailure() {
- bindUser();
- testService.guestInterface();
- }
-
- @Test(expected = UnauthenticatedException.class)
- public void testUserInterfaceFailure() {
- bindGuest();
- testService.userInterface();
- }
-
- @Test(expected = UnauthenticatedException.class)
- public void testAuthenticatedInterfaceFailure() {
- bindGuest();
- testService.authenticatedInterface();
+public class DapcAuthorizationAnnotationTest extends AbstractAuthorizationAnnotationTest {
+
+ @Test
+ void testGuestInterfaceFailure() {
+ assertThrows(UnauthenticatedException.class, () -> {
+ bindUser();
+ testService.guestInterface();
+ });
+ }
+
+ @Test
+ void testUserInterfaceFailure() {
+ assertThrows(UnauthenticatedException.class, () -> {
+ bindGuest();
+ testService.userInterface();
+ });
+ }
+
+ @Test
+ void testAuthenticatedInterfaceFailure() {
+ assertThrows(UnauthenticatedException.class, () -> {
+ bindGuest();
+ testService.authenticatedInterface();
+ });
}
}
diff --git a/support/spring/src/test/java/org/apache/shiro/spring/web/ShiroFilterFactoryBeanTest.java b/support/spring/src/test/java/org/apache/shiro/spring/web/ShiroFilterFactoryBeanTest.java
index 603d1c4aa..a10bb9d14 100644
--- a/support/spring/src/test/java/org/apache/shiro/spring/web/ShiroFilterFactoryBeanTest.java
+++ b/support/spring/src/test/java/org/apache/shiro/spring/web/ShiroFilterFactoryBeanTest.java
@@ -24,7 +24,7 @@ import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.*;
@@ -33,7 +33,7 @@ import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for the {@link ShiroFilterFactoryBean} implementation.
@@ -45,7 +45,7 @@ import static org.junit.Assert.*;
public class ShiroFilterFactoryBeanTest {
@Test
- public void testFilterDefinition() {
+ void testFilterDefinition() {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("org/apache/shiro/spring/web/ShiroFilterFactoryBeanTest.xml");
@@ -70,7 +70,7 @@ public class ShiroFilterFactoryBeanTest {
* @throws Exception if there is any unexpected error
*/
@Test
- public void testFilterDefinitionWithInit() throws Exception {
+ void testFilterDefinitionWithInit() throws Exception {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("org/apache/shiro/spring/web/ShiroFilterFactoryBeanTest.xml");
diff --git a/web/src/test/java/org/apache/shiro/web/config/WebIniSecurityManagerFactoryTest.java b/web/src/test/java/org/apache/shiro/web/config/WebIniSecurityManagerFactoryTest.java
index a0fdcca1f..a1071fe16 100644
--- a/web/src/test/java/org/apache/shiro/web/config/WebIniSecurityManagerFactoryTest.java
+++ b/web/src/test/java/org/apache/shiro/web/config/WebIniSecurityManagerFactoryTest.java
@@ -22,13 +22,13 @@ import org.apache.shiro.config.Ini;
import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.servlet.Filter;
import java.util.Map;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* TODO - Class JavaDoc
@@ -43,7 +43,7 @@ public class WebIniSecurityManagerFactoryTest {
* filters to the pool of beans before the INI configuration is interpreted.
*/
@Test
- public void testDefaultFiltersPresent() {
+ void testDefaultFiltersPresent() {
Ini ini = new Ini();
//just a normal configuration line in the MAIN section for any of the default filters should work
//out of the box. So, create the main section and just config one of them:
diff --git a/web/src/test/java/org/apache/shiro/web/env/EnvironmentLoaderServiceTest.java b/web/src/test/java/org/apache/shiro/web/env/EnvironmentLoaderServiceTest.java
index db4eb5b3b..568324023 100644
--- a/web/src/test/java/org/apache/shiro/web/env/EnvironmentLoaderServiceTest.java
+++ b/web/src/test/java/org/apache/shiro/web/env/EnvironmentLoaderServiceTest.java
@@ -20,8 +20,8 @@ package org.apache.shiro.web.env;
import org.apache.shiro.config.ConfigurationException;
import org.easymock.EasyMock;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import javax.servlet.ServletContext;
import java.util.Arrays;
@@ -44,8 +44,8 @@ import static org.mockito.Mockito.when;
*/
public class EnvironmentLoaderServiceTest {
- @Test()
- public void singleServiceTest() throws Exception {
+ @Test
+ void singleServiceTest() throws Exception {
ServletContext servletContext = EasyMock.mock(ServletContext.class);
expect(servletContext.getInitParameter("shiroEnvironmentClass")).andReturn(null);
@@ -66,7 +66,7 @@ public class EnvironmentLoaderServiceTest {
}
@Test
- public void testDefaultWebEnvironment() {
+ void testDefaultWebEnvironment() {
ServletContext servletContext = EasyMock.mock(ServletContext.class);
expect(servletContext.getInitParameter("shiroEnvironmentClass"))
.andReturn(DefaultWebEnvironment.class.getName());
@@ -83,8 +83,8 @@ public class EnvironmentLoaderServiceTest {
assertThat(environment.getServletContext(), sameInstance(servletContext));
}
- @Test()
- public void multipleServiceTest() throws Exception {
+ @Test
+ void multipleServiceTest() throws Exception {
List<WebEnvironment> environmentList = Arrays.asList(new WebEnvironmentStub(), new WebEnvironmentStub());
@@ -96,7 +96,7 @@ public class EnvironmentLoaderServiceTest {
try {
environmentLoader.createEnvironment(servletContext);
- Assert.fail("Expected ConfigurationException to be thrown");
+ Assertions.fail("Expected ConfigurationException to be thrown");
} catch (ConfigurationException e) {
assertThat(e.getMessage(), stringContainsInOrder("zero or exactly one", "shiroEnvironmentClass"));
}
@@ -105,8 +105,8 @@ public class EnvironmentLoaderServiceTest {
verify(environmentLoader).doLoadWebEnvironmentsFromServiceLoader();
}
- @Test()
- public void loadFromInitParamTest() throws Exception {
+ @Test
+ void loadFromInitParamTest() throws Exception {
ServletContext servletContext = EasyMock.mock(ServletContext.class);
expect(servletContext.getInitParameter(EnvironmentLoader.ENVIRONMENT_CLASS_PARAM)).andReturn(WebEnvironmentStub.class.getName());
diff --git a/web/src/test/java/org/apache/shiro/web/filter/PathMatchingFilterParameterizedTest.java b/web/src/test/java/org/apache/shiro/web/filter/PathMatchingFilterParameterizedTest.java
index 82720adab..5c58c8125 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/PathMatchingFilterParameterizedTest.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/PathMatchingFilterParameterizedTest.java
@@ -18,10 +18,9 @@
*/
package org.apache.shiro.web.filter;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -35,14 +34,11 @@ import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Unit tests for the {@link PathMatchingFilter} implementation.
*/
-@RunWith(Parameterized.class)
public class PathMatchingFilterParameterizedTest {
private static final Logger LOG = LoggerFactory.getLogger(PathMatchingFilterParameterizedTest.class);
@@ -51,14 +47,8 @@ public class PathMatchingFilterParameterizedTest {
private static final String DISABLED_PATH = CONTEXT_PATH + "disabled";
private PathMatchingFilter filter;
-
- @Parameterized.Parameter(0)
public String pattern;
-
- @Parameterized.Parameter(1)
public HttpServletRequest request;
-
- @Parameterized.Parameter(2)
public boolean shouldMatch;
/**
@@ -71,7 +61,6 @@ public class PathMatchingFilterParameterizedTest {
* /foo /foo /foo/*
* </pre>
*/
- @Parameterized.Parameters
public static Object[][] generateParameters() {
return Stream.of(
@@ -110,7 +99,7 @@ public class PathMatchingFilterParameterizedTest {
return request;
}
- @Before
+ @BeforeEach
public void setUp() {
filter = createTestInstance();
}
@@ -140,11 +129,19 @@ public class PathMatchingFilterParameterizedTest {
return filter;
}
- @Test
- public void testBasicAssumptions() {
+ @MethodSource("generateParameters")
+ @ParameterizedTest
+ void testBasicAssumptions(String pattern, HttpServletRequest request, boolean shouldMatch) {
+ initPathMatchingFilterParameterizedTest(pattern, request, shouldMatch);
LOG.debug("Input pattern: [{}], input path: [{}].", this.pattern, this.request.getPathInfo());
boolean matchEnabled = filter.pathsMatch(this.pattern, this.request);
- assertEquals("PathMatch can match URL end with multi Separator, ["+ this.pattern + "] - [" + this.request.getPathInfo() + "]", this.shouldMatch, matchEnabled);
+ assertEquals(this.shouldMatch, matchEnabled, "PathMatch can match URL end with multi Separator, ["+ this.pattern + "] - [" + this.request.getPathInfo() + "]");
verify(request);
}
+
+ public void initPathMatchingFilterParameterizedTest(String pattern, HttpServletRequest request, boolean shouldMatch) {
+ this.pattern = pattern;
+ this.request = request;
+ this.shouldMatch = shouldMatch;
+ }
}
diff --git a/web/src/test/java/org/apache/shiro/web/filter/PathMatchingFilterTest.java b/web/src/test/java/org/apache/shiro/web/filter/PathMatchingFilterTest.java
index e1e29b022..9bfd379b3 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/PathMatchingFilterTest.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/PathMatchingFilterTest.java
@@ -18,16 +18,16 @@
*/
package org.apache.shiro.web.filter;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit tests for the {@link PathMatchingFilter} implementation.
@@ -42,7 +42,7 @@ public class PathMatchingFilterTest {
ServletResponse response;
PathMatchingFilter filter;
- @Before
+ @BeforeEach
public void setUp() {
request = createNiceMock(HttpServletRequest.class);
response = createNiceMock(ServletResponse.class);
@@ -79,7 +79,7 @@ public class PathMatchingFilterTest {
*/
@SuppressWarnings({"JavaDoc"})
@Test
- public void testDisabledBasedOnPath() throws Exception {
+ void testDisabledBasedOnPath() throws Exception {
filter.processPathConfig(DISABLED_PATH, null);
HttpServletRequest request = createNiceMock(HttpServletRequest.class);
@@ -91,7 +91,7 @@ public class PathMatchingFilterTest {
boolean continueFilterChain = filter.preHandle(request, response);
- assertTrue("FilterChain should continue.", continueFilterChain);
+ assertTrue(continueFilterChain, "FilterChain should continue.");
verify(request);
}
@@ -101,7 +101,7 @@ public class PathMatchingFilterTest {
*/
@SuppressWarnings({"JavaDoc"})
@Test
- public void testEnabled() throws Exception {
+ void testEnabled() throws Exception {
//Configure the filter to reflect 2 configured paths. This test will simulate a request to the
//enabled path
filter.processPathConfig(DISABLED_PATH, null);
@@ -118,7 +118,7 @@ public class PathMatchingFilterTest {
boolean continueFilterChain = filter.preHandle(request, response);
- assertFalse("FilterChain should NOT continue.", continueFilterChain);
+ assertFalse(continueFilterChain, "FilterChain should NOT continue.");
verify(request);
}
@@ -127,7 +127,7 @@ public class PathMatchingFilterTest {
* Test asserting <a href="https://issues.apache.org/jira/browse/SHIRO-742">SHIRO-742<a/>.
*/
@Test
- public void testPathMatchEqualUrlSeparatorEnabled() {
+ void testPathMatchEqualUrlSeparatorEnabled() {
expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
expect(request.getRequestURI()).andReturn("/").anyTimes();
expect(request.getServletPath()).andReturn("").anyTimes();
@@ -135,7 +135,7 @@ public class PathMatchingFilterTest {
replay(request);
boolean matchEnabled = filter.pathsMatch("/", request);
- assertTrue("PathMatch can match URL end with Separator", matchEnabled);
+ assertTrue(matchEnabled, "PathMatch can match URL end with Separator");
verify(request);
}
@@ -143,7 +143,7 @@ public class PathMatchingFilterTest {
* Test asserting <a href="https://issues.apache.org/jira/browse/SHIRO-682">SHIRO-682<a/>.
*/
@Test
- public void testPathMatchEEnabled() {
+ void testPathMatchEEnabled() {
expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
expect(request.getRequestURI()).andReturn("/resource/book").anyTimes();
expect(request.getServletPath()).andReturn("").anyTimes();
@@ -151,7 +151,7 @@ public class PathMatchingFilterTest {
replay(request);
boolean matchEnabled = filter.pathsMatch("/resource/book", request);
- assertTrue("PathMatch can match URL end with Separator", matchEnabled);
+ assertTrue(matchEnabled, "PathMatch can match URL end with Separator");
verify(request);
}
@@ -159,7 +159,7 @@ public class PathMatchingFilterTest {
* Test asserting <a href="https://issues.apache.org/jira/browse/SHIRO-682">SHIRO-682<a/>.
*/
@Test
- public void testPathMatchEndWithUrlSeparatorEnabled() {
+ void testPathMatchEndWithUrlSeparatorEnabled() {
expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
expect(request.getRequestURI()).andReturn("/resource/book/").anyTimes();
expect(request.getServletPath()).andReturn("").anyTimes();
@@ -167,7 +167,7 @@ public class PathMatchingFilterTest {
replay(request);
boolean matchEnabled = filter.pathsMatch("/resource/book", request);
- assertTrue("PathMatch can match URL end with Separator", matchEnabled);
+ assertTrue(matchEnabled, "PathMatch can match URL end with Separator");
verify(request);
}
@@ -175,7 +175,7 @@ public class PathMatchingFilterTest {
* Test asserting <a href="https://issues.apache.org/jira/browse/SHIRO-682">SHIRO-682<a/>.
*/
@Test
- public void testPathMatchEndWithMultiUrlSeparatorEnabled() {
+ void testPathMatchEndWithMultiUrlSeparatorEnabled() {
expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
expect(request.getRequestURI()).andReturn("/resource/book//").anyTimes();
expect(request.getServletPath()).andReturn("").anyTimes();
@@ -183,7 +183,7 @@ public class PathMatchingFilterTest {
replay(request);
boolean matchEnabled = filter.pathsMatch("/resource/book", request);
- assertTrue("PathMatch can match URL end with multi Separator", matchEnabled);
+ assertTrue(matchEnabled, "PathMatch can match URL end with multi Separator");
verify(request);
}
diff --git a/web/src/test/java/org/apache/shiro/web/filter/authc/AnonymousFilterTest.java b/web/src/test/java/org/apache/shiro/web/filter/authc/AnonymousFilterTest.java
index 7507ea697..4f71b63c9 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/authc/AnonymousFilterTest.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/authc/AnonymousFilterTest.java
@@ -18,8 +18,9 @@
*/
package org.apache.shiro.web.filter.authc;
-import static org.junit.Assert.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test for {@link org.apache.shiro.web.filter.authc.AnonymousFilter}.
@@ -29,7 +30,7 @@ import org.junit.Test;
public class AnonymousFilterTest {
@Test
- public void test() {
+ void test() {
AnonymousFilter filter = new AnonymousFilter();
boolean allow = filter.onPreHandle(null, null, null);
assertTrue(allow);
diff --git a/web/src/test/java/org/apache/shiro/web/filter/authz/HostFilterTest.java b/web/src/test/java/org/apache/shiro/web/filter/authz/HostFilterTest.java
index 8781590b7..1dbd9e087 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/authz/HostFilterTest.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/authz/HostFilterTest.java
@@ -18,16 +18,17 @@
*/
package org.apache.shiro.web.filter.authz;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.util.regex.Pattern;
+import org.junit.jupiter.api.Test;
+
/** @since 1.0 */
public class HostFilterTest {
@Test
- public void testPrivateClassC() {
+ void testPrivateClassC() {
Pattern p = Pattern.compile(HostFilter.PRIVATE_CLASS_C_REGEX);
String base = "192.168.";
@@ -42,7 +43,7 @@ public class HostFilterTest {
}
@Test
- public void testPrivateClassB() {
+ void testPrivateClassB() {
Pattern p = Pattern.compile(HostFilter.PRIVATE_CLASS_B_REGEX);
String base = "172.";
diff --git a/web/src/test/java/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilterTest.java b/web/src/test/java/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilterTest.java
index e79874571..71dc7f9ec 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilterTest.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilterTest.java
@@ -18,14 +18,14 @@
*/
package org.apache.shiro.web.filter.authz;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
public class HttpMethodPermissionFilterTest {
@Test
- public void testPermissionMapping() {
+ void testPermissionMapping() {
// Testing the isAccessAllowed would be easier, but would need to mock out the servlet request
HttpMethodPermissionFilter filter = new HttpMethodPermissionFilter();
@@ -33,16 +33,16 @@ public class HttpMethodPermissionFilterTest {
String[] permsBefore = {"foo", "bar"};
String[] permsAfter = filter.buildPermissions(permsBefore, filter.getHttpMethodAction("get"));
- Assert.assertEquals(2, permsAfter.length);
- Assert.assertEquals("foo:read", permsAfter[0]);
- Assert.assertEquals("bar:read", permsAfter[1]);
-
- Assert.assertEquals("foo:read", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("head"))[0]);
- Assert.assertEquals("foo:update", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("put"))[0]);
- Assert.assertEquals("foo:create", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("post"))[0]);
- Assert.assertEquals("foo:create", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("mkcol"))[0]);
- Assert.assertEquals("foo:delete", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("delete"))[0]);
- Assert.assertEquals("foo:read", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("options"))[0]);
- Assert.assertEquals("foo:read", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("trace"))[0]);
+ Assertions.assertEquals(2, permsAfter.length);
+ Assertions.assertEquals("foo:read", permsAfter[0]);
+ Assertions.assertEquals("bar:read", permsAfter[1]);
+
+ Assertions.assertEquals("foo:read", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("head"))[0]);
+ Assertions.assertEquals("foo:update", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("put"))[0]);
+ Assertions.assertEquals("foo:create", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("post"))[0]);
+ Assertions.assertEquals("foo:create", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("mkcol"))[0]);
+ Assertions.assertEquals("foo:delete", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("delete"))[0]);
+ Assertions.assertEquals("foo:read", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("options"))[0]);
+ Assertions.assertEquals("foo:read", filter.buildPermissions(permsBefore, filter.getHttpMethodAction("trace"))[0]);
}
}
diff --git a/web/src/test/java/org/apache/shiro/web/filter/authz/IpAddressMatcherTests.java b/web/src/test/java/org/apache/shiro/web/filter/authz/IpAddressMatcherTests.java
index ad87303a3..763131507 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/authz/IpAddressMatcherTests.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/authz/IpAddressMatcherTests.java
@@ -15,10 +15,10 @@
*/
package org.apache.shiro.web.filter.authz;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
+import org.junit.jupiter.api.Test;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @since 2.0
@@ -30,41 +30,41 @@ public class IpAddressMatcherTests {
final String ipv4Address = "192.168.1.104";
@Test
- public void ipv6MatcherMatchesIpv6Address() {
+ void ipv6MatcherMatchesIpv6Address() {
assertTrue(v6matcher.matches(ipv6Address));
}
-
+
@Test
- public void ipv6MatcherDoesntMatchIpv4Address() {
+ void ipv6MatcherDoesntMatchIpv4Address() {
assertFalse(v6matcher.matches(ipv4Address));
}
-
+
@Test
- public void ipv4MatcherMatchesIpv4Address() {
+ void ipv4MatcherMatchesIpv4Address() {
assertTrue(v4matcher.matches(ipv4Address));
}
-
+
@Test
- public void ipv4SubnetMatchesCorrectly() throws Exception {
+ void ipv4SubnetMatchesCorrectly() throws Exception {
IpAddressMatcher matcher = new IpAddressMatcher("192.168.1.0/24");
assertTrue(matcher.matches(ipv4Address));
matcher = new IpAddressMatcher("192.168.1.128/25");
assertFalse(matcher.matches(ipv4Address));
assertTrue(matcher.matches("192.168.1.159"));
}
-
+
@Test
- public void ipv6RangeMatches() throws Exception {
+ void ipv6RangeMatches() throws Exception {
IpAddressMatcher matcher = new IpAddressMatcher("2001:DB8::/48");
assertTrue(matcher.matches("2001:DB8:0:0:0:0:0:0"));
assertTrue(matcher.matches("2001:DB8:0:0:0:0:0:1"));
assertTrue(matcher.matches("2001:DB8:0:FFFF:FFFF:FFFF:FFFF:FFFF"));
assertFalse(matcher.matches("2001:DB8:1:0:0:0:0:0"));
}
-
+
// https://github.com/spring-projects/spring-security/issues/1970q
@Test
- public void zeroMaskMatchesAnything() throws Exception {
+ void zeroMaskMatchesAnything() throws Exception {
IpAddressMatcher matcher = new IpAddressMatcher("0.0.0.0/0");
assertTrue(matcher.matches("123.4.5.6"));
diff --git a/web/src/test/java/org/apache/shiro/web/filter/authz/IpFilterTest.java b/web/src/test/java/org/apache/shiro/web/filter/authz/IpFilterTest.java
index c5def24f7..88164315a 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/authz/IpFilterTest.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/authz/IpFilterTest.java
@@ -18,7 +18,7 @@
*/
package org.apache.shiro.web.filter.authz;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@@ -29,8 +29,7 @@ import java.util.Collection;
import java.util.Collections;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* Test cases for the {@link AuthorizationFilter} class.
@@ -39,7 +38,7 @@ import static org.junit.Assert.assertFalse;
public class IpFilterTest {
@Test
- public void accessShouldBeDeniedByDefault() throws Exception {
+ void accessShouldBeDeniedByDefault() throws Exception {
IpFilter filter = new IpFilter();
HttpServletRequest request = createNiceMock(HttpServletRequest.class);
expect(request.getRemoteAddr()).andReturn("192.168.42.42");
@@ -49,7 +48,7 @@ public class IpFilterTest {
}
@Test
- public void accessShouldBeDeniedWhenNotInTheAllowedSet() throws Exception {
+ void accessShouldBeDeniedWhenNotInTheAllowedSet() throws Exception {
IpFilter filter = new IpFilter();
filter.setAuthorizedIps("192.168.33/24");
HttpServletRequest request = createNiceMock(HttpServletRequest.class);
@@ -60,7 +59,7 @@ public class IpFilterTest {
}
@Test
- public void accessShouldBeGrantedToIpsInTheAllowedSet() throws Exception {
+ void accessShouldBeGrantedToIpsInTheAllowedSet() throws Exception {
IpFilter filter = new IpFilter();
filter.setAuthorizedIps("192.168.32/24 192.168.33/24 192.168.34/24");
HttpServletRequest request = createNiceMock(HttpServletRequest.class);
@@ -71,7 +70,7 @@ public class IpFilterTest {
}
@Test
- public void deniedTakesPrecedenceOverAllowed() throws Exception {
+ void deniedTakesPrecedenceOverAllowed() throws Exception {
IpFilter filter = new IpFilter();
filter.setAuthorizedIps("192.168.0.0/16");
filter.setDeniedIps("192.168.33.0/24");
@@ -83,7 +82,7 @@ public class IpFilterTest {
}
@Test
- public void willBlockAndAllowBasedOnIpSource() throws Exception {
+ void willBlockAndAllowBasedOnIpSource() throws Exception {
IpSource source = new IpSource() {
public Collection<String> getAuthorizedIps() {
return Collections.singleton("192.168.0.0/16");
diff --git a/web/src/test/java/org/apache/shiro/web/filter/authz/PortFilterTest.java b/web/src/test/java/org/apache/shiro/web/filter/authz/PortFilterTest.java
index 98691d5bb..f5a0aeb26 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/authz/PortFilterTest.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/authz/PortFilterTest.java
@@ -18,14 +18,14 @@
*/
package org.apache.shiro.web.filter.authz;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.*;
-
+import static org.junit.jupiter.api.Assertions.*;
+
/**
* Tests for the {@link PortFilter} class.
*
@@ -39,10 +39,10 @@ public class PortFilterTest {
expect(request.getServerName()).andReturn("localhost");
expect(request.getRequestURI()).andReturn("/");
return request;
- }
-
- @Test
- public void testDefault() throws Exception {
+ }
+
+ @Test
+ void testDefault() throws Exception {
HttpServletResponse response = createNiceMock(HttpServletResponse.class);
HttpServletRequest request = createBaseMockRequest();
@@ -56,17 +56,17 @@ public class PortFilterTest {
verify(request);
verify(response);
assertFalse(result);
- }
-
- /**
- * This tests the case where the client (e.g. browser) specifies a simple request to http://localhost/
- * (i.e. http scheme with the implied port of 80). The redirectURL should reflect the configured port (8080) instead
- * of the implied port 80.
- *
- * @throws Exception if there is a test failure
- */
- @Test
- public void testConfiguredPort() throws Exception {
+ }
+
+ /**
+ * This tests the case where the client (e.g. browser) specifies a simple request to http://localhost/
+ * (i.e. http scheme with the implied port of 80). The redirectURL should reflect the configured port (8080) instead
+ * of the implied port 80.
+ *
+ * @throws Exception if there is a test failure
+ */
+ @Test
+ void testConfiguredPort() throws Exception {
int port = 8080;
HttpServletResponse response = createNiceMock(HttpServletResponse.class);
HttpServletRequest request = createBaseMockRequest();
diff --git a/web/src/test/java/org/apache/shiro/web/filter/authz/SslFilterTest.java b/web/src/test/java/org/apache/shiro/web/filter/authz/SslFilterTest.java
index 2e1fe2f57..c1bd9c72c 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/authz/SslFilterTest.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/authz/SslFilterTest.java
@@ -22,15 +22,15 @@ import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import static org.apache.shiro.web.filter.authz.SslFilter.HSTS.*;
import org.easymock.Capture;
import org.easymock.CaptureType;
import static org.easymock.EasyMock.*;
import org.easymock.IAnswer;
-import static org.junit.Assert.*;
-import org.junit.Before;
+import static org.junit.jupiter.api.Assertions.*;
public class SslFilterTest {
@@ -38,7 +38,7 @@ public class SslFilterTest {
private HttpServletResponse response;
private SslFilter sslFilter;
- @Before
+ @BeforeEach
public void before() {
request = createNiceMock(HttpServletRequest.class);
response = createNiceMock(HttpServletResponse.class);
@@ -75,20 +75,20 @@ public class SslFilterTest {
}
@Test
- public void testDisabledByDefault() {
+ void testDisabledByDefault() {
sslFilter.postHandle(request, response);
assertNull(response.getHeader(HTTP_HEADER));
}
@Test
- public void testDefaultValues() {
+ void testDefaultValues() {
sslFilter.getHsts().setEnabled(true);
sslFilter.postHandle(request, response);
assertEquals("max-age=" + DEFAULT_MAX_AGE, response.getHeader(HTTP_HEADER));
}
-
+
@Test
- public void testSetProperties() {
+ void testSetProperties() {
sslFilter.getHsts().setEnabled(true);
sslFilter.getHsts().setMaxAge(7776000);
sslFilter.getHsts().setIncludeSubDomains(true);
diff --git a/web/src/test/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolverTest.java b/web/src/test/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolverTest.java
index 76bff556c..a404a1fd0 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolverTest.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolverTest.java
@@ -20,8 +20,8 @@ package org.apache.shiro.web.filter.mgt;
import org.apache.shiro.util.AntPathMatcher;
import org.apache.shiro.web.WebTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
@@ -32,10 +32,7 @@ import javax.servlet.http.HttpServletResponse;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -49,13 +46,13 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
private PathMatchingFilterChainResolver resolver;
- @Before
+ @BeforeEach
public void setUp() {
resolver = new PathMatchingFilterChainResolver();
}
@Test
- public void testNewInstance() {
+ void testNewInstance() {
assertNotNull(resolver.getPathMatcher());
assertTrue(resolver.getPathMatcher() instanceof AntPathMatcher);
assertNotNull(resolver.getFilterChainManager());
@@ -63,7 +60,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
}
@Test
- public void testNewInstanceWithFilterConfig() {
+ void testNewInstanceWithFilterConfig() {
FilterConfig mock = createNiceMockFilterConfig();
resolver = new PathMatchingFilterChainResolver(mock);
assertNotNull(resolver.getPathMatcher());
@@ -74,7 +71,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
}
@Test
- public void testSetters() {
+ void testSetters() {
resolver.setPathMatcher(new AntPathMatcher());
assertNotNull(resolver.getPathMatcher());
assertTrue(resolver.getPathMatcher() instanceof AntPathMatcher);
@@ -84,7 +81,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
}
@Test
- public void testGetChainsWithoutChains() {
+ void testGetChainsWithoutChains() {
ServletRequest request = mock(HttpServletRequest.class);
ServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -93,7 +90,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
}
@Test
- public void testGetChainsWithMatch() {
+ void testGetChainsWithMatch() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -108,9 +105,9 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
assertNotNull(resolved);
verify(request).getServletPath();
}
-
+
@Test
- public void testPathTraversalWithDot() {
+ void testPathTraversalWithDot() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -125,9 +122,9 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
assertNotNull(resolved);
verify(request).getServletPath();
}
-
+
@Test
- public void testPathTraversalWithDotDot() {
+ void testPathTraversalWithDotDot() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -143,7 +140,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
}
@Test
- public void testGetChainsWithoutMatch() {
+ void testGetChainsWithoutMatch() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -163,7 +160,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
* Test asserting <a href="https://issues.apache.org/jira/browse/SHIRO-682">SHIRO-682<a/>.
*/
@Test
- public void testGetChain() {
+ void testGetChain() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -183,7 +180,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
* Test asserting <a href="https://issues.apache.org/jira/browse/SHIRO-742">SHIRO-742<a/>.
*/
@Test
- public void testGetChainEqualUrlSeparator() {
+ void testGetChainEqualUrlSeparator() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -203,7 +200,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
* Test asserting <a href="https://issues.apache.org/jira/browse/SHIRO-682">SHIRO-682<a/>.
*/
@Test
- public void testGetChainEndWithUrlSeparator() {
+ void testGetChainEndWithUrlSeparator() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -223,7 +220,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
* Test asserting <a href="https://issues.apache.org/jira/browse/SHIRO-682">SHIRO-682<a/>.
*/
@Test
- public void testGetChainEndWithMultiUrlSeparator() {
+ void testGetChainEndWithMultiUrlSeparator() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -240,7 +237,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
}
@Test
- public void testMultipleChainsPathEndsWithSlash() {
+ void testMultipleChainsPathEndsWithSlash() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -260,7 +257,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
* Test asserting <a href="https://issues.apache.org/jira/browse/SHIRO-825">SHIRO-825<a/>.
*/
@Test
- public void testGetChainWhenPathEndsWithSlash() {
+ void testGetChainWhenPathEndsWithSlash() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
@@ -280,7 +277,7 @@ public class PathMatchingFilterChainResolverTest extends WebTest {
* Test asserting <a href="https://issues.apache.org/jira/browse/SHIRO-825">SHIRO-825<a/>.
*/
@Test
- public void testGetChainWhenPathDoesNotEndWithSlash() {
+ void testGetChainWhenPathDoesNotEndWithSlash() {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
FilterChain chain = mock(FilterChain.class);
diff --git a/web/src/test/java/org/apache/shiro/web/filter/mgt/SimpleNamedFilterListTest.java b/web/src/test/java/org/apache/shiro/web/filter/mgt/SimpleNamedFilterListTest.java
index a62e13204..c623b3915 100644
--- a/web/src/test/java/org/apache/shiro/web/filter/mgt/SimpleNamedFilterListTest.java
+++ b/web/src/test/java/org/apache/shiro/web/filter/mgt/SimpleNamedFilterListTest.java
@@ -24,14 +24,14 @@ import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.filter.authz.PortFilter;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.apache.shiro.web.filter.authz.SslFilter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import java.util.*;
import static org.easymock.EasyMock.createNiceMock;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test case for the {@link SimpleNamedFilterList} implementation.
@@ -41,26 +41,30 @@ import static org.junit.Assert.*;
public class SimpleNamedFilterListTest {
@Test
- public void testNewInstance() {
+ void testNewInstance() {
@SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"})
SimpleNamedFilterList list = new SimpleNamedFilterList("test");
assertNotNull(list.getName());
assertEquals("test", list.getName());
}
- @Test(expected = IllegalArgumentException.class)
- public void testNewInstanceNameless() {
- new SimpleNamedFilterList(null);
+ @Test
+ void testNewInstanceNameless() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new SimpleNamedFilterList(null);
+ });
}
@Test
- public void testNewInstanceBackingList() {
+ void testNewInstanceBackingList() {
new SimpleNamedFilterList("test", new ArrayList<Filter>());
}
- @Test(expected = NullPointerException.class)
- public void testNewInstanceNullBackingList() {
- new SimpleNamedFilterList("test", null);
+ @Test
+ void testNewInstanceNullBackingList() {
+ assertThrows(NullPointerException.class, () -> {
+ new SimpleNamedFilterList("test", null);
+ });
}
/**
@@ -68,7 +72,7 @@ public class SimpleNamedFilterListTest {
* implementation is a direct pass through.
*/
@Test
- public void testListMethods() {
+ void testListMethods() {
FilterChain mock = createNiceMock(FilterChain.class);
Filter filter = createNiceMock(Filter.class);
diff --git a/web/src/test/java/org/apache/shiro/web/mgt/AbstractWebSecurityManagerTest.java b/web/src/test/java/org/apache/shiro/web/mgt/AbstractWebSecurityManagerTest.java
index 8d08041d4..a54499157 100644
--- a/web/src/test/java/org/apache/shiro/web/mgt/AbstractWebSecurityManagerTest.java
+++ b/web/src/test/java/org/apache/shiro/web/mgt/AbstractWebSecurityManagerTest.java
@@ -19,14 +19,14 @@
package org.apache.shiro.web.mgt;
import org.apache.shiro.util.ThreadContext;
-import org.junit.After;
+import org.junit.jupiter.api.AfterEach;
/**
* @since 1.0
*/
public abstract class AbstractWebSecurityManagerTest {
- @After
+ @AfterEach
public void tearDown() {
ThreadContext.remove();
}
diff --git a/web/src/test/java/org/apache/shiro/web/mgt/CookieRememberMeManagerTest.java b/web/src/test/java/org/apache/shiro/web/mgt/CookieRememberMeManagerTest.java
index ada3cf61c..7ccc47be0 100644
--- a/web/src/test/java/org/apache/shiro/web/mgt/CookieRememberMeManagerTest.java
+++ b/web/src/test/java/org/apache/shiro/web/mgt/CookieRememberMeManagerTest.java
@@ -29,7 +29,7 @@ import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.subject.WebSubject;
import org.apache.shiro.web.subject.WebSubjectContext;
import org.apache.shiro.web.subject.support.DefaultWebSubjectContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
@@ -38,7 +38,7 @@ import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Unit tests for the {@link CookieRememberMeManager} implementation.
@@ -48,7 +48,7 @@ import static org.junit.Assert.*;
public class CookieRememberMeManagerTest {
@Test
- public void onSuccessfulLogin() {
+ void onSuccessfulLogin() {
HttpServletRequest mockRequest = createNiceMock(HttpServletRequest.class);
HttpServletResponse mockResponse = createNiceMock(HttpServletResponse.class);
@@ -89,10 +89,10 @@ public class CookieRememberMeManagerTest {
verify(mockSubject);
verify(cookie);
}
-
+
// SHIRO-183
@Test
- public void getRememberedSerializedIdentityReturnsNullForDeletedCookie() {
+ void getRememberedSerializedIdentityReturnsNullForDeletedCookie() {
HttpServletRequest mockRequest = createMock(HttpServletRequest.class);
HttpServletResponse mockResponse = createMock(HttpServletResponse.class);
WebSubjectContext context = new DefaultWebSubjectContext();
@@ -111,11 +111,11 @@ public class CookieRememberMeManagerTest {
CookieRememberMeManager mgr = new CookieRememberMeManager();
assertNull(mgr.getRememberedSerializedIdentity(context));
}
-
+
// SHIRO-69
@Test
- public void getRememberedPrincipals() {
+ void getRememberedPrincipals() {
HttpServletRequest mockRequest = createMock(HttpServletRequest.class);
HttpServletResponse mockResponse = createMock(HttpServletResponse.class);
WebSubjectContext context = new DefaultWebSubjectContext();
@@ -152,46 +152,48 @@ public class CookieRememberMeManagerTest {
assertTrue(collection.iterator().next().equals("user"));
}
- @Test(expected = CryptoException.class)
- public void getRememberedPrincipalsNoMoreDefaultCipher() {
- HttpServletRequest mockRequest = createMock(HttpServletRequest.class);
- HttpServletResponse mockResponse = createMock(HttpServletResponse.class);
- WebSubjectContext context = new DefaultWebSubjectContext();
- context.setServletRequest(mockRequest);
- context.setServletResponse(mockResponse);
-
- expect(mockRequest.getAttribute(ShiroHttpServletRequest.IDENTITY_REMOVED_KEY)).andReturn(null);
- expect(mockRequest.getContextPath()).andReturn( "/test" );
-
-
- //The following base64 string was determined from the log output of the above 'onSuccessfulLogin' test.
- //This will have to change any time the PrincipalCollection implementation changes:
- final String userPCAesBase64 = "0o6DCfePYTjK4q579qzUFEfkeGRvbBOdKHp2y8/nGAltt1Vz8uW0Z8igeO" +
- "Tq/yBmcw25f3Q0ui/Leg3x0iQZWhw9Bbu0mFHmHsGxEd6mPwtUpSegIjyX5c/kZpqnb7QLdajPWiczX8P" +
- "Oc2Eku5+8ye1u38Y8uKlklHxcYCPh0pRiDSBxfjPsLaDfOpGbmPjZd4SVg68i/++TvUjqBNJyb+pDix3f" +
- "PeuPvReWGcE50iovezVZrEfDOAQ0cZYW35ShypMWOmE9yZnb+p8++StDyAUegryyuIa4pjuRzfMh9D+sN" +
- "F9tm/EnDC1VCer2S/a0AGlWAQiM7jrWt1sNinZcKIrvShaWI21tONJt8WhozNS2H72lk4p92rfLNHeglT" +
- "xObxIYxLfTI9KiToSe1nYmpQmbBO8x1wWDkWBG//EqRvhgbIfQVqJp12T0fJC1nFuZuVhw/ZanaAZGDk8" +
- "7aLMiw3T6FBZtWaspgvfH+0TJrTD8Ra386ekNXNN8JW8=";
-
- Cookie[] cookies = new Cookie[]{
- new Cookie(CookieRememberMeManager.DEFAULT_REMEMBER_ME_COOKIE_NAME, userPCAesBase64)
- };
-
- expect(mockRequest.getCookies()).andReturn(cookies);
- replay(mockRequest);
-
- CookieRememberMeManager mgr = new CookieRememberMeManager();
- // without the old default cipher set, this will fail (expected)
- // mgr.setCipherKey( Base64.decode("kPH+bIxk5D2deZiIxcaaaA=="));
- // this will throw a CryptoException
- mgr.getRememberedPrincipals(context);
+ @Test
+ void getRememberedPrincipalsNoMoreDefaultCipher() {
+ assertThrows(CryptoException.class, () -> {
+ HttpServletRequest mockRequest = createMock(HttpServletRequest.class);
+ HttpServletResponse mockResponse = createMock(HttpServletResponse.class);
+ WebSubjectContext context = new DefaultWebSubjectContext();
+ context.setServletRequest(mockRequest);
+ context.setServletResponse(mockResponse);
+
+ expect(mockRequest.getAttribute(ShiroHttpServletRequest.IDENTITY_REMOVED_KEY)).andReturn(null);
+ expect(mockRequest.getContextPath()).andReturn("/test");
+
+
+ //The following base64 string was determined from the log output of the above 'onSuccessfulLogin' test.
+ //This will have to change any time the PrincipalCollection implementation changes:
+ final String userPCAesBase64 = "0o6DCfePYTjK4q579qzUFEfkeGRvbBOdKHp2y8/nGAltt1Vz8uW0Z8igeO" +
+ "Tq/yBmcw25f3Q0ui/Leg3x0iQZWhw9Bbu0mFHmHsGxEd6mPwtUpSegIjyX5c/kZpqnb7QLdajPWiczX8P" +
+ "Oc2Eku5+8ye1u38Y8uKlklHxcYCPh0pRiDSBxfjPsLaDfOpGbmPjZd4SVg68i/++TvUjqBNJyb+pDix3f" +
+ "PeuPvReWGcE50iovezVZrEfDOAQ0cZYW35ShypMWOmE9yZnb+p8++StDyAUegryyuIa4pjuRzfMh9D+sN" +
+ "F9tm/EnDC1VCer2S/a0AGlWAQiM7jrWt1sNinZcKIrvShaWI21tONJt8WhozNS2H72lk4p92rfLNHeglT" +
+ "xObxIYxLfTI9KiToSe1nYmpQmbBO8x1wWDkWBG//EqRvhgbIfQVqJp12T0fJC1nFuZuVhw/ZanaAZGDk8" +
+ "7aLMiw3T6FBZtWaspgvfH+0TJrTD8Ra386ekNXNN8JW8=";
+
+ Cookie[] cookies = new Cookie[]{
+ new Cookie(CookieRememberMeManager.DEFAULT_REMEMBER_ME_COOKIE_NAME, userPCAesBase64)
+ };
+
+ expect(mockRequest.getCookies()).andReturn(cookies);
+ replay(mockRequest);
+
+ CookieRememberMeManager mgr = new CookieRememberMeManager();
+ // without the old default cipher set, this will fail (expected)
+ // mgr.setCipherKey( Base64.decode("kPH+bIxk5D2deZiIxcaaaA=="));
+ // this will throw a CryptoException
+ mgr.getRememberedPrincipals(context);
+ });
}
// SHIRO-69
@Test
- public void getRememberedPrincipalsDecryptionError() {
+ void getRememberedPrincipalsDecryptionError() {
HttpServletRequest mockRequest = createNiceMock(HttpServletRequest.class);
HttpServletResponse mockResponse = createNiceMock(HttpServletResponse.class);
@@ -212,11 +214,11 @@ public class CookieRememberMeManagerTest {
CookieRememberMeManager mgr = new CookieRememberMeManager();
final PrincipalCollection rememberedPrincipals = mgr.getRememberedPrincipals(context);
- assertNull("rememberedPrincipals should be null on invalid cookies.", rememberedPrincipals);
+ assertNull(rememberedPrincipals, "rememberedPrincipals should be null on invalid cookies.");
}
@Test
- public void onLogout() {
+ void onLogout() {
CookieRememberMeManager mgr = new CookieRememberMeManager();
org.apache.shiro.web.servlet.Cookie cookie = createMock(org.apache.shiro.web.servlet.Cookie.class);
mgr.setCookie(cookie);
@@ -244,7 +246,7 @@ public class CookieRememberMeManagerTest {
}
@Test
- public void shouldIgnoreInvalidCookieValues() {
+ void shouldIgnoreInvalidCookieValues() {
// given
HttpServletRequest mockRequest = createMock(HttpServletRequest.class);
HttpServletResponse mockResponse = createMock(HttpServletResponse.class);
@@ -266,6 +268,6 @@ public class CookieRememberMeManagerTest {
final byte[] rememberedSerializedIdentity = mgr.getRememberedSerializedIdentity(context);
// then
- assertNull("should ignore invalid cookie values", rememberedSerializedIdentity);
+ assertNull(rememberedSerializedIdentity, "should ignore invalid cookie values");
}
}
diff --git a/web/src/test/java/org/apache/shiro/web/mgt/DefaultWebSecurityManagerTest.java b/web/src/test/java/org/apache/shiro/web/mgt/DefaultWebSecurityManagerTest.java
index 443b0309f..93b86fae9 100644
--- a/web/src/test/java/org/apache/shiro/web/mgt/DefaultWebSecurityManagerTest.java
+++ b/web/src/test/java/org/apache/shiro/web/mgt/DefaultWebSecurityManagerTest.java
@@ -31,9 +31,9 @@ import org.apache.shiro.web.config.WebIniSecurityManagerFactory;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.apache.shiro.web.session.mgt.WebSessionManager;
import org.apache.shiro.web.subject.WebSubject;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@@ -42,12 +42,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -60,7 +55,7 @@ public class DefaultWebSecurityManagerTest extends AbstractWebSecurityManagerTes
private DefaultWebSecurityManager sm;
- @Before
+ @BeforeEach
public void setup() {
sm = new DefaultWebSecurityManager();
sm.setSessionMode(DefaultWebSecurityManager.NATIVE_SESSION_MODE);
@@ -71,7 +66,7 @@ public class DefaultWebSecurityManagerTest extends AbstractWebSecurityManagerTes
}
@Override
- @After
+ @AfterEach
public void tearDown() {
sm.destroy();
super.tearDown();
@@ -81,8 +76,8 @@ public class DefaultWebSecurityManagerTest extends AbstractWebSecurityManagerTes
return new WebSubject.Builder(sm, request, response).buildSubject();
}
- @Test
- public void checkSessionManagerDeterminesContainerSessionMode() {
+ @Test
+ void checkSessionManagerDeterminesContainerSessionMode() {
sm.setSessionMode(DefaultWebSecurityManager.NATIVE_SESSION_MODE);
WebSessionManager sessionManager = mock(WebSessionManager.class);
@@ -90,13 +85,13 @@ public class DefaultWebSecurityManagerTest extends AbstractWebSecurityManagerTes
sm.setSessionManager(sessionManager);
- assertTrue("The set SessionManager is not being used to determine isHttpSessionMode.", sm.isHttpSessionMode());
+ assertTrue(sm.isHttpSessionMode(), "The set SessionManager is not being used to determine isHttpSessionMode.");
verify(sessionManager).isServletContainerSessions();
}
@Test
- public void shiroSessionModeInit() {
+ void shiroSessionModeInit() {
sm.setSessionMode(DefaultWebSecurityManager.NATIVE_SESSION_MODE);
}
@@ -109,7 +104,7 @@ public class DefaultWebSecurityManagerTest extends AbstractWebSecurityManagerTes
}
@Test
- public void testLogin() {
+ void testLogin() {
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
@@ -129,7 +124,7 @@ public class DefaultWebSecurityManagerTest extends AbstractWebSecurityManagerTes
}
@Test
- public void testSessionTimeout() {
+ void testSessionTimeout() {
shiroSessionModeInit();
long globalTimeout = 100;
((AbstractSessionManager) sm.getSessionManager()).setGlobalSessionTimeout(globalTimeout);
@@ -155,7 +150,7 @@ public class DefaultWebSecurityManagerTest extends AbstractWebSecurityManagerTes
}
@Test
- public void testGetSubjectByRequestResponsePair() {
+ void testGetSubjectByRequestResponsePair() {
shiroSessionModeInit();
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
@@ -172,7 +167,7 @@ public class DefaultWebSecurityManagerTest extends AbstractWebSecurityManagerTes
}
@Test
- public void testGetSubjectByRequestSessionId() {
+ void testGetSubjectByRequestSessionId() {
shiroSessionModeInit();
@@ -204,7 +199,7 @@ public class DefaultWebSecurityManagerTest extends AbstractWebSecurityManagerTes
* Asserts fix for <a href="https://issues.apache.org/jira/browse/SHIRO-350">SHIRO-350</a>.
*/
@Test
- public void testBuildNonWebSubjectWithDefaultServletContainerSessionManager() {
+ void testBuildNonWebSubjectWithDefaultServletContainerSessionManager() {
Ini ini = new Ini();
Ini.Section section = ini.addSection(IniRealm.USERS_SECTION_NAME);
diff --git a/web/src/test/java/org/apache/shiro/web/mgt/NonIniWebSecurityManagerTest.java b/web/src/test/java/org/apache/shiro/web/mgt/NonIniWebSecurityManagerTest.java
index dfc3e03b6..48ffaa647 100644
--- a/web/src/test/java/org/apache/shiro/web/mgt/NonIniWebSecurityManagerTest.java
+++ b/web/src/test/java/org/apache/shiro/web/mgt/NonIniWebSecurityManagerTest.java
@@ -22,15 +22,15 @@ import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.Ini;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class NonIniWebSecurityManagerTest extends AbstractWebSecurityManagerTest {
private DefaultWebSecurityManager sm;
- @Before
+ @BeforeEach
public void setup() {
sm = new DefaultWebSecurityManager();
Ini ini = new Ini();
@@ -39,7 +39,7 @@ public class NonIniWebSecurityManagerTest extends AbstractWebSecurityManagerTest
sm.setRealm(new IniRealm(ini));
}
- @After
+ @AfterEach
public void tearDown() {
sm.destroy();
super.tearDown();
@@ -49,7 +49,7 @@ public class NonIniWebSecurityManagerTest extends AbstractWebSecurityManagerTest
* Test for SHIRO-646: Unable to login a DelegatingSubject on a DefaultWebSecurityManager.
*/
@Test
- public void testLoginNonWebSubject(){
+ void testLoginNonWebSubject(){
Subject.Builder builder = new Subject.Builder(sm);
Subject subject = builder.buildSubject();
subject.login(new UsernamePasswordToken("lonestarr", "vespa"));
diff --git a/web/src/test/java/org/apache/shiro/web/servlet/OncePerRequestFilterTest.java b/web/src/test/java/org/apache/shiro/web/servlet/OncePerRequestFilterTest.java
index 16096fdd7..0f4f9d6d4 100644
--- a/web/src/test/java/org/apache/shiro/web/servlet/OncePerRequestFilterTest.java
+++ b/web/src/test/java/org/apache/shiro/web/servlet/OncePerRequestFilterTest.java
@@ -18,8 +18,8 @@
*/
package org.apache.shiro.web.servlet;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
@@ -27,7 +27,7 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -46,7 +46,7 @@ public class OncePerRequestFilterTest {
private ServletRequest request;
private ServletResponse response;
- @Before
+ @BeforeEach
public void setUp() {
filter = createTestInstance();
chain = mock(FilterChain.class);
@@ -63,12 +63,12 @@ public class OncePerRequestFilterTest {
*/
@SuppressWarnings({"JavaDoc"})
@Test
- public void testEnabled() throws IOException, ServletException {
+ void testEnabled() throws IOException, ServletException {
when(request.getAttribute(ATTR_NAME)).thenReturn(null);
filter.doFilter(request, response, chain);
- assertEquals("Filter should have executed", 1, filter.filterCount);
+ assertEquals(1, filter.filterCount, "Filter should have executed");
}
/**
@@ -76,18 +76,18 @@ public class OncePerRequestFilterTest {
*/
@SuppressWarnings({"JavaDoc"})
@Test
- public void testDisabled() throws IOException, ServletException {
+ void testDisabled() throws IOException, ServletException {
filter.setEnabled(false); //test disabled
when(request.getAttribute(ATTR_NAME)).thenReturn(null);
filter.doFilter(request, response, chain);
- assertEquals("Filter should NOT have executed", 0, filter.filterCount);
+ assertEquals(0, filter.filterCount, "Filter should NOT have executed");
}
@Test
- public void testFilterOncePerRequest() throws IOException, ServletException {
+ void testFilterOncePerRequest() throws IOException, ServletException {
filter.setFilterOncePerRequest(false);
when(request.getAttribute(ATTR_NAME)).thenReturn(null, true);
@@ -95,7 +95,7 @@ public class OncePerRequestFilterTest {
filter.doFilter(request, response, chain);
filter.doFilter(request, response, chain);
- assertEquals("Filter should have executed twice", 2, filter.filterCount);
+ assertEquals(2, filter.filterCount, "Filter should have executed twice");
}
static class CountingOncePerRequestFilter extends OncePerRequestFilter {
diff --git a/web/src/test/java/org/apache/shiro/web/session/HttpServletSessionTest.java b/web/src/test/java/org/apache/shiro/web/session/HttpServletSessionTest.java
index 3677683d0..c6b4308e9 100644
--- a/web/src/test/java/org/apache/shiro/web/session/HttpServletSessionTest.java
+++ b/web/src/test/java/org/apache/shiro/web/session/HttpServletSessionTest.java
@@ -19,19 +19,19 @@
package org.apache.shiro.web.session;
import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.servlet.http.HttpSession;
import org.easymock.Capture;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class HttpServletSessionTest {
private HttpSession mockSession;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
this.mockSession = createMock(HttpSession.class);
}
@@ -42,7 +42,7 @@ public class HttpServletSessionTest {
* @since 1.3
*/
@Test
- public void testLongTimeout() throws Exception {
+ void testLongTimeout() throws Exception {
final int expectedTimeoutInSeconds = 30 * 24 * 60 * 60; // 30 days.
final long expectedLongValue = expectedTimeoutInSeconds * 1000L;