Bladeren bron

Removal of jmock test dependency and upgrading of mockito version to 1.8.5. Minor adjustments to other build deps and configurations (e.g. prevent groovy from being used as a transitive dep, since we only use it for tests).

Luke Taylor 15 jaren geleden
bovenliggende
commit
3c02989d67
22 gewijzigde bestanden met toevoegingen van 215 en 398 verwijderingen
  1. 18 22
      acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java
  2. 2 7
      acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java
  3. 8 21
      acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java
  4. 2 2
      build.gradle
  5. 6 0
      config/config.gradle
  6. 0 1
      core/core.gradle
  7. 16 25
      core/src/test/java/org/springframework/security/access/expression/method/MethodSecurityExpressionRootTests.java
  8. 4 12
      core/src/test/java/org/springframework/security/access/hierarchicalroles/UserDetailsServiceWrapperTests.java
  9. 50 86
      core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptorTests.java
  10. 12 25
      core/src/test/java/org/springframework/security/access/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java
  11. 1 5
      gradle/javaprojects.gradle
  12. 0 0
      gradle/maven-deployment.gradle
  13. 10 27
      ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java
  14. 6 13
      ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java
  15. 15 24
      ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorMockTests.java
  16. 0 1
      ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java
  17. 0 3
      taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagExpressionLanguageTests.java
  18. 15 29
      web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java
  19. 26 33
      web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java
  20. 4 13
      web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java
  21. 14 36
      web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java
  22. 6 13
      web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java

+ 18 - 22
acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java

@@ -1,10 +1,8 @@
 package org.springframework.security.acls.domain;
 package org.springframework.security.acls.domain;
 
 
 import static org.junit.Assert.*;
 import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
 
 
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Test;
 import org.junit.Test;
 import org.springframework.security.acls.model.AccessControlEntry;
 import org.springframework.security.acls.model.AccessControlEntry;
 import org.springframework.security.acls.model.Acl;
 import org.springframework.security.acls.model.Acl;
@@ -18,7 +16,6 @@ import org.springframework.security.acls.model.Sid;
  * @author Andrei Stefan
  * @author Andrei Stefan
  */
  */
 public class AccessControlImplEntryTests {
 public class AccessControlImplEntryTests {
-    Mockery jmock = new JUnit4Mockery();
 
 
     //~ Methods ========================================================================================================
     //~ Methods ========================================================================================================
 
 
@@ -35,7 +32,7 @@ public class AccessControlImplEntryTests {
 
 
         // Check Sid field is present
         // Check Sid field is present
         try {
         try {
-            new AccessControlEntryImpl(null, jmock.mock(Acl.class), null,
+            new AccessControlEntryImpl(null, mock(Acl.class), null,
                     BasePermission.ADMINISTRATION, true, true, true);
                     BasePermission.ADMINISTRATION, true, true, true);
             fail("It should have thrown IllegalArgumentException");
             fail("It should have thrown IllegalArgumentException");
         }
         }
@@ -44,7 +41,7 @@ public class AccessControlImplEntryTests {
 
 
         // Check Permission field is present
         // Check Permission field is present
         try {
         try {
-            new AccessControlEntryImpl(null, jmock.mock(Acl.class), new PrincipalSid("johndoe"), null,
+            new AccessControlEntryImpl(null, mock(Acl.class), new PrincipalSid("johndoe"), null,
                     true, true, true);
                     true, true, true);
             fail("It should have thrown IllegalArgumentException");
             fail("It should have thrown IllegalArgumentException");
         }
         }
@@ -54,11 +51,11 @@ public class AccessControlImplEntryTests {
 
 
     @Test
     @Test
     public void testAccessControlEntryImplGetters() {
     public void testAccessControlEntryImplGetters() {
-        Acl mockAcl = jmock.mock(Acl.class);
+        Acl mockAcl = mock(Acl.class);
         Sid sid = new PrincipalSid("johndoe");
         Sid sid = new PrincipalSid("johndoe");
 
 
         // Create a sample entry
         // Create a sample entry
-        AccessControlEntry ace = new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.ADMINISTRATION,
+        AccessControlEntry ace = new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid, BasePermission.ADMINISTRATION,
                 true, true, true);
                 true, true, true);
 
 
         // and check every get() method
         // and check every get() method
@@ -73,32 +70,31 @@ public class AccessControlImplEntryTests {
 
 
     @Test
     @Test
     public void testEquals() {
     public void testEquals() {
-        final Acl mockAcl = jmock.mock(Acl.class);
-        final ObjectIdentity oid = jmock.mock(ObjectIdentity.class);
-        jmock.checking(new Expectations() {{
-            allowing(mockAcl).getObjectIdentity(); will(returnValue(oid));
-        }});
+        final Acl mockAcl = mock(Acl.class);
+        final ObjectIdentity oid = mock(ObjectIdentity.class);
+
+        when(mockAcl.getObjectIdentity()).thenReturn(oid);
         Sid sid = new PrincipalSid("johndoe");
         Sid sid = new PrincipalSid("johndoe");
 
 
-        AccessControlEntry ace = new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.ADMINISTRATION,
+        AccessControlEntry ace = new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid, BasePermission.ADMINISTRATION,
                 true, true, true);
                 true, true, true);
 
 
         assertFalse(ace.equals(null));
         assertFalse(ace.equals(null));
-        assertFalse(ace.equals(new Long(100)));
+        assertFalse(ace.equals(Long.valueOf(100)));
         assertTrue(ace.equals(ace));
         assertTrue(ace.equals(ace));
-        assertTrue(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
+        assertTrue(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
                 BasePermission.ADMINISTRATION, true, true, true)));
                 BasePermission.ADMINISTRATION, true, true, true)));
-        assertFalse(ace.equals(new AccessControlEntryImpl(new Long(2), mockAcl, sid,
+        assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(2), mockAcl, sid,
                 BasePermission.ADMINISTRATION, true, true, true)));
                 BasePermission.ADMINISTRATION, true, true, true)));
-        assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, new PrincipalSid("scott"),
+        assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, new PrincipalSid("scott"),
                 BasePermission.ADMINISTRATION, true, true, true)));
                 BasePermission.ADMINISTRATION, true, true, true)));
-        assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.WRITE, true,
+        assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid, BasePermission.WRITE, true,
                 true, true)));
                 true, true)));
-        assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
+        assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
                 BasePermission.ADMINISTRATION, false, true, true)));
                 BasePermission.ADMINISTRATION, false, true, true)));
-        assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
+        assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
                 BasePermission.ADMINISTRATION, true, false, true)));
                 BasePermission.ADMINISTRATION, true, false, true)));
-        assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
+        assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
                 BasePermission.ADMINISTRATION, true, true, false)));
                 BasePermission.ADMINISTRATION, true, true, false)));
     }
     }
 }
 }

+ 2 - 7
acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java

@@ -1,15 +1,11 @@
 package org.springframework.security.acls.domain;
 package org.springframework.security.acls.domain;
 
 
 import static org.junit.Assert.*;
 import static org.junit.Assert.*;
-import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.*;
 
 
 import java.lang.reflect.Field;
 import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
 
 
-import org.jmock.Mockery;
 import org.junit.After;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.Test;
@@ -50,7 +46,6 @@ public class AclImplTests {
     private static final List<Sid> BEN = Arrays.asList((Sid)new PrincipalSid("ben"));
     private static final List<Sid> BEN = Arrays.asList((Sid)new PrincipalSid("ben"));
 
 
     Authentication auth = new TestingAuthenticationToken("joe", "ignored", "ROLE_ADMINISTRATOR");
     Authentication auth = new TestingAuthenticationToken("joe", "ignored", "ROLE_ADMINISTRATOR");
-    Mockery jmockCtx = new Mockery();
     AclAuthorizationStrategy authzStrategy;
     AclAuthorizationStrategy authzStrategy;
     PermissionGrantingStrategy pgs;
     PermissionGrantingStrategy pgs;
     AuditLogger mockAuditLogger;
     AuditLogger mockAuditLogger;

+ 8 - 21
acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java

@@ -1,13 +1,11 @@
 package org.springframework.security.acls.domain;
 package org.springframework.security.acls.domain;
 
 
 import static org.junit.Assert.*;
 import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
 
 
 import java.io.ByteArrayOutputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.PrintStream;
 import java.io.PrintStream;
 
 
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.After;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.Test;
@@ -21,29 +19,17 @@ import org.springframework.security.acls.model.AuditableAccessControlEntry;
  */
  */
 public class AuditLoggerTests {
 public class AuditLoggerTests {
     //~ Instance fields ================================================================================================
     //~ Instance fields ================================================================================================
-    private Mockery jmock = new JUnit4Mockery();
     private PrintStream console;
     private PrintStream console;
     private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
     private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
     private ConsoleAuditLogger logger;
     private ConsoleAuditLogger logger;
     private AuditableAccessControlEntry ace;
     private AuditableAccessControlEntry ace;
-    private Expectations aceRequiresAudit;
-    private Expectations aceDoesntRequireAudit;
 
 
     //~ Methods ========================================================================================================
     //~ Methods ========================================================================================================
 
 
     @Before
     @Before
     public void setUp() throws Exception {
     public void setUp() throws Exception {
         logger = new ConsoleAuditLogger();
         logger = new ConsoleAuditLogger();
-        ace = jmock.mock(AuditableAccessControlEntry.class);
-        aceRequiresAudit = new Expectations() {{
-            allowing(ace).isAuditSuccess(); will(returnValue(true));
-            allowing(ace).isAuditFailure(); will(returnValue(true));
-        }};
-        aceDoesntRequireAudit = new Expectations() {{
-            allowing(ace).isAuditSuccess(); will(returnValue(false));
-            allowing(ace).isAuditFailure(); will(returnValue(false));
-        }};
-
+        ace = mock(AuditableAccessControlEntry.class);
         console = System.out;
         console = System.out;
         System.setOut(new PrintStream(bytes));
         System.setOut(new PrintStream(bytes));
     }
     }
@@ -56,35 +42,36 @@ public class AuditLoggerTests {
 
 
     @Test
     @Test
     public void nonAuditableAceIsIgnored() {
     public void nonAuditableAceIsIgnored() {
-        AccessControlEntry ace = jmock.mock(AccessControlEntry.class);
+        AccessControlEntry ace = mock(AccessControlEntry.class);
         logger.logIfNeeded(true, ace);
         logger.logIfNeeded(true, ace);
         assertEquals(0, bytes.size());
         assertEquals(0, bytes.size());
     }
     }
 
 
     @Test
     @Test
     public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() throws Exception {
     public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() throws Exception {
-        jmock.checking(aceDoesntRequireAudit);
+        when(ace.isAuditSuccess()).thenReturn(false);
         logger.logIfNeeded(true, ace);
         logger.logIfNeeded(true, ace);
         assertEquals(0, bytes.size());
         assertEquals(0, bytes.size());
     }
     }
 
 
     @Test
     @Test
     public void successIsLoggedIfAceRequiresSuccessAudit() throws Exception {
     public void successIsLoggedIfAceRequiresSuccessAudit() throws Exception {
-        jmock.checking(aceRequiresAudit);
+        when(ace.isAuditSuccess()).thenReturn(true);
+
         logger.logIfNeeded(true, ace);
         logger.logIfNeeded(true, ace);
         assertTrue(bytes.toString().startsWith("GRANTED due to ACE"));
         assertTrue(bytes.toString().startsWith("GRANTED due to ACE"));
     }
     }
 
 
     @Test
     @Test
     public void failureIsntLoggedIfAceDoesntRequireFailureAudit() throws Exception {
     public void failureIsntLoggedIfAceDoesntRequireFailureAudit() throws Exception {
-        jmock.checking(aceDoesntRequireAudit);
+        when(ace.isAuditFailure()).thenReturn(false);
         logger.logIfNeeded(false, ace);
         logger.logIfNeeded(false, ace);
         assertEquals(0, bytes.size());
         assertEquals(0, bytes.size());
     }
     }
 
 
     @Test
     @Test
     public void failureIsLoggedIfAceRequiresFailureAudit() throws Exception {
     public void failureIsLoggedIfAceRequiresFailureAudit() throws Exception {
-        jmock.checking(aceRequiresAudit);
+        when(ace.isAuditFailure()).thenReturn(true);
         logger.logIfNeeded(false, ace);
         logger.logIfNeeded(false, ace);
         assertTrue(bytes.toString().startsWith("DENIED due to ACE"));
         assertTrue(bytes.toString().startsWith("DENIED due to ACE"));
     }
     }

+ 2 - 2
build.gradle

@@ -14,7 +14,7 @@ allprojects {
         mavenRepo name: 'SpringSource Maven Snapshot Repo', urls: 'http://maven.springframework.org/snapshot/'
         mavenRepo name: 'SpringSource Maven Snapshot Repo', urls: 'http://maven.springframework.org/snapshot/'
         mavenRepo name: 'SpringSource Enterprise Release', urls: 'http://repository.springsource.com/maven/bundles/release'
         mavenRepo name: 'SpringSource Enterprise Release', urls: 'http://repository.springsource.com/maven/bundles/release'
         mavenRepo name: 'SpringSource Enterprise External', urls: 'http://repository.springsource.com/maven/bundles/external'
         mavenRepo name: 'SpringSource Enterprise External', urls: 'http://repository.springsource.com/maven/bundles/external'
-        mavenRepo(name: 'Spock Snapshots', urls: 'http://m2repo.spockframework.org/snapshots')
+//        mavenRepo(name: 'Spock Snapshots', urls: 'http://m2repo.spockframework.org/snapshots')
     }
     }
 }
 }
 
 
@@ -32,7 +32,7 @@ configure(javaProjects) {
 
 
 configure(coreModuleProjects) {
 configure(coreModuleProjects) {
     apply from: "$rootDir/gradle/bundlor.gradle"
     apply from: "$rootDir/gradle/bundlor.gradle"
-    apply from: "$rootDir/gradle/maven.gradle"
+    apply from: "$rootDir/gradle/maven-deployment.gradle"
     // Gives better names in structure101 jar diagram
     // Gives better names in structure101 jar diagram
     sourceSets.main.classesDir = new File(buildDir, "classes/" + project.name.substring("spring-security".length() + 1))
     sourceSets.main.classesDir = new File(buildDir, "classes/" + project.name.substring("spring-security".length() + 1))
 }
 }

+ 6 - 0
config/config.gradle

@@ -4,6 +4,12 @@ apply plugin: 'groovy'
 
 
 compileTestJava.dependsOn(':spring-security-core:compileTestJava')
 compileTestJava.dependsOn(':spring-security-core:compileTestJava')
 
 
+configurations {
+    // GRADLE-1124
+    compile.extendsFrom = [provided]
+    testCompile.extendsFrom groovy
+}
+
 dependencies {
 dependencies {
     compile project(':spring-security-core'),
     compile project(':spring-security-core'),
             project(':spring-security-web'),
             project(':spring-security-web'),

+ 0 - 1
core/core.gradle

@@ -11,7 +11,6 @@ dependencies {
             "org.springframework:spring-tx:$springVersion",
             "org.springframework:spring-tx:$springVersion",
             "org.springframework:spring-web:$springVersion",
             "org.springframework:spring-web:$springVersion",
             "org.aspectj:aspectjrt:$aspectjVersion",
             "org.aspectj:aspectjrt:$aspectjVersion",
-            "org.aspectj:aspectjweaver:$aspectjVersion",
             'javax.annotation:jsr250-api:1.0'
             'javax.annotation:jsr250-api:1.0'
 
 
     testCompile 'commons-collections:commons-collections:3.2',
     testCompile 'commons-collections:commons-collections:3.2',

+ 16 - 25
core/src/test/java/org/springframework/security/access/expression/method/MethodSecurityExpressionRootTests.java

@@ -1,9 +1,10 @@
 package org.springframework.security.access.expression.method;
 package org.springframework.security.access.expression.method;
 
 
 import static org.junit.Assert.*;
 import static org.junit.Assert.*;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.*;
 
 
-import org.jmock.Expectations;
-import org.jmock.Mockery;
 import org.junit.Before;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.Test;
 import org.springframework.expression.Expression;
 import org.springframework.expression.Expression;
@@ -23,18 +24,17 @@ public class MethodSecurityExpressionRootTests {
     SpelExpressionParser parser = new SpelExpressionParser();
     SpelExpressionParser parser = new SpelExpressionParser();
     MethodSecurityExpressionRoot root;
     MethodSecurityExpressionRoot root;
     StandardEvaluationContext ctx;
     StandardEvaluationContext ctx;
-    Mockery jmock = new Mockery();
     private AuthenticationTrustResolver trustResolver;
     private AuthenticationTrustResolver trustResolver;
     private Authentication user;
     private Authentication user;
 
 
 
 
     @Before
     @Before
     public void createContext() {
     public void createContext() {
-        user = jmock.mock(Authentication.class);
+        user = mock(Authentication.class);
         root = new MethodSecurityExpressionRoot(user);
         root = new MethodSecurityExpressionRoot(user);
         ctx = new StandardEvaluationContext();
         ctx = new StandardEvaluationContext();
         ctx.setRootObject(root);
         ctx.setRootObject(root);
-        trustResolver = jmock.mock(AuthenticationTrustResolver.class);
+        trustResolver = mock(AuthenticationTrustResolver.class);
         root.setTrustResolver(trustResolver);
         root.setTrustResolver(trustResolver);
     }
     }
 
 
@@ -48,42 +48,35 @@ public class MethodSecurityExpressionRootTests {
 
 
     @Test
     @Test
     public void isAnonymousReturnsTrueIfTrustResolverReportsAnonymous() {
     public void isAnonymousReturnsTrueIfTrustResolverReportsAnonymous() {
-        jmock.checking(new Expectations() {{
-            oneOf(trustResolver).isAnonymous(user); will(returnValue(true));
-        }});
+        when(trustResolver.isAnonymous(user)).thenReturn(true);
         assertTrue(root.isAnonymous());
         assertTrue(root.isAnonymous());
     }
     }
 
 
     @Test
     @Test
     public void isAnonymousReturnsFalseIfTrustResolverReportsNonAnonymous() {
     public void isAnonymousReturnsFalseIfTrustResolverReportsNonAnonymous() {
-        jmock.checking(new Expectations() {{
-            oneOf(trustResolver).isAnonymous(user); will(returnValue(false));
-        }});
+        when(trustResolver.isAnonymous(user)).thenReturn(false);
         assertFalse(root.isAnonymous());
         assertFalse(root.isAnonymous());
     }
     }
 
 
     @Test
     @Test
     public void hasPermissionOnDomainObjectReturnsFalseIfPermissionEvaluatorDoes() throws Exception {
     public void hasPermissionOnDomainObjectReturnsFalseIfPermissionEvaluatorDoes() throws Exception {
         final Object dummyDomainObject = new Object();
         final Object dummyDomainObject = new Object();
-        final PermissionEvaluator pe = jmock.mock(PermissionEvaluator.class);
+        final PermissionEvaluator pe = mock(PermissionEvaluator.class);
         ctx.setVariable("domainObject", dummyDomainObject);
         ctx.setVariable("domainObject", dummyDomainObject);
         root.setPermissionEvaluator(pe);
         root.setPermissionEvaluator(pe);
-        jmock.checking(new Expectations() {{
-            oneOf(pe).hasPermission(user, dummyDomainObject, "ignored"); will(returnValue(false));
-        }});
+        when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(false);
 
 
         assertFalse(root.hasPermission(dummyDomainObject, "ignored"));
         assertFalse(root.hasPermission(dummyDomainObject, "ignored"));
+
     }
     }
 
 
     @Test
     @Test
     public void hasPermissionOnDomainObjectReturnsTrueIfPermissionEvaluatorDoes() throws Exception {
     public void hasPermissionOnDomainObjectReturnsTrueIfPermissionEvaluatorDoes() throws Exception {
         final Object dummyDomainObject = new Object();
         final Object dummyDomainObject = new Object();
-        final PermissionEvaluator pe = jmock.mock(PermissionEvaluator.class);
+        final PermissionEvaluator pe = mock(PermissionEvaluator.class);
         ctx.setVariable("domainObject", dummyDomainObject);
         ctx.setVariable("domainObject", dummyDomainObject);
         root.setPermissionEvaluator(pe);
         root.setPermissionEvaluator(pe);
-        jmock.checking(new Expectations() {{
-            oneOf(pe).hasPermission(user, dummyDomainObject, "ignored"); will(returnValue(true));
-        }});
+        when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(true);
 
 
         assertTrue(root.hasPermission(dummyDomainObject, "ignored"));
         assertTrue(root.hasPermission(dummyDomainObject, "ignored"));
     }
     }
@@ -93,13 +86,11 @@ public class MethodSecurityExpressionRootTests {
     public void hasPermissionOnDomainObjectWorksWithIntegerExpressions() throws Exception {
     public void hasPermissionOnDomainObjectWorksWithIntegerExpressions() throws Exception {
         final Object dummyDomainObject = new Object();
         final Object dummyDomainObject = new Object();
         ctx.setVariable("domainObject", dummyDomainObject);
         ctx.setVariable("domainObject", dummyDomainObject);
-        final PermissionEvaluator pe = jmock.mock(PermissionEvaluator.class);
+        final PermissionEvaluator pe = mock(PermissionEvaluator.class);
         root.setPermissionEvaluator(pe);
         root.setPermissionEvaluator(pe);
-
-        jmock.checking(new Expectations() {{
-            exactly(3).of(pe).hasPermission(with(user), with(dummyDomainObject), with(any(Integer.class)));
-                will(onConsecutiveCalls(returnValue(true), returnValue(true), returnValue(false)));
-        }});
+        when(pe.hasPermission(eq(user), eq(dummyDomainObject), any(Integer.class))).thenReturn(true)
+                .thenReturn(true)
+                .thenReturn(false);
 
 
         Expression e = parser.parseExpression("hasPermission(#domainObject, 0xA)");
         Expression e = parser.parseExpression("hasPermission(#domainObject, 0xA)");
         // evaluator returns true
         // evaluator returns true

+ 4 - 12
core/src/test/java/org/springframework/security/access/hierarchicalroles/UserDetailsServiceWrapperTests.java

@@ -1,27 +1,21 @@
 package org.springframework.security.access.hierarchicalroles;
 package org.springframework.security.access.hierarchicalroles;
 
 
 import static org.junit.Assert.*;
 import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
 
 
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JMock;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 import org.springframework.security.core.authority.AuthorityUtils;
 import org.springframework.security.core.authority.AuthorityUtils;
 import org.springframework.security.core.userdetails.User;
 import org.springframework.security.core.userdetails.User;
 import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 
 
-@RunWith(JMock.class)
 @SuppressWarnings("deprecation")
 @SuppressWarnings("deprecation")
 public class UserDetailsServiceWrapperTests {
 public class UserDetailsServiceWrapperTests {
 
 
     private UserDetailsService wrappedUserDetailsService = null;
     private UserDetailsService wrappedUserDetailsService = null;
     private UserDetailsServiceWrapper userDetailsServiceWrapper = null;
     private UserDetailsServiceWrapper userDetailsServiceWrapper = null;
-    private Mockery jmockContext = new JUnit4Mockery();
 
 
     @Before
     @Before
     public void setUp() throws Exception {
     public void setUp() throws Exception {
@@ -29,12 +23,10 @@ public class UserDetailsServiceWrapperTests {
         roleHierarchy.setHierarchy("ROLE_A > ROLE_B");
         roleHierarchy.setHierarchy("ROLE_A > ROLE_B");
         final UserDetails user = new User("EXISTING_USER", "PASSWORD", true, true, true, true,
         final UserDetails user = new User("EXISTING_USER", "PASSWORD", true, true, true, true,
                 AuthorityUtils.createAuthorityList("ROLE_A"));
                 AuthorityUtils.createAuthorityList("ROLE_A"));
-        final UserDetailsService wrappedUserDetailsService = jmockContext.mock(UserDetailsService.class);
+        final UserDetailsService wrappedUserDetailsService = mock(UserDetailsService.class);
+        when(wrappedUserDetailsService.loadUserByUsername("EXISTING_USER")).thenReturn(user);
+        when(wrappedUserDetailsService.loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION")).thenThrow(new UsernameNotFoundException("USERNAME_NOT_FOUND_EXCEPTION"));
 
 
-        jmockContext.checking( new Expectations() {{
-            allowing(wrappedUserDetailsService).loadUserByUsername("EXISTING_USER"); will(returnValue(user));
-            allowing(wrappedUserDetailsService).loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION"); will(throwException(new UsernameNotFoundException("USERNAME_NOT_FOUND_EXCEPTION")));
-        }});
         this.wrappedUserDetailsService = wrappedUserDetailsService;
         this.wrappedUserDetailsService = wrappedUserDetailsService;
         userDetailsServiceWrapper = new UserDetailsServiceWrapper();
         userDetailsServiceWrapper = new UserDetailsServiceWrapper();
         userDetailsServiceWrapper.setRoleHierarchy(roleHierarchy);
         userDetailsServiceWrapper.setRoleHierarchy(roleHierarchy);

+ 50 - 86
core/src/test/java/org/springframework/security/access/intercept/aopalliance/MethodSecurityInterceptorTests.java

@@ -15,15 +15,13 @@
 
 
 package org.springframework.security.access.intercept.aopalliance;
 package org.springframework.security.access.intercept.aopalliance;
 
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.*;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.*;
 
 
-import java.util.List;
+import java.util.*;
 
 
 import org.aopalliance.intercept.MethodInvocation;
 import org.aopalliance.intercept.MethodInvocation;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.After;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.Test;
@@ -37,12 +35,12 @@ import org.springframework.security.access.SecurityConfig;
 import org.springframework.security.access.intercept.AfterInvocationManager;
 import org.springframework.security.access.intercept.AfterInvocationManager;
 import org.springframework.security.access.intercept.RunAsManager;
 import org.springframework.security.access.intercept.RunAsManager;
 import org.springframework.security.access.intercept.RunAsUserToken;
 import org.springframework.security.access.intercept.RunAsUserToken;
-import org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor;
 import org.springframework.security.access.method.MethodSecurityMetadataSource;
 import org.springframework.security.access.method.MethodSecurityMetadataSource;
 import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
 import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
 import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.authentication.BadCredentialsException;
 import org.springframework.security.authentication.BadCredentialsException;
 import org.springframework.security.authentication.TestingAuthenticationToken;
 import org.springframework.security.authentication.TestingAuthenticationToken;
+import org.springframework.security.core.Authentication;
 import org.springframework.security.core.AuthenticationException;
 import org.springframework.security.core.AuthenticationException;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.core.context.SecurityContextHolder;
 
 
@@ -53,7 +51,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
  */
  */
 @SuppressWarnings("unchecked")
 @SuppressWarnings("unchecked")
 public class MethodSecurityInterceptorTests {
 public class MethodSecurityInterceptorTests {
-    private Mockery jmock = new JUnit4Mockery();
     private TestingAuthenticationToken token;
     private TestingAuthenticationToken token;
     private MethodSecurityInterceptor interceptor;
     private MethodSecurityInterceptor interceptor;
     private ITargetObject realTarget;
     private ITargetObject realTarget;
@@ -62,9 +59,6 @@ public class MethodSecurityInterceptorTests {
     private MethodSecurityMetadataSource mds;
     private MethodSecurityMetadataSource mds;
     private AuthenticationManager authman;
     private AuthenticationManager authman;
 
 
-    private Expectations mdsWillReturnNullFromGetAttributes;
-    private Expectations mdsWillReturnROLE_USERFromGetAttributes;
-
     //~ Methods ========================================================================================================
     //~ Methods ========================================================================================================
 
 
     @Before
     @Before
@@ -72,20 +66,13 @@ public class MethodSecurityInterceptorTests {
         SecurityContextHolder.clearContext();
         SecurityContextHolder.clearContext();
         token = new TestingAuthenticationToken("Test", "Password");
         token = new TestingAuthenticationToken("Test", "Password");
         interceptor = new MethodSecurityInterceptor();
         interceptor = new MethodSecurityInterceptor();
-        adm = jmock.mock(AccessDecisionManager.class);
-        authman = jmock.mock(AuthenticationManager.class);
-        mds = jmock.mock(MethodSecurityMetadataSource.class);
+        adm = mock(AccessDecisionManager.class);
+        authman = mock(AuthenticationManager.class);
+        mds = mock(MethodSecurityMetadataSource.class);
         interceptor.setAccessDecisionManager(adm);
         interceptor.setAccessDecisionManager(adm);
         interceptor.setAuthenticationManager(authman);
         interceptor.setAuthenticationManager(authman);
         interceptor.setSecurityMetadataSource(mds);
         interceptor.setSecurityMetadataSource(mds);
         createTarget(false);
         createTarget(false);
-
-        mdsWillReturnNullFromGetAttributes = new Expectations() {{
-            oneOf(mds).getAttributes(with(any(MethodInvocation.class))); will (returnValue(null));
-        }};
-        mdsWillReturnROLE_USERFromGetAttributes = new Expectations() {{
-            oneOf(mds).getAttributes(with(any(MethodInvocation.class))); will (returnValue(SecurityConfig.createList("ROLE_USER")));
-        }};
     }
     }
 
 
     @After
     @After
@@ -94,7 +81,7 @@ public class MethodSecurityInterceptorTests {
     }
     }
 
 
     private void createTarget(boolean useMock) {
     private void createTarget(boolean useMock) {
-        realTarget = useMock ? jmock.mock(ITargetObject.class) : new TargetObject();
+        realTarget = useMock ? mock(ITargetObject.class) : new TargetObject();
         ProxyFactory pf = new ProxyFactory(realTarget);
         ProxyFactory pf = new ProxyFactory(realTarget);
         pf.addAdvice(interceptor);
         pf.addAdvice(interceptor);
         advisedTarget = (ITargetObject) pf.getProxy();
         advisedTarget = (ITargetObject) pf.getProxy();
@@ -102,8 +89,8 @@ public class MethodSecurityInterceptorTests {
 
 
     @Test
     @Test
     public void gettersReturnExpectedData() {
     public void gettersReturnExpectedData() {
-        RunAsManager runAs = jmock.mock(RunAsManager.class);
-        AfterInvocationManager aim = jmock.mock(AfterInvocationManager.class);
+        RunAsManager runAs = mock(RunAsManager.class);
+        AfterInvocationManager aim = mock(AfterInvocationManager.class);
         interceptor.setRunAsManager(runAs);
         interceptor.setRunAsManager(runAs);
         interceptor.setAfterInvocationManager(aim);
         interceptor.setAfterInvocationManager(aim);
         assertEquals(adm, interceptor.getAccessDecisionManager());
         assertEquals(adm, interceptor.getAccessDecisionManager());
@@ -139,87 +126,70 @@ public class MethodSecurityInterceptorTests {
 
 
     @Test(expected=IllegalArgumentException.class)
     @Test(expected=IllegalArgumentException.class)
     public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation() throws Throwable {
     public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation() throws Throwable {
-        jmock.checking(new Expectations() {{
-           oneOf(mds).supports(MethodInvocation.class); will(returnValue(false));
-        }});
+        when(mds.supports(MethodInvocation.class)).thenReturn(false);
         interceptor.afterPropertiesSet();
         interceptor.afterPropertiesSet();
     }
     }
 
 
     @Test(expected=IllegalArgumentException.class)
     @Test(expected=IllegalArgumentException.class)
     public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation() throws Exception {
     public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation() throws Exception {
-        jmock.checking(new Expectations() {{
-            oneOf(mds).supports(MethodInvocation.class); will(returnValue(true));
-            oneOf(adm).supports(MethodInvocation.class); will(returnValue(false));
-         }});
-         interceptor.afterPropertiesSet();
+        when(mds.supports(MethodInvocation.class)).thenReturn(true);
+        when(adm.supports(MethodInvocation.class)).thenReturn(false);
+        interceptor.afterPropertiesSet();
     }
     }
 
 
     @Test(expected=IllegalArgumentException.class)
     @Test(expected=IllegalArgumentException.class)
     public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation() throws Exception {
     public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation() throws Exception {
-        final RunAsManager ram = jmock.mock(RunAsManager.class);
-        jmock.checking(new Expectations() {{
-            ignoring(mds);
-            oneOf(ram).supports(MethodInvocation.class); will(returnValue(false));
-        }});
+        final RunAsManager ram = mock(RunAsManager.class);
+        when(ram.supports(MethodInvocation.class)).thenReturn(false);
         interceptor.setRunAsManager(ram);
         interceptor.setRunAsManager(ram);
         interceptor.afterPropertiesSet();
         interceptor.afterPropertiesSet();
     }
     }
 
 
     @Test(expected=IllegalArgumentException.class)
     @Test(expected=IllegalArgumentException.class)
     public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation() throws Exception {
     public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation() throws Exception {
-        final AfterInvocationManager aim = jmock.mock(AfterInvocationManager.class);
-        jmock.checking(new Expectations() {{
-            oneOf(aim).supports(MethodInvocation.class); will(returnValue(false));
-            ignoring(anything());
-        }});
+        final AfterInvocationManager aim = mock(AfterInvocationManager.class);
+        when(aim.supports(MethodInvocation.class)).thenReturn(false);
         interceptor.setAfterInvocationManager(aim);
         interceptor.setAfterInvocationManager(aim);
         interceptor.afterPropertiesSet();
         interceptor.afterPropertiesSet();
     }
     }
 
 
     @Test(expected=IllegalArgumentException.class)
     @Test(expected=IllegalArgumentException.class)
     public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes() throws Exception {
     public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes() throws Exception {
-        jmock.checking(new Expectations() {{
-            oneOf(adm).supports(with(aNonNull(ConfigAttribute.class))); will(returnValue(false));
-            ignoring(anything());
-        }});
+        when(adm.supports(any(ConfigAttribute.class))).thenReturn(false);
         interceptor.afterPropertiesSet();
         interceptor.afterPropertiesSet();
     }
     }
 
 
     @Test
     @Test
     public void validationNotAttemptedIfIsValidateConfigAttributesSetToFalse() throws Exception {
     public void validationNotAttemptedIfIsValidateConfigAttributesSetToFalse() throws Exception {
-        jmock.checking(new Expectations() {{
-            oneOf(mds).supports(MethodInvocation.class); will(returnValue(true));
-            oneOf(adm).supports(MethodInvocation.class); will(returnValue(true));
-            never(mds).getAllConfigAttributes();
-            never(adm).supports(with(any(ConfigAttribute.class)));
-        }});
+        when(adm.supports(MethodInvocation.class)).thenReturn(true);
+        when(mds.supports(MethodInvocation.class)).thenReturn(true);
         interceptor.setValidateConfigAttributes(false);
         interceptor.setValidateConfigAttributes(false);
         interceptor.afterPropertiesSet();
         interceptor.afterPropertiesSet();
+        verify(mds, never()).getAllConfigAttributes();
+        verify(adm, never()).supports(any(ConfigAttribute.class));
     }
     }
 
 
     @Test
     @Test
     public void validationNotAttemptedIfMethodSecurityMetadataSourceReturnsNullForAttributes() throws Exception {
     public void validationNotAttemptedIfMethodSecurityMetadataSourceReturnsNullForAttributes() throws Exception {
-        jmock.checking(new Expectations() {{
-            oneOf(mds).supports(MethodInvocation.class); will(returnValue(true));
-            oneOf(adm).supports(MethodInvocation.class); will(returnValue(true));
-            oneOf(mds).getAllConfigAttributes(); will(returnValue(null));
-            never(adm).supports(with(any(ConfigAttribute.class)));
-        }});
+        when(adm.supports(MethodInvocation.class)).thenReturn(true);
+        when(mds.supports(MethodInvocation.class)).thenReturn(true);
+        when(mds.getAllConfigAttributes()).thenReturn(null);
+
         interceptor.setValidateConfigAttributes(true);
         interceptor.setValidateConfigAttributes(true);
         interceptor.afterPropertiesSet();
         interceptor.afterPropertiesSet();
+        verify(adm, never()).supports(any(ConfigAttribute.class));
     }
     }
 
 
     @Test
     @Test
     public void callingAPublicMethodFacadeWillNotRepeatSecurityChecksWhenPassedToTheSecuredMethodItFronts() {
     public void callingAPublicMethodFacadeWillNotRepeatSecurityChecksWhenPassedToTheSecuredMethodItFronts() {
-        jmock.checking(mdsWillReturnNullFromGetAttributes);
+        mdsReturnsNull();
         String result = advisedTarget.publicMakeLowerCase("HELLO");
         String result = advisedTarget.publicMakeLowerCase("HELLO");
         assertEquals("hello Authentication empty", result);
         assertEquals("hello Authentication empty", result);
-        jmock.assertIsSatisfied();
     }
     }
 
 
     @Test
     @Test
     public void callingAPublicMethodWhenPresentingAnAuthenticationObjectDoesntChangeItsAuthenticatedProperty() {
     public void callingAPublicMethodWhenPresentingAnAuthenticationObjectDoesntChangeItsAuthenticatedProperty() {
-        jmock.checking(mdsWillReturnNullFromGetAttributes);
+        mdsReturnsNull();
         SecurityContextHolder.getContext().setAuthentication(token);
         SecurityContextHolder.getContext().setAuthentication(token);
         assertEquals("hello org.springframework.security.authentication.TestingAuthenticationToken false",
         assertEquals("hello org.springframework.security.authentication.TestingAuthenticationToken false",
                 advisedTarget.publicMakeLowerCase("HELLO"));
                 advisedTarget.publicMakeLowerCase("HELLO"));
@@ -227,14 +197,12 @@ public class MethodSecurityInterceptorTests {
     }
     }
 
 
     @Test(expected=AuthenticationException.class)
     @Test(expected=AuthenticationException.class)
-    public void callIsWhenAuthenticationManagerRejectsAuthentication() throws Exception {
+    public void callIsntMadeWhenAuthenticationManagerRejectsAuthentication() throws Exception {
         final TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password");
         final TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password");
         SecurityContextHolder.getContext().setAuthentication(token);
         SecurityContextHolder.getContext().setAuthentication(token);
 
 
-        jmock.checking(mdsWillReturnROLE_USERFromGetAttributes);
-        jmock.checking(new Expectations() {{
-            oneOf(authman).authenticate(token); will(throwException(new BadCredentialsException("rejected")));
-        }});
+        mdsReturnsUserRole();
+        when(authman.authenticate(token)).thenThrow(new BadCredentialsException("rejected"));
 
 
         advisedTarget.makeLowerCase("HELLO");
         advisedTarget.makeLowerCase("HELLO");
     }
     }
@@ -243,10 +211,7 @@ public class MethodSecurityInterceptorTests {
     public void callSucceedsIfAccessDecisionManagerGrantsAccess() throws Exception {
     public void callSucceedsIfAccessDecisionManagerGrantsAccess() throws Exception {
         token.setAuthenticated(true);
         token.setAuthenticated(true);
         SecurityContextHolder.getContext().setAuthentication(token);
         SecurityContextHolder.getContext().setAuthentication(token);
-        jmock.checking(mdsWillReturnROLE_USERFromGetAttributes);
-        jmock.checking(new Expectations() {{
-           oneOf(adm).decide(with(token), with(aNonNull(MethodInvocation.class)), with(aNonNull(List.class)));
-        }});
+        mdsReturnsUserRole();
 
 
         String result = advisedTarget.makeLowerCase("HELLO");
         String result = advisedTarget.makeLowerCase("HELLO");
 
 
@@ -259,12 +224,9 @@ public class MethodSecurityInterceptorTests {
         SecurityContextHolder.getContext().setAuthentication(token);
         SecurityContextHolder.getContext().setAuthentication(token);
         // Use mocked target to make sure invocation doesn't happen (not in expectations so test would fail)
         // Use mocked target to make sure invocation doesn't happen (not in expectations so test would fail)
         createTarget(true);
         createTarget(true);
-        jmock.checking(mdsWillReturnROLE_USERFromGetAttributes);
-        jmock.checking(new Expectations() {{
-            oneOf(authman).authenticate(token); will(returnValue(token));
-            oneOf(adm).decide(with(token), with(aNonNull(MethodInvocation.class)), with(aNonNull(List.class)));
-            will(throwException(new AccessDeniedException("rejected")));
-        }});
+        mdsReturnsUserRole();
+        when(authman.authenticate(token)).thenReturn(token);
+        doThrow(new AccessDeniedException("rejected")).when(adm).decide(any(Authentication.class), any(MethodInvocation.class), any(List.class));
 
 
         advisedTarget.makeUpperCase("HELLO");
         advisedTarget.makeUpperCase("HELLO");
     }
     }
@@ -278,16 +240,12 @@ public class MethodSecurityInterceptorTests {
     public void runAsReplacementIsCorrectlySet() throws Exception {
     public void runAsReplacementIsCorrectlySet() throws Exception {
         SecurityContextHolder.getContext().setAuthentication(token);
         SecurityContextHolder.getContext().setAuthentication(token);
         token.setAuthenticated(true);
         token.setAuthenticated(true);
-        final RunAsManager runAs = jmock.mock(RunAsManager.class);
+        final RunAsManager runAs = mock(RunAsManager.class);
         final RunAsUserToken runAsToken =
         final RunAsUserToken runAsToken =
             new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), TestingAuthenticationToken.class);
             new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), TestingAuthenticationToken.class);
         interceptor.setRunAsManager(runAs);
         interceptor.setRunAsManager(runAs);
-        jmock.checking(mdsWillReturnROLE_USERFromGetAttributes);
-        jmock.checking(new Expectations() {{
-            oneOf(runAs).buildRunAs(with(token), with(aNonNull(MethodInvocation.class)), with(aNonNull(List.class)));
-            will(returnValue(runAsToken));
-            ignoring(anything());
-        }});
+        mdsReturnsUserRole();
+        when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
 
 
         String result = advisedTarget.makeUpperCase("hello");
         String result = advisedTarget.makeUpperCase("hello");
         assertEquals("HELLO org.springframework.security.access.intercept.RunAsUserToken true", result);
         assertEquals("HELLO org.springframework.security.access.intercept.RunAsUserToken true", result);
@@ -297,9 +255,15 @@ public class MethodSecurityInterceptorTests {
 
 
     @Test(expected=AuthenticationCredentialsNotFoundException.class)
     @Test(expected=AuthenticationCredentialsNotFoundException.class)
     public void emptySecurityContextIsRejected() throws Exception {
     public void emptySecurityContextIsRejected() throws Exception {
-        jmock.checking(new Expectations() {{
-            ignoring(anything());
-        }});
+        mdsReturnsUserRole();
         advisedTarget.makeUpperCase("hello");
         advisedTarget.makeUpperCase("hello");
     }
     }
+
+    void mdsReturnsNull() {
+        when(mds.getAttributes(any(MethodInvocation.class))).thenReturn(null);
+    }
+
+    void mdsReturnsUserRole() {
+        when(mds.getAttributes(any(MethodInvocation.class))).thenReturn(SecurityConfig.createList("ROLE_USER"));
+    }
 }
 }

+ 12 - 25
core/src/test/java/org/springframework/security/access/intercept/method/MethodInvocationPrivilegeEvaluatorTests.java

@@ -16,13 +16,11 @@
 package org.springframework.security.access.intercept.method;
 package org.springframework.security.access.intercept.method;
 
 
 import static org.junit.Assert.*;
 import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
 
 
-import java.util.List;
+import java.util.*;
 
 
 import org.aopalliance.intercept.MethodInvocation;
 import org.aopalliance.intercept.MethodInvocation;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.Test;
 import org.springframework.security.ITargetObject;
 import org.springframework.security.ITargetObject;
@@ -47,7 +45,6 @@ import org.springframework.security.util.MethodInvocationUtils;
  * @author Ben Alex
  * @author Ben Alex
  */
  */
 public class MethodInvocationPrivilegeEvaluatorTests {
 public class MethodInvocationPrivilegeEvaluatorTests {
-    private Mockery jmock = new JUnit4Mockery();
     private TestingAuthenticationToken token;
     private TestingAuthenticationToken token;
     private MethodSecurityInterceptor interceptor;
     private MethodSecurityInterceptor interceptor;
     private AccessDecisionManager adm;
     private AccessDecisionManager adm;
@@ -61,9 +58,9 @@ public class MethodInvocationPrivilegeEvaluatorTests {
         SecurityContextHolder.clearContext();
         SecurityContextHolder.clearContext();
         interceptor = new MethodSecurityInterceptor();
         interceptor = new MethodSecurityInterceptor();
         token = new TestingAuthenticationToken("Test", "Password", "ROLE_SOMETHING");
         token = new TestingAuthenticationToken("Test", "Password", "ROLE_SOMETHING");
-        adm = jmock.mock(AccessDecisionManager.class);
-        AuthenticationManager authman = jmock.mock(AuthenticationManager.class);
-        mds = jmock.mock(MethodSecurityMetadataSource.class);
+        adm = mock(AccessDecisionManager.class);
+        AuthenticationManager authman = mock(AuthenticationManager.class);
+        mds = mock(MethodSecurityMetadataSource.class);
         interceptor.setAccessDecisionManager(adm);
         interceptor.setAccessDecisionManager(adm);
         interceptor.setAuthenticationManager(authman);
         interceptor.setAuthenticationManager(authman);
         interceptor.setSecurityMetadataSource(mds);
         interceptor.setSecurityMetadataSource(mds);
@@ -75,10 +72,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
         final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
         final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
 
 
         MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
         MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
-        jmock.checking(new Expectations() {{
-            oneOf(mds).getAttributes(mi); will(returnValue(role));
-            oneOf(adm).decide(token, mi, role);
-        }});
+        when(mds.getAttributes(mi)).thenReturn(role);
 
 
         mipe.setSecurityInterceptor(interceptor);
         mipe.setSecurityInterceptor(interceptor);
         mipe.afterPropertiesSet();
         mipe.afterPropertiesSet();
@@ -92,10 +86,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
                 new Class[] {String.class}, new Object[] {"Hello world"});
                 new Class[] {String.class}, new Object[] {"Hello world"});
         MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
         MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
         mipe.setSecurityInterceptor(interceptor);
         mipe.setSecurityInterceptor(interceptor);
-        jmock.checking(new Expectations() {{
-            oneOf(mds).getAttributes(mi); will(returnValue(role));
-            oneOf(adm).decide(token, mi, role);
-        }});
+        when(mds.getAttributes(mi)).thenReturn(role);
 
 
         assertTrue(mipe.isAllowed(mi, token));
         assertTrue(mipe.isAllowed(mi, token));
     }
     }
@@ -103,13 +94,11 @@ public class MethodInvocationPrivilegeEvaluatorTests {
     @Test
     @Test
     public void declinesAccessUsingCreate() throws Exception {
     public void declinesAccessUsingCreate() throws Exception {
         Object object = new TargetObject();
         Object object = new TargetObject();
-        final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", new Object[] {"foobar"});
+        final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
         MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
         MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
         mipe.setSecurityInterceptor(interceptor);
         mipe.setSecurityInterceptor(interceptor);
-        jmock.checking(new Expectations() {{
-            oneOf(mds).getAttributes(mi); will(returnValue(role));
-            oneOf(adm).decide(token, mi, role); will(throwException(new AccessDeniedException("rejected")));
-        }});
+        when(mds.getAttributes(mi)).thenReturn(role);
+        doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, role);
 
 
         assertFalse(mipe.isAllowed(mi, token));
         assertFalse(mipe.isAllowed(mi, token));
     }
     }
@@ -121,10 +110,8 @@ public class MethodInvocationPrivilegeEvaluatorTests {
 
 
         MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
         MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
         mipe.setSecurityInterceptor(interceptor);
         mipe.setSecurityInterceptor(interceptor);
-        jmock.checking(new Expectations() {{
-            oneOf(mds).getAttributes(mi); will(returnValue(role));
-            oneOf(adm).decide(token, mi, role); will(throwException(new AccessDeniedException("rejected")));
-        }});
+        when(mds.getAttributes(mi)).thenReturn(role);
+        doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, role);
 
 
         assertFalse(mipe.isAllowed(mi, token));
         assertFalse(mipe.isAllowed(mi, token));
     }
     }

+ 1 - 5
gradle/javaprojects.gradle

@@ -31,11 +31,7 @@ dependencies {
     }
     }
 
 
     testCompile 'junit:junit:4.7',
     testCompile 'junit:junit:4.7',
-            'org.mockito:mockito-core:1.8.3',
-            'org.jmock:jmock:2.5.1',
-            'org.jmock:jmock-junit4:2.5.1',
-            'org.hamcrest:hamcrest-core:1.1',
-            'org.hamcrest:hamcrest-library:1.1',
+            'org.mockito:mockito-core:1.8.5',
             "org.springframework:spring-test:$springVersion"
             "org.springframework:spring-test:$springVersion"
 
 
     // Use slf4j/logback for logging
     // Use slf4j/logback for logging

+ 0 - 0
gradle/maven.gradle → gradle/maven-deployment.gradle


+ 10 - 27
ldap/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java

@@ -15,17 +15,13 @@
 
 
 package org.springframework.security.ldap;
 package org.springframework.security.ldap;
 
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
 
 
 import javax.naming.NamingException;
 import javax.naming.NamingException;
 import javax.naming.directory.DirContext;
 import javax.naming.directory.DirContext;
 
 
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JMock;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Test;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 
 
 
 /**
 /**
@@ -33,41 +29,31 @@ import org.junit.runner.RunWith;
  *
  *
  * @author Luke Taylor
  * @author Luke Taylor
  */
  */
-@RunWith(JMock.class)
 public class LdapUtilsTests {
 public class LdapUtilsTests {
-    Mockery context = new JUnit4Mockery();
 
 
     //~ Methods ========================================================================================================
     //~ Methods ========================================================================================================
 
 
     @Test
     @Test
     public void testCloseContextSwallowsNamingException() throws Exception {
     public void testCloseContextSwallowsNamingException() throws Exception {
-        final DirContext dirCtx = context.mock(DirContext.class);
-
-        context.checking(new Expectations() {{
-            oneOf(dirCtx).close(); will(throwException(new NamingException()));
-        }});
+        final DirContext dirCtx = mock(DirContext.class);
+        doThrow(new NamingException()).when(dirCtx).close();
 
 
         LdapUtils.closeContext(dirCtx);
         LdapUtils.closeContext(dirCtx);
     }
     }
 
 
     @Test
     @Test
     public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception {
     public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception {
-        final DirContext mockCtx = context.mock(DirContext.class);
+        final DirContext mockCtx = mock(DirContext.class);
 
 
-        context.checking(new Expectations() {{
-            atLeast(1).of(mockCtx).getNameInNamespace(); will(returnValue("dc=springframework,dc=org"));
-        }});
+        when(mockCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
 
 
         assertEquals("", LdapUtils.getRelativeName("dc=springframework,dc=org", mockCtx));
         assertEquals("", LdapUtils.getRelativeName("dc=springframework,dc=org", mockCtx));
     }
     }
 
 
     @Test
     @Test
     public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception {
     public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception {
-        final DirContext mockCtx = context.mock(DirContext.class);
-
-        context.checking(new Expectations() {{
-            atLeast(1).of(mockCtx).getNameInNamespace(); will(returnValue(""));
-        }});
+        final DirContext mockCtx = mock(DirContext.class);
+        when(mockCtx.getNameInNamespace()).thenReturn("");
 
 
         assertEquals("cn=jane,dc=springframework,dc=org",
         assertEquals("cn=jane,dc=springframework,dc=org",
             LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx));
             LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx));
@@ -75,11 +61,8 @@ public class LdapUtilsTests {
 
 
     @Test
     @Test
     public void testGetRelativeNameWorksWithArbitrarySpaces() throws Exception {
     public void testGetRelativeNameWorksWithArbitrarySpaces() throws Exception {
-        final DirContext mockCtx = context.mock(DirContext.class);
-
-        context.checking(new Expectations() {{
-            atLeast(1).of(mockCtx).getNameInNamespace(); will(returnValue("dc=springsecurity,dc = org"));
-        }});
+        final DirContext mockCtx = mock(DirContext.class);
+        when(mockCtx.getNameInNamespace()).thenReturn("dc=springsecurity,dc = org");
 
 
         assertEquals("cn=jane smith",
         assertEquals("cn=jane smith",
             LdapUtils.getRelativeName("cn=jane smith, dc = springsecurity , dc=org", mockCtx));
             LdapUtils.getRelativeName("cn=jane smith, dc = springsecurity , dc=org", mockCtx));

+ 6 - 13
ldap/src/test/java/org/springframework/security/ldap/authentication/LdapAuthenticationProviderTests.java

@@ -16,12 +16,10 @@
 package org.springframework.security.ldap.authentication;
 package org.springframework.security.ldap.authentication;
 
 
 import static org.junit.Assert.*;
 import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
 
 
-import java.util.Collection;
+import java.util.*;
 
 
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Test;
 import org.junit.Test;
 import org.springframework.ldap.core.DirContextAdapter;
 import org.springframework.ldap.core.DirContextAdapter;
 import org.springframework.ldap.core.DirContextOperations;
 import org.springframework.ldap.core.DirContextOperations;
@@ -43,7 +41,6 @@ import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
  * @author Luke Taylor
  * @author Luke Taylor
  */
  */
 public class LdapAuthenticationProviderTests {
 public class LdapAuthenticationProviderTests {
-    Mockery jmock = new JUnit4Mockery();
 
 
     //~ Methods ========================================================================================================
     //~ Methods ========================================================================================================
 
 
@@ -81,11 +78,9 @@ public class LdapAuthenticationProviderTests {
 
 
     @Test(expected=BadCredentialsException.class)
     @Test(expected=BadCredentialsException.class)
     public void usernameNotFoundExceptionIsHiddenByDefault() {
     public void usernameNotFoundExceptionIsHiddenByDefault() {
-        final LdapAuthenticator authenticator = jmock.mock(LdapAuthenticator.class);
+        final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
         final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
         final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
-        jmock.checking(new Expectations() {{
-            oneOf(authenticator).authenticate(joe); will(throwException(new UsernameNotFoundException("nobody")));
-        }});
+        when(authenticator.authenticate(joe)).thenThrow(new UsernameNotFoundException("nobody"));
 
 
         LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
         LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
         provider.authenticate(joe);
         provider.authenticate(joe);
@@ -93,11 +88,9 @@ public class LdapAuthenticationProviderTests {
 
 
     @Test(expected=UsernameNotFoundException.class)
     @Test(expected=UsernameNotFoundException.class)
     public void usernameNotFoundExceptionIsNotHiddenIfConfigured() {
     public void usernameNotFoundExceptionIsNotHiddenIfConfigured() {
-        final LdapAuthenticator authenticator = jmock.mock(LdapAuthenticator.class);
+        final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
         final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
         final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
-        jmock.checking(new Expectations() {{
-            oneOf(authenticator).authenticate(joe); will(throwException(new UsernameNotFoundException("nobody")));
-        }});
+        when(authenticator.authenticate(joe)).thenThrow(new UsernameNotFoundException("nobody"));
 
 
         LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
         LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
         provider.setHideUserNotFoundExceptions(false);
         provider.setHideUserNotFoundExceptions(false);

+ 15 - 24
ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorMockTests.java

@@ -15,19 +15,19 @@
 
 
 package org.springframework.security.ldap.authentication;
 package org.springframework.security.ldap.authentication;
 
 
-import javax.naming.directory.Attributes;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.*;
+
+import javax.naming.NamingEnumeration;
 import javax.naming.directory.BasicAttribute;
 import javax.naming.directory.BasicAttribute;
 import javax.naming.directory.BasicAttributes;
 import javax.naming.directory.BasicAttributes;
 import javax.naming.directory.DirContext;
 import javax.naming.directory.DirContext;
 import javax.naming.directory.SearchControls;
 import javax.naming.directory.SearchControls;
 
 
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Test;
 import org.junit.Test;
 import org.springframework.ldap.core.support.BaseLdapPathContextSource;
 import org.springframework.ldap.core.support.BaseLdapPathContextSource;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.ldap.authentication.PasswordComparisonAuthenticator;
 
 
 
 
 /**
 /**
@@ -35,14 +35,13 @@ import org.springframework.security.ldap.authentication.PasswordComparisonAuthen
  * @author Luke Taylor
  * @author Luke Taylor
  */
  */
 public class PasswordComparisonAuthenticatorMockTests {
 public class PasswordComparisonAuthenticatorMockTests {
-    Mockery jmock = new JUnit4Mockery();
 
 
     //~ Methods ========================================================================================================
     //~ Methods ========================================================================================================
 
 
     @Test
     @Test
     public void ldapCompareOperationIsUsedWhenPasswordIsNotRetrieved() throws Exception {
     public void ldapCompareOperationIsUsedWhenPasswordIsNotRetrieved() throws Exception {
-        final DirContext dirCtx = jmock.mock(DirContext.class);
-        final BaseLdapPathContextSource source = jmock.mock(BaseLdapPathContextSource.class);
+        final DirContext dirCtx = mock(DirContext.class);
+        final BaseLdapPathContextSource source = mock(BaseLdapPathContextSource.class);
         final BasicAttributes attrs = new BasicAttributes();
         final BasicAttributes attrs = new BasicAttributes();
         attrs.put(new BasicAttribute("uid", "bob"));
         attrs.put(new BasicAttribute("uid", "bob"));
 
 
@@ -51,26 +50,18 @@ public class PasswordComparisonAuthenticatorMockTests {
         authenticator.setUserDnPatterns(new String[] {"cn={0},ou=people"});
         authenticator.setUserDnPatterns(new String[] {"cn={0},ou=people"});
 
 
         // Get the mock to return an empty attribute set
         // Get the mock to return an empty attribute set
-        jmock.checking(new Expectations() {{
-            allowing(source).getReadOnlyContext(); will(returnValue(dirCtx));
-            oneOf(dirCtx).getAttributes(with(equal("cn=Bob,ou=people")), with(aNull(String[].class))); will(returnValue(attrs));
-            oneOf(dirCtx).getNameInNamespace(); will(returnValue("dc=springframework,dc=org"));
-        }});
+        when(source.getReadOnlyContext()).thenReturn(dirCtx);
+        when(dirCtx.getAttributes(eq("cn=Bob,ou=people"), any(String[].class))).thenReturn(attrs);
+        when(dirCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
 
 
         // Setup a single return value (i.e. success)
         // Setup a single return value (i.e. success)
-        final Attributes searchResults = new BasicAttributes("", null);
+        final NamingEnumeration searchResults = new BasicAttributes("", null).getAll();
 
 
-        jmock.checking(new Expectations() {{
-            oneOf(dirCtx).search(with(equal("cn=Bob,ou=people")),
-                            with(equal("(userPassword={0})")),
-                            with(aNonNull(Object[].class)),
-                            with(aNonNull(SearchControls.class)));
-            will(returnValue(searchResults.getAll()));
-            atLeast(1).of(dirCtx).close();
-        }});
+        when(dirCtx.search(eq("cn=Bob,ou=people"),
+                            eq("(userPassword={0})"),
+                            any(Object[].class),
+                            any(SearchControls.class))).thenReturn(searchResults);
 
 
         authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob","bobspassword"));
         authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob","bobspassword"));
-
-        jmock.assertIsSatisfied();
     }
     }
 }
 }

+ 0 - 1
ldap/src/test/java/org/springframework/security/ldap/authentication/PasswordComparisonAuthenticatorTests.java

@@ -23,7 +23,6 @@ import org.springframework.security.authentication.encoding.PlaintextPasswordEnc
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.security.ldap.AbstractLdapIntegrationTests;
 import org.springframework.security.ldap.AbstractLdapIntegrationTests;
-import org.springframework.security.ldap.authentication.PasswordComparisonAuthenticator;
 
 
 
 
 import org.springframework.ldap.core.DirContextAdapter;
 import org.springframework.ldap.core.DirContextAdapter;

+ 0 - 3
taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagExpressionLanguageTests.java

@@ -20,8 +20,6 @@ import javax.servlet.jsp.el.VariableResolver;
 import javax.servlet.jsp.tagext.Tag;
 import javax.servlet.jsp.tagext.Tag;
 
 
 import junit.framework.TestCase;
 import junit.framework.TestCase;
-
-import org.jmock.Mockery;
 import org.springframework.mock.web.MockPageContext;
 import org.springframework.mock.web.MockPageContext;
 import org.springframework.security.authentication.TestingAuthenticationToken;
 import org.springframework.security.authentication.TestingAuthenticationToken;
 import org.springframework.security.core.GrantedAuthority;
 import org.springframework.security.core.GrantedAuthority;
@@ -33,7 +31,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
  * Test case to implement commons-el expression language expansion.
  * Test case to implement commons-el expression language expansion.
  */
  */
 public class AuthorizeTagExpressionLanguageTests extends TestCase {
 public class AuthorizeTagExpressionLanguageTests extends TestCase {
-    Mockery jmock = new Mockery();
     //~ Instance fields ================================================================================================
     //~ Instance fields ================================================================================================
 
 
     private final LegacyAuthorizeTag authorizeTag = new LegacyAuthorizeTag();
     private final LegacyAuthorizeTag authorizeTag = new LegacyAuthorizeTag();

+ 15 - 29
web/src/test/java/org/springframework/security/web/access/intercept/FilterSecurityInterceptorTests.java

@@ -15,13 +15,12 @@
 
 
 package org.springframework.security.web.access.intercept;
 package org.springframework.security.web.access.intercept;
 
 
-import java.util.List;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.*;
 
 
+import java.util.*;
 import javax.servlet.FilterChain;
 import javax.servlet.FilterChain;
 
 
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.After;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.Test;
@@ -38,17 +37,15 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.web.FilterInvocation;
 import org.springframework.security.web.FilterInvocation;
-import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
-import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
 
 
 
 
 /**
 /**
  * Tests {@link FilterSecurityInterceptor}.
  * Tests {@link FilterSecurityInterceptor}.
  *
  *
  * @author Ben Alex
  * @author Ben Alex
+ * @author Luke Taylor
  */
  */
 public class FilterSecurityInterceptorTests {
 public class FilterSecurityInterceptorTests {
-    private Mockery jmock = new JUnit4Mockery();
     private AuthenticationManager am;
     private AuthenticationManager am;
     private AccessDecisionManager adm;
     private AccessDecisionManager adm;
     private FilterInvocationSecurityMetadataSource ods;
     private FilterInvocationSecurityMetadataSource ods;
@@ -62,11 +59,11 @@ public class FilterSecurityInterceptorTests {
     @Before
     @Before
     public final void setUp() throws Exception {
     public final void setUp() throws Exception {
         interceptor = new FilterSecurityInterceptor();
         interceptor = new FilterSecurityInterceptor();
-        am = jmock.mock(AuthenticationManager.class);
-        ods = jmock.mock(FilterInvocationSecurityMetadataSource.class);
-        adm = jmock.mock(AccessDecisionManager.class);
-        ram = jmock.mock(RunAsManager.class);
-        publisher = jmock.mock(ApplicationEventPublisher.class);
+        am = mock(AuthenticationManager.class);
+        ods = mock(FilterInvocationSecurityMetadataSource.class);
+        adm = mock(AccessDecisionManager.class);
+        ram = mock(RunAsManager.class);
+        publisher = mock(ApplicationEventPublisher.class);
         interceptor.setAuthenticationManager(am);
         interceptor.setAuthenticationManager(am);
         interceptor.setSecurityMetadataSource(ods);
         interceptor.setSecurityMetadataSource(ods);
         interceptor.setAccessDecisionManager(adm);
         interceptor.setAccessDecisionManager(adm);
@@ -82,19 +79,13 @@ public class FilterSecurityInterceptorTests {
 
 
     @Test(expected=IllegalArgumentException.class)
     @Test(expected=IllegalArgumentException.class)
     public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass() throws Exception {
     public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass() throws Exception {
-        jmock.checking(new Expectations() {{
-            ignoring(ods);
-            allowing(adm).supports(FilterInvocation.class); will(returnValue(false));
-        }});
+        when(adm.supports(FilterInvocation.class)).thenReturn(true);
         interceptor.afterPropertiesSet();
         interceptor.afterPropertiesSet();
     }
     }
 
 
     @Test(expected=IllegalArgumentException.class)
     @Test(expected=IllegalArgumentException.class)
     public void testEnsuresRunAsManagerSupportsFilterInvocationClass() throws Exception {
     public void testEnsuresRunAsManagerSupportsFilterInvocationClass() throws Exception {
-        jmock.checking(new Expectations() {{
-            ignoring(ods);
-            allowing(ram).supports(FilterInvocation.class); will(returnValue(false));
-        }});
+        when(adm.supports(FilterInvocation.class)).thenReturn(false);
         interceptor.afterPropertiesSet();
         interceptor.afterPropertiesSet();
     }
     }
 
 
@@ -113,19 +104,14 @@ public class FilterSecurityInterceptorTests {
         SecurityContextHolder.getContext().setAuthentication(token);
         SecurityContextHolder.getContext().setAuthentication(token);
 
 
         // Create and test our secure object
         // Create and test our secure object
-        final FilterChain chain = jmock.mock(FilterChain.class);
+        final FilterChain chain = mock(FilterChain.class);
         final FilterInvocation fi = new FilterInvocation(request, response, chain);
         final FilterInvocation fi = new FilterInvocation(request, response, chain);
         final List<ConfigAttribute> attributes = SecurityConfig.createList("MOCK_OK");
         final List<ConfigAttribute> attributes = SecurityConfig.createList("MOCK_OK");
 
 
-        jmock.checking(new Expectations() {{
-            ignoring(ram);
-            allowing(ods).getAttributes(fi); will(returnValue(attributes));
-            oneOf(adm).decide(token, fi, attributes);
-            // Setup our expectation that the filter chain will be invoked, as access is granted
-            oneOf(chain).doFilter(request, response);
-            oneOf(publisher).publishEvent(with(aNonNull(AuthorizedEvent.class)));
-        }});
+        when(ods.getAttributes(fi)).thenReturn(attributes);
 
 
         interceptor.invoke(fi);
         interceptor.invoke(fi);
+
+        verify(publisher).publishEvent(any(AuthorizedEvent.class));        
     }
     }
 }
 }

+ 26 - 33
web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java

@@ -16,17 +16,15 @@
 package org.springframework.security.web.authentication.rememberme;
 package org.springframework.security.web.authentication.rememberme;
 
 
 import static org.junit.Assert.*;
 import static org.junit.Assert.*;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.*;
 import static org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.*;
 import static org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.*;
 
 
-import java.util.Date;
-
+import java.util.*;
 import javax.servlet.http.Cookie;
 import javax.servlet.http.Cookie;
 
 
 import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.codec.digest.DigestUtils;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.Test;
 import org.springframework.mock.web.MockHttpServletRequest;
 import org.springframework.mock.web.MockHttpServletRequest;
@@ -38,7 +36,6 @@ import org.springframework.security.core.userdetails.User;
 import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
-import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
 import org.springframework.util.StringUtils;
 import org.springframework.util.StringUtils;
 
 
 /**
 /**
@@ -47,30 +44,27 @@ import org.springframework.util.StringUtils;
  * @author Ben Alex
  * @author Ben Alex
  */
  */
 public class TokenBasedRememberMeServicesTests {
 public class TokenBasedRememberMeServicesTests {
-    private Mockery jmock = new JUnit4Mockery();
     private UserDetailsService uds;
     private UserDetailsService uds;
     private UserDetails user = new User("someone", "password", true, true, true, true,
     private UserDetails user = new User("someone", "password", true, true, true, true,
             AuthorityUtils.createAuthorityList("ROLE_ABC"));
             AuthorityUtils.createAuthorityList("ROLE_ABC"));
     private TokenBasedRememberMeServices services;
     private TokenBasedRememberMeServices services;
-    private Expectations udsWillReturnUser;
-    private Expectations udsWillThrowNotFound;
 
 
     //~ Methods ========================================================================================================
     //~ Methods ========================================================================================================
 
 
     @Before
     @Before
     public void createTokenBasedRememberMeServices() {
     public void createTokenBasedRememberMeServices() {
         services = new TokenBasedRememberMeServices();
         services = new TokenBasedRememberMeServices();
-        uds = jmock.mock(UserDetailsService.class);
+        uds = mock(UserDetailsService.class);
         services.setKey("key");
         services.setKey("key");
         services.setUserDetailsService(uds);
         services.setUserDetailsService(uds);
-        udsWillReturnUser = new Expectations() {{
-            oneOf(uds).loadUserByUsername(with(aNonNull(String.class))); will(returnValue(user));
-        }};
-        udsWillThrowNotFound = new Expectations() {{
-            oneOf(uds).loadUserByUsername(with(aNonNull(String.class)));
-            will(throwException(new UsernameNotFoundException("")));
-        }};
+    }
+
+    void udsWillReturnUser() {
+        when(uds.loadUserByUsername(any(String.class))).thenReturn(user);
+    }
 
 
+    void udsWillThrowNotFound() {
+        when(uds.loadUserByUsername(any(String.class))).thenThrow(new UsernameNotFoundException(""));
     }
     }
 
 
     private long determineExpiryTimeFromBased64EncodedToken(String validToken) {
     private long determineExpiryTimeFromBased64EncodedToken(String validToken) {
@@ -79,8 +73,8 @@ public class TokenBasedRememberMeServicesTests {
 
 
         if (cookieTokens.length == 3) {
         if (cookieTokens.length == 3) {
             try {
             try {
-                return new Long(cookieTokens[1]).longValue();
-            } catch (NumberFormatException nfe) {}
+                return Long.parseLong(cookieTokens[1]);
+            } catch (NumberFormatException ignored) {}
         }
         }
 
 
         return -1;
         return -1;
@@ -89,11 +83,10 @@ public class TokenBasedRememberMeServicesTests {
     private String generateCorrectCookieContentForToken(long expiryTime, String username, String password, String key) {
     private String generateCorrectCookieContentForToken(long expiryTime, String username, String password, String key) {
         // format is:
         // format is:
         //     username + ":" + expiryTime + ":" + Md5Hex(username + ":" + expiryTime + ":" + password + ":" + key)
         //     username + ":" + expiryTime + ":" + Md5Hex(username + ":" + expiryTime + ":" + password + ":" + key)
-        String signatureValue = new String(DigestUtils.md5Hex(username + ":" + expiryTime + ":" + password + ":" + key));
+        String signatureValue = DigestUtils.md5Hex(username + ":" + expiryTime + ":" + password + ":" + key);
         String tokenValue = username + ":" + expiryTime + ":" + signatureValue;
         String tokenValue = username + ":" + expiryTime + ":" + signatureValue;
-        String tokenValueBase64 = new String(Base64.encodeBase64(tokenValue.getBytes()));
 
 
-        return tokenValueBase64;
+        return new String(Base64.encodeBase64(tokenValue.getBytes()));
     }
     }
 
 
     @Test
     @Test
@@ -110,7 +103,7 @@ public class TokenBasedRememberMeServicesTests {
     public void autoLoginIgnoresUnrelatedCookie() throws Exception {
     public void autoLoginIgnoresUnrelatedCookie() throws Exception {
         Cookie cookie = new Cookie("unrelated_cookie", "foobar");
         Cookie cookie = new Cookie("unrelated_cookie", "foobar");
         MockHttpServletRequest request = new MockHttpServletRequest();
         MockHttpServletRequest request = new MockHttpServletRequest();
-        request.setCookies(new Cookie[] {cookie});
+        request.setCookies(cookie);
         MockHttpServletResponse response = new MockHttpServletResponse();
         MockHttpServletResponse response = new MockHttpServletResponse();
 
 
         Authentication result = services.autoLogin(request, response);
         Authentication result = services.autoLogin(request, response);
@@ -124,7 +117,7 @@ public class TokenBasedRememberMeServicesTests {
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
                 generateCorrectCookieContentForToken(System.currentTimeMillis() - 1000000, "someone", "password", "key"));
                 generateCorrectCookieContentForToken(System.currentTimeMillis() - 1000000, "someone", "password", "key"));
         MockHttpServletRequest request = new MockHttpServletRequest();
         MockHttpServletRequest request = new MockHttpServletRequest();
-        request.setCookies(new Cookie[] {cookie});
+        request.setCookies(cookie);
 
 
         MockHttpServletResponse response = new MockHttpServletResponse();
         MockHttpServletResponse response = new MockHttpServletResponse();
 
 
@@ -139,7 +132,7 @@ public class TokenBasedRememberMeServicesTests {
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
                 new String(Base64.encodeBase64("x".getBytes())));
                 new String(Base64.encodeBase64("x".getBytes())));
         MockHttpServletRequest request = new MockHttpServletRequest();
         MockHttpServletRequest request = new MockHttpServletRequest();
-        request.setCookies(new Cookie[] {cookie});
+        request.setCookies(cookie);
 
 
         MockHttpServletResponse response = new MockHttpServletResponse();
         MockHttpServletResponse response = new MockHttpServletResponse();
         assertNull(services.autoLogin(request, response));
         assertNull(services.autoLogin(request, response));
@@ -154,7 +147,7 @@ public class TokenBasedRememberMeServicesTests {
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
                 "NOT_BASE_64_ENCODED");
                 "NOT_BASE_64_ENCODED");
         MockHttpServletRequest request = new MockHttpServletRequest();
         MockHttpServletRequest request = new MockHttpServletRequest();
-        request.setCookies(new Cookie[] {cookie});
+        request.setCookies(cookie);
 
 
         MockHttpServletResponse response = new MockHttpServletResponse();
         MockHttpServletResponse response = new MockHttpServletResponse();
         assertNull(services.autoLogin(request, response));
         assertNull(services.autoLogin(request, response));
@@ -166,12 +159,12 @@ public class TokenBasedRememberMeServicesTests {
 
 
     @Test
     @Test
     public void autoLoginClearsCookieIfSignatureBlocksDoesNotMatchExpectedValue() throws Exception {
     public void autoLoginClearsCookieIfSignatureBlocksDoesNotMatchExpectedValue() throws Exception {
-        jmock.checking(udsWillReturnUser);
+        udsWillReturnUser();
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
                 generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password",
                 generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password",
                     "WRONG_KEY"));
                     "WRONG_KEY"));
         MockHttpServletRequest request = new MockHttpServletRequest();
         MockHttpServletRequest request = new MockHttpServletRequest();
-        request.setCookies(new Cookie[] {cookie});
+        request.setCookies(cookie);
 
 
         MockHttpServletResponse response = new MockHttpServletResponse();
         MockHttpServletResponse response = new MockHttpServletResponse();
 
 
@@ -187,7 +180,7 @@ public class TokenBasedRememberMeServicesTests {
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
                 new String(Base64.encodeBase64("username:NOT_A_NUMBER:signature".getBytes())));
                 new String(Base64.encodeBase64("username:NOT_A_NUMBER:signature".getBytes())));
         MockHttpServletRequest request = new MockHttpServletRequest();
         MockHttpServletRequest request = new MockHttpServletRequest();
-        request.setCookies(new Cookie[] {cookie});
+        request.setCookies(cookie);
 
 
         MockHttpServletResponse response = new MockHttpServletResponse();
         MockHttpServletResponse response = new MockHttpServletResponse();
         assertNull(services.autoLogin(request, response));
         assertNull(services.autoLogin(request, response));
@@ -199,11 +192,11 @@ public class TokenBasedRememberMeServicesTests {
 
 
     @Test
     @Test
     public void autoLoginClearsCookieIfUserNotFound() throws Exception {
     public void autoLoginClearsCookieIfUserNotFound() throws Exception {
-        jmock.checking(udsWillThrowNotFound);
+        udsWillThrowNotFound();
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
                 generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", "key"));
                 generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", "key"));
         MockHttpServletRequest request = new MockHttpServletRequest();
         MockHttpServletRequest request = new MockHttpServletRequest();
-        request.setCookies(new Cookie[] {cookie});
+        request.setCookies(cookie);
 
 
         MockHttpServletResponse response = new MockHttpServletResponse();
         MockHttpServletResponse response = new MockHttpServletResponse();
 
 
@@ -216,11 +209,11 @@ public class TokenBasedRememberMeServicesTests {
 
 
     @Test
     @Test
     public void autoLoginWithValidTokenAndUserSucceeds() throws Exception {
     public void autoLoginWithValidTokenAndUserSucceeds() throws Exception {
-        jmock.checking(udsWillReturnUser);
+        udsWillReturnUser();
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
         Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
                 generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", "key"));
                 generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", "key"));
         MockHttpServletRequest request = new MockHttpServletRequest();
         MockHttpServletRequest request = new MockHttpServletRequest();
-        request.setCookies(new Cookie[] {cookie});
+        request.setCookies(cookie);
 
 
         MockHttpServletResponse response = new MockHttpServletResponse();
         MockHttpServletResponse response = new MockHttpServletResponse();
 
 

+ 4 - 13
web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java

@@ -19,8 +19,7 @@ import static org.junit.Assert.*;
 import static org.mockito.Mockito.*;
 import static org.mockito.Mockito.*;
 
 
 import java.io.IOException;
 import java.io.IOException;
-import java.util.Map;
-
+import java.util.*;
 import javax.servlet.Filter;
 import javax.servlet.Filter;
 import javax.servlet.FilterChain;
 import javax.servlet.FilterChain;
 import javax.servlet.ServletException;
 import javax.servlet.ServletException;
@@ -28,9 +27,6 @@ import javax.servlet.ServletRequest;
 
 
 import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.codec.digest.DigestUtils;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.After;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.Test;
@@ -88,22 +84,17 @@ public class DigestAuthenticationFilterTests {
                                                                       final boolean expectChainToProceed) throws ServletException, IOException {
                                                                       final boolean expectChainToProceed) throws ServletException, IOException {
         final MockHttpServletResponse response = new MockHttpServletResponse();
         final MockHttpServletResponse response = new MockHttpServletResponse();
 
 
-        Mockery jmockContext = new JUnit4Mockery();
-        final FilterChain chain = jmockContext.mock(FilterChain.class);
-
-        jmockContext.checking(new Expectations() {{
-             exactly(expectChainToProceed ? 1 : 0).of(chain).doFilter(request, response);
-        }});
+        final FilterChain chain = mock(FilterChain.class);
 
 
         filter.doFilter(request, response, chain);
         filter.doFilter(request, response, chain);
 
 
-        jmockContext.assertIsSatisfied();
+        verify(chain, times(expectChainToProceed ? 1 : 0)).doFilter(request, response);
         return response;
         return response;
     }
     }
 
 
     private static String generateNonce(int validitySeconds) {
     private static String generateNonce(int validitySeconds) {
         long expiryTime = System.currentTimeMillis() + (validitySeconds * 1000);
         long expiryTime = System.currentTimeMillis() + (validitySeconds * 1000);
-        String signatureValue = new String(DigestUtils.md5Hex(expiryTime + ":" + KEY));
+        String signatureValue = DigestUtils.md5Hex(expiryTime + ":" + KEY);
         String nonceValue = expiryTime + ":" + signatureValue;
         String nonceValue = expiryTime + ":" + signatureValue;
 
 
         return new String(Base64.encodeBase64(nonceValue.getBytes()));
         return new String(Base64.encodeBase64(nonceValue.getBytes()));

+ 14 - 36
web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java

@@ -1,22 +1,15 @@
 package org.springframework.security.web.context;
 package org.springframework.security.web.context;
 
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.*;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.*;
 
 
 import java.io.IOException;
 import java.io.IOException;
-
 import javax.servlet.FilterChain;
 import javax.servlet.FilterChain;
 import javax.servlet.ServletException;
 import javax.servlet.ServletException;
 import javax.servlet.ServletRequest;
 import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
 import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
 
 
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.After;
 import org.junit.After;
 import org.junit.Test;
 import org.junit.Test;
 import org.springframework.mock.web.MockHttpServletRequest;
 import org.springframework.mock.web.MockHttpServletRequest;
@@ -27,7 +20,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.core.context.SecurityContextImpl;
 import org.springframework.security.core.context.SecurityContextImpl;
 
 
 public class SecurityContextPersistenceFilterTests {
 public class SecurityContextPersistenceFilterTests {
-    Mockery jmock = new JUnit4Mockery();
     TestingAuthenticationToken testToken = new TestingAuthenticationToken("someone", "passwd", "ROLE_A");
     TestingAuthenticationToken testToken = new TestingAuthenticationToken("someone", "passwd", "ROLE_A");
 
 
     @After
     @After
@@ -37,31 +29,25 @@ public class SecurityContextPersistenceFilterTests {
 
 
     @Test
     @Test
     public void contextIsClearedAfterChainProceeds() throws Exception {
     public void contextIsClearedAfterChainProceeds() throws Exception {
-        final FilterChain chain = jmock.mock(FilterChain.class);
+        final FilterChain chain = mock(FilterChain.class);
         final MockHttpServletRequest request = new MockHttpServletRequest();
         final MockHttpServletRequest request = new MockHttpServletRequest();
         final MockHttpServletResponse response = new MockHttpServletResponse();
         final MockHttpServletResponse response = new MockHttpServletResponse();
         SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
         SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
         SecurityContextHolder.getContext().setAuthentication(testToken);
         SecurityContextHolder.getContext().setAuthentication(testToken);
-        jmock.checking(new Expectations() {{
-            oneOf(chain).doFilter(with(aNonNull(HttpServletRequest.class)), with(aNonNull(HttpServletResponse.class)));
-        }});
 
 
         filter.doFilter(request, response, chain);
         filter.doFilter(request, response, chain);
+        verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
         assertNull(SecurityContextHolder.getContext().getAuthentication());
         assertNull(SecurityContextHolder.getContext().getAuthentication());
     }
     }
 
 
     @Test
     @Test
     public void contextIsStillClearedIfExceptionIsThrowByFilterChain() throws Exception {
     public void contextIsStillClearedIfExceptionIsThrowByFilterChain() throws Exception {
-        final FilterChain chain = jmock.mock(FilterChain.class);
+        final FilterChain chain = mock(FilterChain.class);
         final MockHttpServletRequest request = new MockHttpServletRequest();
         final MockHttpServletRequest request = new MockHttpServletRequest();
         final MockHttpServletResponse response = new MockHttpServletResponse();
         final MockHttpServletResponse response = new MockHttpServletResponse();
         SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
         SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
         SecurityContextHolder.getContext().setAuthentication(testToken);
         SecurityContextHolder.getContext().setAuthentication(testToken);
-
-        jmock.checking(new Expectations() {{
-            oneOf(chain).doFilter(with(aNonNull(HttpServletRequest.class)), with(aNonNull(HttpServletResponse.class)));
-            will(throwException(new IOException()));
-        }});
+        doThrow(new IOException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
         try {
         try {
             filter.doFilter(request, response, chain);
             filter.doFilter(request, response, chain);
             fail();
             fail();
@@ -81,13 +67,10 @@ public class SecurityContextPersistenceFilterTests {
         final SecurityContext scExpectedAfter = new SecurityContextImpl();
         final SecurityContext scExpectedAfter = new SecurityContextImpl();
         scExpectedAfter.setAuthentication(testToken);
         scExpectedAfter.setAuthentication(testToken);
         scBefore.setAuthentication(beforeAuth);
         scBefore.setAuthentication(beforeAuth);
-        final SecurityContextRepository repo = jmock.mock(SecurityContextRepository.class);
+        final SecurityContextRepository repo = mock(SecurityContextRepository.class);
         filter.setSecurityContextRepository(repo);
         filter.setSecurityContextRepository(repo);
 
 
-        jmock.checking(new Expectations() {{
-            oneOf(repo).loadContext(with(aNonNull(HttpRequestResponseHolder.class))); will(returnValue(scBefore));
-            oneOf(repo).saveContext(scExpectedAfter, request, response);
-        }});
+        when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore);
 
 
         final FilterChain chain = new FilterChain() {
         final FilterChain chain = new FilterChain() {
             public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
             public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
@@ -99,30 +82,25 @@ public class SecurityContextPersistenceFilterTests {
 
 
         filter.doFilter(request, response, chain);
         filter.doFilter(request, response, chain);
 
 
-        jmock.assertIsSatisfied();
+        verify(repo).saveContext(scExpectedAfter, request, response);
     }
     }
 
 
     @Test
     @Test
     public void filterIsNotAppliedAgainIfFilterAppliedAttributeIsSet() throws Exception {
     public void filterIsNotAppliedAgainIfFilterAppliedAttributeIsSet() throws Exception {
-        final FilterChain chain = jmock.mock(FilterChain.class);
+        final FilterChain chain = mock(FilterChain.class);
         final MockHttpServletRequest request = new MockHttpServletRequest();
         final MockHttpServletRequest request = new MockHttpServletRequest();
         final MockHttpServletResponse response = new MockHttpServletResponse();
         final MockHttpServletResponse response = new MockHttpServletResponse();
         SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
         SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
-        filter.setSecurityContextRepository(jmock.mock(SecurityContextRepository.class));
-
-        jmock.checking(new Expectations() {{
-            oneOf(chain).doFilter(request, response);
-        }});
+        filter.setSecurityContextRepository(mock(SecurityContextRepository.class));
 
 
         request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE);
         request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE);
         filter.doFilter(request, response, chain);
         filter.doFilter(request, response, chain);
-        jmock.assertIsSatisfied();
+        verify(chain).doFilter(request, response);
     }
     }
 
 
     @Test
     @Test
     public void sessionIsEagerlyCreatedWhenConfigured() throws Exception {
     public void sessionIsEagerlyCreatedWhenConfigured() throws Exception {
-        final FilterChain chain = jmock.mock(FilterChain.class);
-        jmock.checking(new Expectations() {{ ignoring(chain); }});
+        final FilterChain chain = mock(FilterChain.class);
         final MockHttpServletRequest request = new MockHttpServletRequest();
         final MockHttpServletRequest request = new MockHttpServletRequest();
         final MockHttpServletResponse response = new MockHttpServletResponse();
         final MockHttpServletResponse response = new MockHttpServletResponse();
         SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
         SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();

+ 6 - 13
web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java

@@ -15,17 +15,15 @@
 
 
 package org.springframework.security.web.servletapi;
 package org.springframework.security.web.servletapi;
 
 
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.*;
+
 import javax.servlet.FilterChain;
 import javax.servlet.FilterChain;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpServletResponse;
 
 
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Test;
 import org.junit.Test;
 import org.springframework.mock.web.MockHttpServletRequest;
 import org.springframework.mock.web.MockHttpServletRequest;
 import org.springframework.mock.web.MockHttpServletResponse;
 import org.springframework.mock.web.MockHttpServletResponse;
-import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
-import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
 
 
 
 
 /**
 /**
@@ -34,7 +32,6 @@ import org.springframework.security.web.servletapi.SecurityContextHolderAwareReq
  * @author Ben Alex
  * @author Ben Alex
  */
  */
 public class SecurityContextHolderAwareRequestFilterTests {
 public class SecurityContextHolderAwareRequestFilterTests {
-    Mockery jmock = new JUnit4Mockery();
 
 
     //~ Methods ========================================================================================================
     //~ Methods ========================================================================================================
 
 
@@ -42,19 +39,15 @@ public class SecurityContextHolderAwareRequestFilterTests {
     public void expectedRequestWrapperClassIsUsed() throws Exception {
     public void expectedRequestWrapperClassIsUsed() throws Exception {
         SecurityContextHolderAwareRequestFilter filter = new SecurityContextHolderAwareRequestFilter();
         SecurityContextHolderAwareRequestFilter filter = new SecurityContextHolderAwareRequestFilter();
         filter.setRolePrefix("ROLE_");
         filter.setRolePrefix("ROLE_");
-//        filter.init(jmock.mock(FilterConfig.class));
-        final FilterChain filterChain = jmock.mock(FilterChain.class);
-
-        jmock.checking(new Expectations() {{
-            exactly(2).of(filterChain).doFilter(
-                    with(aNonNull(SecurityContextHolderAwareRequestWrapper.class)), with(aNonNull(HttpServletResponse.class)));
-        }});
+        final FilterChain filterChain = mock(FilterChain.class);
 
 
         filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), filterChain);
         filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), filterChain);
 
 
         // Now re-execute the filter, ensuring our replacement wrapper is still used
         // Now re-execute the filter, ensuring our replacement wrapper is still used
         filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), filterChain);
         filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), filterChain);
 
 
+        verify(filterChain, times(2)).doFilter(any(SecurityContextHolderAwareRequestWrapper.class), any(HttpServletResponse.class));
+
         filter.destroy();
         filter.destroy();
     }
     }
 }
 }