From 469549d04ec54555065b19998bb20393470c3ef8 Mon Sep 17 00:00:00 2001 From: Mattias Hellborg Arthursson Date: Tue, 27 Aug 2013 13:15:41 +0200 Subject: [PATCH] LDAP-257: Upgraded all core unit tests to JUnit 4 style, and migrated to Mockito. --- core/build.gradle | 7 +- .../ldap/NamingExceptionTest.java | 13 +- ...luesAuthenticationSourceDecoratorTest.java | 68 +- .../ldap/control/PagedResultTest.java | 18 +- .../ldap/control/PagedResultsCookieTest.java | 11 +- .../PagedResultsDirContextProcessorTest.java | 63 +- ...RequestControlDirContextProcessorTest.java | 124 +- .../SortControlDirContextProcessorTest.java | 76 +- ...ctingNameClassPairCallbackHandlerTest.java | 27 +- .../ContextMapperCallbackHandlerTest.java | 61 +- .../ldap/core/DirContextAdapterBugTest.java | 12 +- .../ldap/core/DirContextAdapterTest.java | 89 +- .../core/DistinguishedNameEditorTest.java | 23 +- .../ldap/core/DistinguishedNameTest.java | 162 ++- .../ldap/core/LdapEncoderTest.java | 31 +- .../ldap/core/LdapRdnComponentTest.java | 20 +- .../ldap/core/LdapRdnTest.java | 71 +- .../ldap/core/LdapTemplateListTest.java | 228 +--- .../ldap/core/LdapTemplateLookupTest.java | 233 +--- .../ldap/core/LdapTemplateRenameTest.java | 108 +- .../ldap/core/LdapTemplateTest.java | 1142 +++++++---------- .../ldap/core/RequestControlMatcher.java | 72 -- .../AggregateDirContextProcessorTest.java | 73 +- .../BaseLdapPathBeanPostProcessorTest.java | 102 +- ...ameClassPairResultCallbackHandlerTest.java | 25 +- .../support/DefaultDirObjectFactoryTest.java | 94 +- ...efaultIncrementalAttributesMapperTest.java | 29 +- .../core/support/LdapContextSourceTest.java | 65 +- .../ldap/core/support/RangeOptionTest.java | 19 +- ...eDirContextAuthenticationStrategyTest.java | 20 +- .../ldap/filter/AbstractFilterTest.java | 20 +- .../ldap/filter/AndFilterTest.java | 24 +- .../ldap/filter/EqualsFilterTest.java | 21 +- .../filter/GreaterThanOrEqualsFilterTest.java | 21 +- .../ldap/filter/HardcodedFilterTest.java | 14 +- .../filter/LessThanOrEqualsFilterTest.java | 21 +- .../ldap/filter/LikeFilterTest.java | 21 +- .../ldap/filter/NotFilterTest.java | 12 +- .../ldap/filter/NotPresentFilterTest.java | 14 +- .../ldap/filter/OrFilterTest.java | 22 +- .../ldap/filter/PresentFilterTest.java | 14 +- .../filter/WhitespaceWildcardsFilterTest.java | 15 +- .../ldap/pool/AbstractPoolTestCase.java | 98 +- .../ldap/pool/DelegatingContextTest.java | 100 +- .../ldap/pool/DelegatingDirContextTest.java | 86 +- .../ldap/pool/DelegatingLdapContextTest.java | 87 +- .../MutableDelegatingLdapContextTest.java | 12 +- .../DirContextPoolableObjectFactoryTest.java | 116 +- .../MutablePoolingContextSourceTest.java | 19 +- .../factory/PoolingContextSourceTest.java | 69 +- .../DefaultDirContextValidatorTest.java | 96 +- .../ldap/support/LdapUtilsTest.java | 84 +- .../BindOperationExecutorTest.java | 56 +- .../BindOperationRecorderTest.java | 44 +- ...satingTransactionOperationFactoryTest.java | 68 +- .../LdapTransactionUtilsTest.java | 49 +- ...ModifyAttributesOperationExecutorTest.java | 60 +- ...ModifyAttributesOperationRecorderTest.java | 77 +- .../RebindOperationExecutorTest.java | 61 +- .../RebindOperationRecorderTest.java | 62 +- .../RenameOperationExecutorTest.java | 50 +- .../RenameOperationRecorderTest.java | 39 +- .../UnbindOperationExecutorTest.java | 53 +- .../UnbindOperationRecorderTest.java | 57 +- .../ContextSourceTransactionManagerTest.java | 142 +- ...ransactionAwareContextSourceProxyTest.java | 81 +- ...nAwareDirContextInvocationHandlerTest.java | 80 +- .../DefaultTempEntryRenamingStrategyTest.java | 15 +- ...tSubtreeTempEntryRenamingStrategyTest.java | 14 +- .../CompensatingTransactionUtilsTest.java | 76 +- ...satingTransactionOperationManagerTest.java | 124 +- gradle/java.gradle | 3 +- 72 files changed, 1970 insertions(+), 3313 deletions(-) delete mode 100644 core/src/test/java/org/springframework/ldap/core/RequestControlMatcher.java diff --git a/core/build.gradle b/core/build.gradle index b77dc958..64803946 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -1,6 +1,3 @@ -sourceCompatibility = '1.4' -targetCompatibility = '1.4' - apply from: 'javacc.gradle' idea.module.excludeDirs = [ @@ -25,7 +22,7 @@ dependencies { "org.springframework:spring-orm:$springVersion" testCompile "junit:junit:$junitVersion", - "easymock:easymock:$easyMockVersion", - "gsbase:gsbase:$gsbaseVersion" + "gsbase:gsbase:$gsbaseVersion", + "org.mockito:mockito-core:$mockitoVersion" } diff --git a/core/src/test/java/org/springframework/ldap/NamingExceptionTest.java b/core/src/test/java/org/springframework/ldap/NamingExceptionTest.java index c0ffb26b..47b07c0f 100644 --- a/core/src/test/java/org/springframework/ldap/NamingExceptionTest.java +++ b/core/src/test/java/org/springframework/ldap/NamingExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,24 +15,27 @@ */ package org.springframework.ldap; +import org.junit.Test; + +import javax.naming.directory.InitialDirContext; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import javax.naming.directory.InitialDirContext; - -import junit.framework.TestCase; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; /** * Unit tests for the NamingException class. * * @author Ulrik Sandberg */ -public class NamingExceptionTest extends TestCase { +public class NamingExceptionTest { private ByteArrayOutputStream byteArrayOutputStream; + @Test public void testNamingExceptionWithNonSerializableResolvedObj() throws Exception { javax.naming.NameAlreadyBoundException wrappedException = new javax.naming.NameAlreadyBoundException( diff --git a/core/src/test/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecoratorTest.java b/core/src/test/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecoratorTest.java index 4124098d..25ce8750 100644 --- a/core/src/test/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecoratorTest.java +++ b/core/src/test/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecoratorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,13 +15,17 @@ */ package org.springframework.ldap.authentication; -import org.easymock.MockControl; -import org.springframework.ldap.authentication.DefaultValuesAuthenticationSourceDecorator; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.AuthenticationSource; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -public class DefaultValuesAuthenticationSourceDecoratorTest extends TestCase { +public class DefaultValuesAuthenticationSourceDecoratorTest { private static final String DEFAULT_PASSWORD = "defaultPassword"; @@ -29,79 +33,55 @@ public class DefaultValuesAuthenticationSourceDecoratorTest extends TestCase { private DefaultValuesAuthenticationSourceDecorator tested; - private MockControl authenticationSourceControl; - private AuthenticationSource authenticationSourceMock; - protected void setUp() throws Exception { - super.setUp(); - - authenticationSourceControl = MockControl - .createControl(AuthenticationSource.class); - authenticationSourceMock = (AuthenticationSource) authenticationSourceControl - .getMock(); + @Before + public void setUp() throws Exception { + authenticationSourceMock = mock(AuthenticationSource.class); tested = new DefaultValuesAuthenticationSourceDecorator(); tested.setDefaultUser(DEFAULT_USER); tested.setDefaultPassword(DEFAULT_PASSWORD); tested.setTarget(authenticationSourceMock); } - protected void tearDown() throws Exception { - super.tearDown(); - - tested = null; - authenticationSourceControl = null; - authenticationSourceMock = null; - } - + @Test public void testGetPrincipal_TargetHasPrincipal() { - authenticationSourceControl.expectAndDefaultReturn( - authenticationSourceMock.getPrincipal(), "cn=someUser"); - authenticationSourceControl.replay(); - + when(authenticationSourceMock.getPrincipal()).thenReturn("cn=someUser"); String principal = tested.getPrincipal(); - authenticationSourceControl.verify(); assertEquals("cn=someUser", principal); } + @Test public void testGetPrincipal_TargetHasNoPrincipal() { - authenticationSourceControl.expectAndDefaultReturn( - authenticationSourceMock.getPrincipal(), ""); - authenticationSourceControl.replay(); + when(authenticationSourceMock.getPrincipal()).thenReturn(""); String principal = tested.getPrincipal(); - authenticationSourceControl.verify(); assertEquals(DEFAULT_USER, principal); } + @Test public void testGetCredentials_TargetHasPrincipal() { - authenticationSourceControl.expectAndDefaultReturn( - authenticationSourceMock.getPrincipal(), "cn=someUser"); - authenticationSourceControl.expectAndDefaultReturn( - authenticationSourceMock.getCredentials(), "somepassword"); - authenticationSourceControl.replay(); + when(authenticationSourceMock.getPrincipal()).thenReturn("cn=someUser"); + when(authenticationSourceMock.getCredentials()).thenReturn("somepassword"); String credentials = tested.getCredentials(); - authenticationSourceControl.verify(); assertEquals("somepassword", credentials); } + @Test public void testGetCredentials_TargetHasNoPrincipal() { - authenticationSourceControl.expectAndDefaultReturn( - authenticationSourceMock.getPrincipal(), ""); - authenticationSourceControl.expectAndDefaultReturn( - authenticationSourceMock.getCredentials(), "somepassword"); - authenticationSourceControl.replay(); + when(authenticationSourceMock.getPrincipal()).thenReturn(""); + when(authenticationSourceMock.getCredentials()).thenReturn("somepassword"); String credentials = tested.getCredentials(); - authenticationSourceControl.verify(); assertEquals(DEFAULT_PASSWORD, credentials); } + @Test public void testAfterPropertiesSet_noTarget() throws Exception { tested.setTarget(null); try { @@ -112,6 +92,7 @@ public class DefaultValuesAuthenticationSourceDecoratorTest extends TestCase { } } + @Test public void testAfterPropertiesSet_noDefaultUser() throws Exception { tested.setDefaultUser(null); try { @@ -122,6 +103,7 @@ public class DefaultValuesAuthenticationSourceDecoratorTest extends TestCase { } } + @Test public void testAfterPropertiesSet_noDefaultPassword() throws Exception { tested.setDefaultPassword(null); try { diff --git a/core/src/test/java/org/springframework/ldap/control/PagedResultTest.java b/core/src/test/java/org/springframework/ldap/control/PagedResultTest.java index 1247c51c..b7d182e2 100644 --- a/core/src/test/java/org/springframework/ldap/control/PagedResultTest.java +++ b/core/src/test/java/org/springframework/ldap/control/PagedResultTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,17 +15,12 @@ */ package org.springframework.ldap.control; -import java.util.LinkedList; -import java.util.List; +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; import javax.naming.ldap.PagedResultsControl; - -import org.springframework.ldap.control.PagedResult; -import org.springframework.ldap.control.PagedResultsCookie; - -import com.gargoylesoftware.base.testing.EqualsTester; - -import junit.framework.TestCase; +import java.util.LinkedList; +import java.util.List; /** * Unit tests for the PagedResult class. @@ -34,7 +29,8 @@ import junit.framework.TestCase; * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ -public class PagedResultTest extends TestCase { +public class PagedResultTest { + @Test public void testEquals() throws Exception { List expectedList = new LinkedList(); expectedList.add("dummy"); diff --git a/core/src/test/java/org/springframework/ldap/control/PagedResultsCookieTest.java b/core/src/test/java/org/springframework/ldap/control/PagedResultsCookieTest.java index 17fa365f..e71cef5a 100644 --- a/core/src/test/java/org/springframework/ldap/control/PagedResultsCookieTest.java +++ b/core/src/test/java/org/springframework/ldap/control/PagedResultsCookieTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.ldap.control; -import org.springframework.ldap.control.PagedResultsCookie; - import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; -import junit.framework.TestCase; - -public class PagedResultsCookieTest extends TestCase { +public class PagedResultsCookieTest { + @Test public void testEquals() { byte[] expectedCookie = new byte[] { 1, 2 }; byte[] differentCookie = new byte[] { 2, 3 }; diff --git a/core/src/test/java/org/springframework/ldap/control/PagedResultsDirContextProcessorTest.java b/core/src/test/java/org/springframework/ldap/control/PagedResultsDirContextProcessorTest.java index b4b700e6..273aa17b 100644 --- a/core/src/test/java/org/springframework/ldap/control/PagedResultsDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/control/PagedResultsDirContextProcessorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,9 @@ import com.sun.jndi.ldap.Ber; import com.sun.jndi.ldap.BerDecoder; import com.sun.jndi.ldap.BerEncoder; import com.sun.jndi.ldap.ctl.DirSyncResponseControl; -import junit.framework.TestCase; -import org.easymock.MockControl; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import javax.naming.ldap.Control; import javax.naming.ldap.LdapContext; @@ -28,46 +29,42 @@ import javax.naming.ldap.PagedResultsControl; import javax.naming.ldap.PagedResultsResponseControl; import java.io.IOException; -public class PagedResultsDirContextProcessorTest extends TestCase { +import static junit.framework.Assert.assertNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; - private MockControl ldapContextControl; +public class PagedResultsDirContextProcessorTest { private LdapContext ldapContextMock; private PagedResultsDirContextProcessor tested; - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { tested = new PagedResultsDirContextProcessor(20); // Create ldapContext mock - ldapContextControl = MockControl.createControl(LdapContext.class); - ldapContextMock = (LdapContext) ldapContextControl.getMock(); + ldapContextMock = mock(LdapContext.class); } - protected void tearDown() throws Exception { - super.tearDown(); + @After + public void tearDown() throws Exception { tested = null; - ldapContextControl = null; ldapContextMock = null; } - protected void replay() { - ldapContextControl.replay(); - } - - protected void verify() { - ldapContextControl.verify(); - } - + @Test public void testCreateRequestControl() throws Exception { PagedResultsControl control = (PagedResultsControl) tested .createRequestControl(); assertNotNull(control); } + @Test public void testCreateRequestControl_CookieSet() throws Exception { PagedResultsCookie cookie = new PagedResultsCookie(new byte[0]); PagedResultsDirContextProcessor tested = new PagedResultsDirContextProcessor(20, @@ -78,6 +75,7 @@ public class PagedResultsDirContextProcessorTest extends TestCase { assertNotNull(control); } + @Test public void testPostProcess() throws Exception { int resultSize = 50; byte pageSize = 8; @@ -88,21 +86,16 @@ public class PagedResultsDirContextProcessorTest extends TestCase { PagedResultsResponseControl control = new PagedResultsResponseControl( "dummy", true, cookie); - ldapContextControl.expectAndDefaultReturn(ldapContextMock - .getResponseControls(), new Control[] { control }); - - replay(); - + when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); tested.postProcess(ldapContextMock); - verify(); - PagedResultsCookie returnedCookie = tested.getCookie(); assertEquals(8, returnedCookie.getCookie()[0]); assertEquals(20, tested.getPageSize()); assertEquals(50, tested.getResultSize()); } + @Test public void testPostProcess_InvalidResponseControl() throws Exception { int resultSize = 50; byte pageSize = 8; @@ -115,35 +108,27 @@ public class PagedResultsDirContextProcessorTest extends TestCase { DirSyncResponseControl control = new DirSyncResponseControl( "dummy", true, cookie); - ldapContextControl.expectAndDefaultReturn(ldapContextMock - .getResponseControls(), new Control[] { control }); - - replay(); + when(ldapContextMock.getResponseControls()).thenReturn(new Control[]{control}); tested.postProcess(ldapContextMock); - verify(); - assertNull(tested.getCookie()); assertEquals(20, tested.getPageSize()); assertEquals(0, tested.getResultSize()); } + @Test public void testPostProcess_NoResponseControls() throws Exception { - ldapContextControl.expectAndDefaultReturn(ldapContextMock - .getResponseControls(), null); - - replay(); + when(ldapContextMock.getResponseControls()).thenReturn(null); tested.postProcess(ldapContextMock); - verify(); - assertNull(tested.getCookie()); assertEquals(20, tested.getPageSize()); assertEquals(0, tested.getResultSize()); } + @Test public void testBerDecoding() throws Exception { byte[] value = new byte[1]; value[0] = 8; diff --git a/core/src/test/java/org/springframework/ldap/control/RequestControlDirContextProcessorTest.java b/core/src/test/java/org/springframework/ldap/control/RequestControlDirContextProcessorTest.java index 84e012f1..47484cf9 100644 --- a/core/src/test/java/org/springframework/ldap/control/RequestControlDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/control/RequestControlDirContextProcessorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,54 +15,45 @@ */ package org.springframework.ldap.control; +import com.sun.jndi.ldap.ctl.SortControl; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.ldap.Control; import javax.naming.ldap.LdapContext; -import junit.framework.TestCase; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; -import org.easymock.MockControl; - -import com.sun.jndi.ldap.ctl.SortControl; - -public class RequestControlDirContextProcessorTest extends TestCase { +public class RequestControlDirContextProcessorTest { private AbstractRequestControlDirContextProcessor tested; - private MockControl requestControlControl; - private Control requestControlMock; - private MockControl requestControl2Control; - private Control requestControl2Mock; - private MockControl ldapContextControl; - private LdapContext ldapContextMock; - private MockControl dirContextControl; - private DirContext dirContextMock; - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { // Create requestControl mock - requestControlControl = MockControl.createControl(Control.class); - requestControlMock = (Control) requestControlControl.getMock(); + requestControlMock = mock(Control.class); // Create requestControl2 mock - requestControl2Control = MockControl.createControl(Control.class); - requestControl2Mock = (Control) requestControl2Control.getMock(); + requestControl2Mock = mock(Control.class); // Create ldapContext mock - ldapContextControl = MockControl.createControl(LdapContext.class); - ldapContextMock = (LdapContext) ldapContextControl.getMock(); + ldapContextMock = mock(LdapContext.class); // Create dirContext mock - dirContextControl = MockControl.createControl(DirContext.class); - dirContextMock = (DirContext) dirContextControl.getMock(); + dirContextMock = mock(DirContext.class); tested = new AbstractRequestControlDirContextProcessor() { @@ -76,109 +67,64 @@ public class RequestControlDirContextProcessorTest extends TestCase { }; } - protected void tearDown() throws Exception { - super.tearDown(); - - requestControlControl = null; + @After + public void tearDown() throws Exception { requestControlMock = null; - - requestControl2Control = null; requestControl2Mock = null; - - ldapContextControl = null; ldapContextMock = null; - - dirContextControl = null; dirContextMock = null; } - protected void replay() { - requestControlControl.replay(); - requestControl2Control.replay(); - ldapContextControl.replay(); - dirContextControl.replay(); - } - - protected void verify() { - requestControlControl.verify(); - requestControl2Control.verify(); - ldapContextControl.verify(); - dirContextControl.verify(); - } - + @Test public void testPreProcessWithExistingControlOfDifferentClassShouldAdd() throws Exception { - ldapContextControl.setDefaultMatcher(MockControl.ARRAY_MATCHER); SortControl existingControl = new SortControl(new String[] { "cn" }, true); - ldapContextControl.expectAndDefaultReturn(ldapContextMock.getRequestControls(), - new Control[] { existingControl }); - ldapContextMock.setRequestControls(new Control[] { existingControl, requestControlMock }); - - replay(); + when(ldapContextMock.getRequestControls()).thenReturn(new Control[]{existingControl}); tested.preProcess(ldapContextMock); - verify(); + verify(ldapContextMock).setRequestControls(new Control[] { existingControl, requestControlMock }); } + @Test public void testPreProcessWithExistingControlOfSameClassShouldReplace() throws Exception { - ldapContextControl.setDefaultMatcher(MockControl.ARRAY_MATCHER); - ldapContextControl.expectAndDefaultReturn(ldapContextMock.getRequestControls(), - new Control[] { requestControl2Mock }); - ldapContextMock.setRequestControls(new Control[] { requestControlMock }); - - replay(); + when(ldapContextMock.getRequestControls()).thenReturn(new Control[]{requestControl2Mock}); tested.preProcess(ldapContextMock); - verify(); + verify(ldapContextMock).setRequestControls(new Control[] { requestControlMock }); } + @Test public void testPreProcessWithExistingControlOfSameClassAndPropertyFalseShouldAdd() throws Exception { - ldapContextControl.setDefaultMatcher(MockControl.ARRAY_MATCHER); - ldapContextControl.expectAndDefaultReturn(ldapContextMock.getRequestControls(), - new Control[] { requestControl2Mock }); - ldapContextMock.setRequestControls(new Control[] { requestControl2Mock, requestControlMock }); - - replay(); + when(ldapContextMock.getRequestControls()).thenReturn(new Control[] { requestControl2Mock }); tested.setReplaceSameControlEnabled(false); tested.preProcess(ldapContextMock); - verify(); + verify(ldapContextMock).setRequestControls(new Control[]{requestControl2Mock, requestControlMock}); } + @Test public void testPreProcessWithNoExistingControlsShouldAdd() throws NamingException { - ldapContextControl.setDefaultMatcher(MockControl.ARRAY_MATCHER); - ldapContextControl.expectAndDefaultReturn(ldapContextMock.getRequestControls(), new Control[0]); - ldapContextMock.setRequestControls(new Control[] { requestControlMock }); - - replay(); + when(ldapContextMock.getRequestControls()).thenReturn(new Control[0]); tested.preProcess(ldapContextMock); - verify(); + verify(ldapContextMock).setRequestControls(new Control[]{requestControlMock}); } + @Test public void testPreProcessWithNullControlsShouldAdd() throws NamingException { - ldapContextControl.setDefaultMatcher(MockControl.ARRAY_MATCHER); - ldapContextControl.expectAndDefaultReturn(ldapContextMock.getRequestControls(), null); - ldapContextMock.setRequestControls(new Control[] { requestControlMock }); - - replay(); + when(ldapContextMock.getRequestControls()).thenReturn(null); tested.preProcess(ldapContextMock); - verify(); + verify(ldapContextMock).setRequestControls(new Control[] { requestControlMock }); } + @Test(expected = IllegalArgumentException.class) public void testPreProcessWhenNotLdapContextShouldFail() throws Exception { - try { - tested.preProcess(dirContextMock); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException expected) { - assertTrue(true); - } + tested.preProcess(dirContextMock); } } diff --git a/core/src/test/java/org/springframework/ldap/control/SortControlDirContextProcessorTest.java b/core/src/test/java/org/springframework/ldap/control/SortControlDirContextProcessorTest.java index cb9da438..96255e56 100644 --- a/core/src/test/java/org/springframework/ldap/control/SortControlDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/control/SortControlDirContextProcessorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,61 +15,44 @@ */ package org.springframework.ldap.control; -import java.io.IOException; +import com.sun.jndi.ldap.Ber; +import com.sun.jndi.ldap.BerDecoder; +import com.sun.jndi.ldap.BerEncoder; +import com.sun.jndi.ldap.ctl.DirSyncResponseControl; +import org.junit.Before; +import org.junit.Test; import javax.naming.ldap.Control; import javax.naming.ldap.LdapContext; import javax.naming.ldap.SortControl; import javax.naming.ldap.SortResponseControl; +import java.io.IOException; -import junit.framework.TestCase; - -import org.easymock.MockControl; - -import com.sun.jndi.ldap.Ber; -import com.sun.jndi.ldap.BerDecoder; -import com.sun.jndi.ldap.BerEncoder; -import com.sun.jndi.ldap.ctl.DirSyncResponseControl; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Unit tests for the SortControlDirContextProcessor class. * * @author Ulrik Sandberg */ -public class SortControlDirContextProcessorTest extends TestCase { - - private MockControl ldapContextControl; +public class SortControlDirContextProcessorTest { private LdapContext ldapContextMock; private SortControlDirContextProcessor tested; - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() throws Exception { tested = new SortControlDirContextProcessor("key"); // Create ldapContext mock - ldapContextControl = MockControl.createControl(LdapContext.class); - ldapContextMock = (LdapContext) ldapContextControl.getMock(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - - tested = null; - ldapContextControl = null; - ldapContextMock = null; - } - - protected void replay() { - ldapContextControl.replay(); - } - - protected void verify() { - ldapContextControl.verify(); + ldapContextMock = mock(LdapContext.class); } + @Test public void testCreateRequestControl() throws Exception { SortControl result = (SortControl) tested.createRequestControl(); assertNotNull(result); @@ -77,6 +60,7 @@ public class SortControlDirContextProcessorTest extends TestCase { assertEquals(9, result.getEncodedValue().length); } + @Test public void testPostProcess() throws Exception { byte sortResult = 0; // success @@ -84,19 +68,15 @@ public class SortControlDirContextProcessorTest extends TestCase { SortResponseControl control = new SortResponseControl( "dummy", true, value); - ldapContextControl.expectAndDefaultReturn(ldapContextMock - .getResponseControls(), new Control[] { control }); - - replay(); + when(ldapContextMock.getResponseControls()).thenReturn( new Control[]{control}); tested.postProcess(ldapContextMock); - verify(); - assertEquals(true, tested.isSorted()); assertEquals(0, tested.getResultCode()); } + @Test public void testPostProcess_NonSuccess() throws Exception { byte sortResult = 1; @@ -104,19 +84,15 @@ public class SortControlDirContextProcessorTest extends TestCase { SortResponseControl control = new SortResponseControl( "dummy", true, value); - ldapContextControl.expectAndDefaultReturn(ldapContextMock - .getResponseControls(), new Control[] { control }); - - replay(); + when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); tested.postProcess(ldapContextMock); - verify(); - assertEquals(false, tested.isSorted()); assertEquals(1, tested.getResultCode()); } + @Test public void testPostProcess_InvalidResponseControl() throws Exception { int resultSize = 50; byte pageSize = 8; @@ -129,18 +105,14 @@ public class SortControlDirContextProcessorTest extends TestCase { DirSyncResponseControl control = new DirSyncResponseControl("dummy", true, cookie); - ldapContextControl.expectAndDefaultReturn(ldapContextMock - .getResponseControls(), new Control[] { control }); - - replay(); + when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); tested.postProcess(ldapContextMock); - verify(); - assertEquals(false, tested.isSorted()); } + @Test public void testBerDecoding() throws Exception { int sortResult = 53; // unwilling to perform byte[] encoded = encodeValue(sortResult); diff --git a/core/src/test/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandlerTest.java b/core/src/test/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandlerTest.java index 624abc0f..f9949efb 100644 --- a/core/src/test/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandlerTest.java +++ b/core/src/test/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,16 @@ package org.springframework.ldap.core; -import java.util.List; +import org.junit.Before; +import org.junit.Test; import javax.naming.NameClassPair; +import java.util.List; -import org.springframework.ldap.core.CollectingNameClassPairCallbackHandler; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; -import junit.framework.TestCase; - -public class CollectingNameClassPairCallbackHandlerTest extends TestCase { +public class CollectingNameClassPairCallbackHandlerTest { private CollectingNameClassPairCallbackHandler tested; @@ -32,9 +33,8 @@ public class CollectingNameClassPairCallbackHandlerTest extends TestCase { private NameClassPair expectedNameClassPair; - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() throws Exception { expectedResult = new Object(); expectedNameClassPair = new NameClassPair(null, null); tested = new CollectingNameClassPairCallbackHandler() { @@ -45,14 +45,7 @@ public class CollectingNameClassPairCallbackHandlerTest extends TestCase { }; } - protected void tearDown() throws Exception { - super.tearDown(); - - expectedNameClassPair = null; - expectedResult = null; - tested = null; - } - + @Test public void testHandleNameClassPair() { tested.handleNameClassPair(expectedNameClassPair); List result = tested.getList(); diff --git a/core/src/test/java/org/springframework/ldap/core/ContextMapperCallbackHandlerTest.java b/core/src/test/java/org/springframework/ldap/core/ContextMapperCallbackHandlerTest.java index 7e4615cc..3d64ea14 100644 --- a/core/src/test/java/org/springframework/ldap/core/ContextMapperCallbackHandlerTest.java +++ b/core/src/test/java/org/springframework/ldap/core/ContextMapperCallbackHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,74 +15,47 @@ */ package org.springframework.ldap.core; +import org.junit.Before; +import org.junit.Test; + import javax.naming.Binding; -import org.easymock.MockControl; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -import junit.framework.TestCase; - -public class ContextMapperCallbackHandlerTest extends TestCase { - - private MockControl mapperControl; +public class ContextMapperCallbackHandlerTest { private ContextMapper mapperMock; private ContextMapperCallbackHandler tested; - protected void setUp() throws Exception { - super.setUp(); - - mapperControl = MockControl.createControl(ContextMapper.class); - mapperMock = (ContextMapper) mapperControl.getMock(); + @Before + public void setUp() throws Exception { + mapperMock = mock(ContextMapper.class); tested = new ContextMapperCallbackHandler(mapperMock); } - protected void tearDown() throws Exception { - super.tearDown(); - - mapperControl = null; - mapperMock = null; - tested = null; - } - + @Test(expected = IllegalArgumentException.class) public void testConstructorWithEmptyArgument() { - try { - new ContextMapperCallbackHandler(null); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertTrue(true); - } + new ContextMapperCallbackHandler(null); } + @Test public void testGetObjectFromNameClassPair() { Object expectedObject = "object"; Object expectedResult = "result"; Binding expectedBinding = new Binding("some name", expectedObject); - mapperControl.expectAndReturn( - mapperMock.mapFromContext(expectedObject), expectedResult); - - mapperControl.replay(); - + when(mapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); Object actualResult = tested .getObjectFromNameClassPair(expectedBinding); - - mapperControl.verify(); - assertEquals(expectedResult, actualResult); } + @Test(expected = ObjectRetrievalException.class) public void testGetObjectFromNameClassPairObjectRetrievalException() { Binding expectedBinding = new Binding("some name", null); - - mapperControl.replay(); - - try { - tested.getObjectFromNameClassPair(expectedBinding); - fail("ObjectRetrievalException expected"); - } catch (ObjectRetrievalException expected) { - assertTrue(true); - } - mapperControl.verify(); + tested.getObjectFromNameClassPair(expectedBinding); } } diff --git a/core/src/test/java/org/springframework/ldap/core/DirContextAdapterBugTest.java b/core/src/test/java/org/springframework/ldap/core/DirContextAdapterBugTest.java index 4c53bedc..ec48e8c7 100644 --- a/core/src/test/java/org/springframework/ldap/core/DirContextAdapterBugTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DirContextAdapterBugTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,13 @@ */ package org.springframework.ldap.core; +import org.junit.Test; + import javax.naming.Name; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttributes; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** @@ -27,8 +29,9 @@ import junit.framework.TestCase; * * @author Luke Taylor */ -public class DirContextAdapterBugTest extends TestCase { +public class DirContextAdapterBugTest { + @Test public void testResetAttributeValuesNotReportedAsModifications() { BasicAttributes attrs = new BasicAttributes("myattr", "a"); attrs.get("myattr").add("b"); @@ -41,6 +44,7 @@ public class DirContextAdapterBugTest extends TestCase { assertEquals(0, ctx.getModificationItems().length); } + @Test public void testResetAttributeValuesSameLengthNotReportedAsModifications() { BasicAttributes attrs = new BasicAttributes("myattr", "a"); attrs.get("myattr").add("b"); @@ -61,6 +65,7 @@ public class DirContextAdapterBugTest extends TestCase { * * TODO Is this correct behaviour? */ + @Test public void testResetNullAttributeValuesReportedAsModifications() { BasicAttributes attrs = new BasicAttributes("myattr", null); UpdateAdapter ctx = new UpdateAdapter(attrs, new DistinguishedName()); @@ -71,6 +76,7 @@ public class DirContextAdapterBugTest extends TestCase { assertEquals(1, ctx.getModificationItems().length); } + @Test public void testResetNullAttributeValueNotReportedAsModification() throws Exception { BasicAttributes attrs = new BasicAttributes("myattr", "b"); UpdateAdapter ctx = new UpdateAdapter(attrs, new DistinguishedName()); diff --git a/core/src/test/java/org/springframework/ldap/core/DirContextAdapterTest.java b/core/src/test/java/org/springframework/ldap/core/DirContextAdapterTest.java index 75b5426e..143bd2d9 100644 --- a/core/src/test/java/org/springframework/ldap/core/DirContextAdapterTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DirContextAdapterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ package org.springframework.ldap.core; -import java.util.Iterator; -import java.util.SortedSet; +import org.junit.Before; +import org.junit.Test; import javax.naming.CompositeName; import javax.naming.Name; @@ -28,8 +28,15 @@ import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; +import java.util.Iterator; +import java.util.SortedSet; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; /** * Tests the DirContextAdapter class. @@ -38,7 +45,7 @@ import junit.framework.TestCase; * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ -public class DirContextAdapterTest extends TestCase { +public class DirContextAdapterTest { private static final DistinguishedName BASE_NAME = new DistinguishedName( "dc=jayway, dc=se"); @@ -47,15 +54,12 @@ public class DirContextAdapterTest extends TestCase { private DirContextAdapter tested; - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { tested = new DirContextAdapter(); } - protected void tearDown() throws Exception { - super.tearDown(); - } - + @Test public void testSetUpdateMode() throws Exception { assertFalse(tested.isUpdateMode()); tested.setUpdateMode(true); @@ -64,6 +68,7 @@ public class DirContextAdapterTest extends TestCase { assertFalse(tested.isUpdateMode()); } + @Test public void testGetModificationItems() throws Exception { ModificationItem[] items = tested.getModificationItems(); assertEquals(0, items.length); @@ -71,6 +76,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, items.length); } + @Test public void testAlwaysReplace() throws Exception { ModificationItem[] items = tested.getModificationItems(); assertEquals(0, items.length); @@ -78,11 +84,13 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, items.length); } + @Test public void testGetStringAttributeWhenAttributeDoesNotExist() throws Exception { String s = tested.getStringAttribute("does not exist"); assertNull(s); } + @Test public void testGetStringAttributeWhenAttributeDoesExistButWithNoValue() throws Exception { final Attributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("abc")); @@ -96,6 +104,7 @@ public class DirContextAdapterTest extends TestCase { assertNull(s); } + @Test public void testAttributeExistsWhenAttributeDoesExistButWithNoValue() throws Exception { final Attributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("abc")); @@ -109,11 +118,13 @@ public class DirContextAdapterTest extends TestCase { assertEquals(true, result); } + @Test public void testAttributeExistsWhenAttributeDoesNotExist() throws Exception { boolean result = tested.attributeExists("does not exist"); assertEquals(false, result); } + @Test public void testGetStringAttributeWhenAttributeExists() throws Exception { final Attributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("abc", "def")); @@ -127,6 +138,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("def", s); } + @Test public void testGetStringAttributesWhenMultiValueAttributeExists() throws Exception { final Attributes attrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -145,6 +157,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(2, s.length); } + @Test public void testGetStringAttributesExistsWithInvalidType() throws Exception { final Attributes attrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -165,6 +178,7 @@ public class DirContextAdapterTest extends TestCase { } } + @Test public void testGetStringAttributesExistsEmpty() throws Exception { final Attributes attrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -180,11 +194,13 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, s.length); } + @Test public void testGetStringAttributesNotExists() throws Exception { String s[] = tested.getStringAttributes("abc"); assertNull(s); } + @Test public void testGetAttributesSortedStringSetExists() throws Exception { final Attributes attrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -205,6 +221,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("234", it.next()); } + @Test public void testGetAttributesSortedStringSetNotExists() throws Exception { final Attributes attrs = new BasicAttributes(); class TestableDirContextAdapter extends DirContextAdapter { @@ -217,6 +234,7 @@ public class DirContextAdapterTest extends TestCase { assertNull(s); } + @Test public void testAddAttributeValue() throws NamingException { // Perform test tested.addAttributeValue("abc", "123"); @@ -226,6 +244,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("123", (String) attr.get()); } + @Test public void testAddAttributeValueAttributeWithOtherValueExists() throws NamingException { tested.setAttribute(new BasicAttribute("abc", "321")); @@ -239,6 +258,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("123", (String) attr.get(1)); } + @Test public void testAddAttributeValueAttributeWithSameValueExists() throws NamingException { tested.setAttribute(new BasicAttribute("abc", "123")); @@ -252,6 +272,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("123", (String) attr.get(0)); } + @Test public void testAddAttributeValueInUpdateMode() throws NamingException { tested.setUpdateMode(true); tested.addAttributeValue("abc", "123"); @@ -267,6 +288,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("123", attribute.get()); } + @Test public void testAddAttributeValueInUpdateModeAttributeWhenOtherValueExistsInOrigAttrs() throws NamingException { @@ -287,6 +309,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("123", attribute.get()); } + @Test public void testGetModificationItemsOnAddAttributeValueInUpdateModeAttributeWhenSameValueExistsInOrigAttrs() throws NamingException { @@ -303,6 +326,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, modificationItems.length); } + @Test public void testAddAttributeValueInUpdateModeAttributeWithOtherValueExistsInUpdAttrs() throws NamingException { tested.setUpdateMode(true); @@ -322,6 +346,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("123", attribute.get(1)); } + @Test public void testAddAttributeValueInUpdateModeAttributeWithSameValueExistsInUpdAttrs() throws NamingException { tested.setUpdateMode(true); @@ -341,6 +366,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("123", attribute.get()); } + @Test public void testRemoveAttributeValueAttributeDoesntExist() { // Perform test tested.removeAttributeValue("abc", "123"); @@ -349,6 +375,7 @@ public class DirContextAdapterTest extends TestCase { assertNull(attributes.get("abc")); } + @Test public void testRemoveAttributeValueAttributeWithOtherValueExists() throws NamingException { tested.setAttribute(new BasicAttribute("abc", "321")); @@ -363,6 +390,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("321", attr.get()); } + @Test public void testRemoveAttributeValueAttributeWithSameValueExists() { tested.setAttribute(new BasicAttribute("abc", "123")); @@ -374,6 +402,7 @@ public class DirContextAdapterTest extends TestCase { assertNull(attr); } + @Test public void testRemoveAttributeValueAttributeWithOtherAndSameValueExists() throws NamingException { BasicAttribute basicAttribute = new BasicAttribute("abc"); @@ -391,6 +420,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("321", attr.get()); } + @Test public void testRemoveAttributeValueInUpdateMode() { tested.setUpdateMode(true); @@ -403,6 +433,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, modificationItems.length); } + @Test public void testRemoveAttributeValueInUpdateModeSameValueExistsInUpdatedAttrs() { tested.setUpdateMode(true); tested.setAttributeValue("abc", "123"); @@ -416,6 +447,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, modificationItems.length); } + @Test public void testRemoveAttributeValueInUpdateModeOtherValueExistsInUpdatedAttrs() throws NamingException { tested.setUpdateMode(true); @@ -434,6 +466,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("321", modificationAttribute.get()); } + @Test public void testRemoveAttributeValueInUpdateModeOtherAndSameValueExistsInUpdatedAttrs() throws NamingException { tested.setUpdateMode(true); @@ -451,6 +484,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(1, modificationAttribute.size()); } + @Test public void testRemoveAttributeValueInUpdateModeSameValueExistsInOrigAttrs() { tested.setAttribute(new BasicAttribute("abc", "123")); tested.setUpdateMode(true); @@ -467,6 +501,7 @@ public class DirContextAdapterTest extends TestCase { .getModificationOp()); } + @Test public void testRemoveAttributeValueInUpdateModeSameAndOtherValueExistsInOrigAttrs() throws NamingException { BasicAttribute basicAttribute = new BasicAttribute("abc"); @@ -488,6 +523,7 @@ public class DirContextAdapterTest extends TestCase { .getModificationOp()); } + @Test public void testSetStringAttribute() throws Exception { assertFalse(tested.isUpdateMode()); tested.setAttributeValue("abc", "123"); @@ -496,6 +532,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("123", (String) attr.get()); } + @Test public void testSetStringAttributeNull() throws Exception { assertFalse(tested.isUpdateMode()); tested.setAttributeValue("abc", null); @@ -504,6 +541,7 @@ public class DirContextAdapterTest extends TestCase { assertNull(attr); } + @Test public void testAddAttribute() throws Exception { tested.setUpdateMode(true); assertTrue(tested.isUpdateMode()); @@ -532,12 +570,14 @@ public class DirContextAdapterTest extends TestCase { assertEquals("123", (String) attr.get()); } + @Test public void testGetDn() throws Exception { DirContextAdapter tested = new DirContextAdapter(DUMMY_NAME); Name result = tested.getDn(); assertEquals(DUMMY_NAME, result); } + @Test public void testGetDn_BasePath() { DirContextAdapter tested = new DirContextAdapter(null, DUMMY_NAME, BASE_NAME); @@ -545,12 +585,14 @@ public class DirContextAdapterTest extends TestCase { assertEquals(DUMMY_NAME, result); } + @Test public void testGetNameInNamespace() { DirContextAdapter tested = new DirContextAdapter(DUMMY_NAME); String result = tested.getNameInNamespace(); assertEquals(DUMMY_NAME.toString(), result); } + @Test public void testGetNameInNamespace_BasePath() { DirContextAdapter tested = new DirContextAdapter(null, new DistinguishedName("c=SE"), BASE_NAME); @@ -558,6 +600,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(DUMMY_NAME.toString(), result); } + @Test public void testAddMultiAttributes() throws Exception { tested.setUpdateMode(true); assertTrue(tested.isUpdateMode()); @@ -588,6 +631,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("456", (String) attr.get(1)); } + @Test public void testRemoveAttribute() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); fixtureAttrs.put(new BasicAttribute("abc", "123")); @@ -625,6 +669,7 @@ public class DirContextAdapterTest extends TestCase { assertNull(attr); } + @Test public void testRemoveMultiAttribute() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute abc = new BasicAttribute("abc"); @@ -650,6 +695,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, attr.size()); } + @Test public void testChangeAttribute() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); fixtureAttrs.put(new BasicAttribute("abc", "123")); @@ -670,6 +716,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("234", (String) attr.get()); } + @Test public void testNoChangeAttribute() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); fixtureAttrs.put(new BasicAttribute("abc", "123")); @@ -687,6 +734,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, mods.length); } + @Test public void testNoChangeMultiAttribute() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -709,6 +757,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, modNames.length); } + @Test public void testNoChangeMultiAttributeOrderDoesNotMatter() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -730,6 +779,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, modNames.length); } + @Test public void testChangeMultiAttributeOrderDoesMatter() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -759,6 +809,7 @@ public class DirContextAdapterTest extends TestCase { * Test case corresponding to LDAP-96 in Spring Jira. * http://jira.springframework.org/browse/LDAP-96 */ + @Test public void testChangeMultiAttributeOrderDoesMatterLDAP96() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); @@ -787,6 +838,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("Juergen", attr.get(2)); } + @Test public void testChangeMultiAttribute_AddValue() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -812,6 +864,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("klytt", modificationItems[0].getAttribute().get()); } + @Test public void testChangeMultiAttribute_RemoveValue() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -835,6 +888,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("qwe", modificationItems[0].getAttribute().get()); } + @Test public void testChangeMultiAttribute_RemoveTwoValues() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -860,6 +914,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("rty", modificationItems[0].getAttribute().get(1)); } + @Test public void testChangeMultiAttribute_RemoveAllValues() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -882,6 +937,7 @@ public class DirContextAdapterTest extends TestCase { .getModificationOp()); } + @Test public void testChangeMultiAttribute_SameValue() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -902,6 +958,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals(0, modificationItems.length); } + @Test public void testChangeMultiAttribute_AddAndRemoveValue() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -941,6 +998,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("kalle", modifiedAttribute.get(1)); } + @Test public void testAddAttribute_Multivalue() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("abc"); @@ -962,6 +1020,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("def", modificationItems[0].getAttribute().getID()); } + @Test public void testChangeAttributeTwice() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); fixtureAttrs.put(new BasicAttribute("abc", "123")); @@ -994,6 +1053,7 @@ public class DirContextAdapterTest extends TestCase { assertEquals("987", tested.getStringAttribute("abc")); } + @Test public void testAddReplaceAndChangeAttribute() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); fixtureAttrs.put(new BasicAttribute("abc", "123")); @@ -1056,6 +1116,7 @@ public class DirContextAdapterTest extends TestCase { * * @throws NamingException */ + @Test public void testSetAttribute_UpdateMode() throws NamingException { // Set original attribute value Attribute attribute = new BasicAttribute("cn", "john doe"); @@ -1078,11 +1139,13 @@ public class DirContextAdapterTest extends TestCase { assertEquals("nisse hult", modificationAttribute.get()); } + @Test public void testGetStringAttributes_NullValue() { String result = tested.getStringAttribute("someAbsentAttribute"); assertNull(result); } + @Test public void testGetStringAttributes_AttributeExists_NullValue() { tested.setAttribute(new BasicAttribute("someAttribute", null)); String result = tested.getStringAttribute("someAttribute"); @@ -1098,6 +1161,7 @@ public class DirContextAdapterTest extends TestCase { return null; } + @Test public void testModifyMultiValueAttributeModificationOrder() throws NamingException { BasicAttribute attribute = new BasicAttribute("abc"); @@ -1126,6 +1190,7 @@ public class DirContextAdapterTest extends TestCase { /** * Test for LDAP-13. */ + @Test public void testModifyAttributeByteArray() { tested.setAttribute(new BasicAttribute("abc", new byte[] { 1, 2, 3 })); @@ -1142,6 +1207,7 @@ public class DirContextAdapterTest extends TestCase { * Test for LDAP-109, since also DirContextAdapter may get an invalid * CompositeName sent to it. */ + @Test public void testConstructorUsingCompositeNameWithBackslashes() throws Exception { CompositeName compositeName = new CompositeName(); @@ -1151,6 +1217,7 @@ public class DirContextAdapterTest extends TestCase { .toString()); } + @Test public void testStringConstructor() { DirContextAdapter tested = new DirContextAdapter("cn=john doe, ou=company"); assertEquals(new DistinguishedName("cn=john doe, ou=company"), tested.getDn()); diff --git a/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java index 51e1781e..2f1dab2d 100644 --- a/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,25 +15,29 @@ */ package org.springframework.ldap.core; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; /** * Unit tests for {@link DistinguishedNameEditor}. * * @author Mattias Hellborg Arthursson */ -public class DistinguishedNameEditorTest extends TestCase { +public class DistinguishedNameEditorTest { private DistinguishedNameEditor tested; - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { tested = new DistinguishedNameEditor(); } - protected void tearDown() throws Exception { - tested = null; - } - + @Test public void testSetAsText() throws Exception { String expectedDn = "dc=jayway, dc=se"; @@ -50,12 +54,14 @@ public class DistinguishedNameEditorTest extends TestCase { } } + @Test public void testSetAsTextNullValue() throws Exception { tested.setAsText(null); Object result = tested.getValue(); assertNull(result); } + @Test public void testGetAsText() throws Exception { String expectedDn = "dc=jayway,dc=se"; tested.setValue(new DistinguishedName(expectedDn)); @@ -63,6 +69,7 @@ public class DistinguishedNameEditorTest extends TestCase { assertEquals(expectedDn, text); } + @Test public void testGetAsTextNullValue() throws Exception { tested.setValue(null); String text = tested.getAsText(); diff --git a/core/src/test/java/org/springframework/ldap/core/DistinguishedNameTest.java b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameTest.java index 5ede168b..e66eb691 100644 --- a/core/src/test/java/org/springframework/ldap/core/DistinguishedNameTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameTest.java @@ -17,7 +17,7 @@ package org.springframework.ldap.core; import com.gargoylesoftware.base.testing.EqualsTester; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.ldap.BadLdapGrammarException; import javax.naming.CompositeName; @@ -25,26 +25,35 @@ import javax.naming.InvalidNameException; import javax.naming.Name; import java.util.Enumeration; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + /** * Unit tests for the {@link DistinguishedName} class. * * @author Adam Skogman * @author Mattias Hellborg Arthursson */ -public class DistinguishedNameTest extends TestCase { +public class DistinguishedNameTest { + @Test public void testDistinguishedName_CompositeWithSlash() throws Exception { Name testPath = new CompositeName("cn=foo\\/bar"); DistinguishedName path = new DistinguishedName(testPath); assertEquals("cn=foo/bar", path.toString()); } + @Test public void testDistinguishedName_CompositeWithSlashAsString() throws Exception { Name testPath = new CompositeName("cn=foo\\/bar"); DistinguishedName path = new DistinguishedName(testPath.toString()); assertEquals("cn=foo/bar", path.toString()); } + @Test public void testDistinguishedName_Ldap237_NotDestroyedByCompositeName() throws InvalidNameException { DistinguishedName path = new DistinguishedName("ou=Roger \\\"Bunny\\\" Rabbit,dc=somecompany,dc=com"); assertEquals("ou=Roger \\\"Bunny\\\" Rabbit,dc=somecompany,dc=com", path.toString()); @@ -55,11 +64,13 @@ public class DistinguishedNameTest extends TestCase { * * @throws InvalidNameException */ + @Test public void testDistinguishedName_Ldap237_DestroyedByCompositeName() throws InvalidNameException { DistinguishedName path = new DistinguishedName("ou=Roger \\\\\"Bunny\\\\\" Rabbit,dc=somecompany,dc=com"); assertEquals("ou=Roger \\\"Bunny\\\" Rabbit,dc=somecompany,dc=com", path.toString()); } + @Test public void testEmptyPathImmutable() throws Exception { DistinguishedName emptyPath = DistinguishedName.EMPTY_PATH; try { @@ -71,6 +82,7 @@ public class DistinguishedNameTest extends TestCase { } } + @Test public void testDistinguishedName() { String testPath = "cn=foo\\,bar,OU=FOO\\,bar , OU=foo\\;bar;OU=foo\\;bar" @@ -99,6 +111,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals("bar,", path.getLdapRdn(0).getComponent().getValue()); } + @Test public void testRemove() throws InvalidNameException { String testPath = "cn=john.doe, OU=Users,OU=Some Company,OU=G,OU=I,OU=M"; @@ -113,6 +126,7 @@ public class DistinguishedNameTest extends TestCase { /** * Tests parsing and toString. */ + @Test public void testContains() { DistinguishedName migpath = new DistinguishedName("OU=G,OU=I,OU=M"); @@ -133,6 +147,7 @@ public class DistinguishedNameTest extends TestCase { assertFalse("Does not contain MIG", pathE2.contains(migpath)); } + @Test public void testAppend() { DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); DistinguishedName path2 = new DistinguishedName("OU=baz"); @@ -142,6 +157,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals("Append failed", "ou=baz,ou=foo,ou=bar", path1.toString()); } + @Test public void testPrepend() { DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); DistinguishedName path2 = new DistinguishedName("cn=fie, OU=baz"); @@ -150,7 +166,8 @@ public class DistinguishedNameTest extends TestCase { assertEquals("Append failed", "ou=foo,ou=bar,cn=fie,ou=baz", path1.toString()); } - + + @Test public void testEquals() throws Exception { // original object @@ -171,6 +188,7 @@ public class DistinguishedNameTest extends TestCase { new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + @Test public void testClone() { DistinguishedName path1 = new DistinguishedName("cn=john.doe, OU=Users,OU=Some company,C=SE"); @@ -184,6 +202,7 @@ public class DistinguishedNameTest extends TestCase { } + @Test public void testEndsWith_true() { DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); DistinguishedName ending1 = new DistinguishedName("uid=mtah.test"); @@ -195,6 +214,7 @@ public class DistinguishedNameTest extends TestCase { assertTrue(path2.endsWith(ending2)); } + @Test public void testEndsWith_false() { DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); DistinguishedName ending1 = new DistinguishedName("ou=people"); @@ -206,6 +226,7 @@ public class DistinguishedNameTest extends TestCase { assertFalse(path2.endsWith(ending2)); } + @Test public void testGetAll() throws Exception { DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); @@ -224,6 +245,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals("uid=mtah.test", element); } + @Test public void testGet() throws Exception { DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); @@ -232,6 +254,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals("ou=EU", string); } + @Test public void testSize() { DistinguishedName path1 = new DistinguishedName(); assertEquals(0, path1.size()); @@ -240,6 +263,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals(4, path2.size()); } + @Test public void testGetPrefix() { DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); @@ -256,6 +280,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals("ou=EU", prefix.get(1)); } + @Test public void testGetSuffix() { DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); @@ -278,6 +303,7 @@ public class DistinguishedNameTest extends TestCase { } } + @Test public void testStartsWith_true() { DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); DistinguishedName start1 = new DistinguishedName("o=example.com"); @@ -289,6 +315,7 @@ public class DistinguishedNameTest extends TestCase { assertTrue(path2.startsWith(start2)); } + @Test public void testStartsWith_false() { DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); DistinguishedName start1 = new DistinguishedName("ou=people"); @@ -300,6 +327,7 @@ public class DistinguishedNameTest extends TestCase { assertFalse(path2.startsWith(start2)); } + @Test public void testStartsWith_Longer() { DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); @@ -308,6 +336,7 @@ public class DistinguishedNameTest extends TestCase { assertFalse(path1.startsWith(path2)); } + @Test public void testStartsWith_EmptyPath() { DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); @@ -316,16 +345,19 @@ public class DistinguishedNameTest extends TestCase { assertFalse(path1.startsWith(path2)); } + @Test public void testIsEmpty_True() { DistinguishedName path = new DistinguishedName(); assertTrue(path.isEmpty()); } + @Test public void testIsEmpty_False() { DistinguishedName path = new DistinguishedName("o=example.com"); assertFalse(path.isEmpty()); } + @Test public void testAddAll() throws Exception { DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); DistinguishedName path2 = new DistinguishedName("OU=baz"); @@ -335,6 +367,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals("AddAll failed", "ou=baz,ou=foo,ou=bar", path1.toString()); } + @Test public void testAddAll_Index() throws InvalidNameException { DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); DistinguishedName path2 = new DistinguishedName("OU=baz"); @@ -344,6 +377,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals("AddAll failed", "ou=foo,ou=baz,ou=bar", path1.toString()); } + @Test public void testAdd() throws InvalidNameException { DistinguishedName path1 = new DistinguishedName("ou=foo, ou=bar"); path1.add("ou=baz"); @@ -351,6 +385,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals("Add failed", "ou=baz,ou=foo,ou=bar", path1.toString()); } + @Test public void testAdd_Index() throws InvalidNameException { DistinguishedName path1 = new DistinguishedName("ou=foo, ou=bar"); path1.add(1, "ou=baz"); @@ -358,6 +393,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals("Add failed", "ou=foo,ou=baz,ou=bar", path1.toString()); } + @Test public void testToUrl() { DistinguishedName path = new DistinguishedName("dc=jayway, dc=se"); String url = path.toUrl(); @@ -365,12 +401,14 @@ public class DistinguishedNameTest extends TestCase { assertEquals("dc=jayway,dc=se", url); } + @Test public void testMultiValueRdn() throws Exception { DistinguishedName path = new DistinguishedName("firstName=Rod+lastName=Johnson,ou=UK,dc=interface21,dc=com"); assertEquals(4, path.size()); assertEquals("firstname=Rod+lastname=Johnson", path.get(3)); } + @Test public void testCompareTo_Equals() throws Exception { DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); @@ -379,6 +417,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals(0, result); } + @Test public void testCompareTo_Less() throws Exception { DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=DK"); DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); @@ -387,6 +426,7 @@ public class DistinguishedNameTest extends TestCase { assertTrue(result < 0); } + @Test public void testCompareTo_Less_MoreSignificant() throws Exception { DistinguishedName name1 = new DistinguishedName("an=john doe, ou=Some company, c=DK"); DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); @@ -395,6 +435,7 @@ public class DistinguishedNameTest extends TestCase { assertTrue(result < 0); } + @Test public void testCompareTo_Greater() throws Exception { DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=DK"); @@ -403,6 +444,7 @@ public class DistinguishedNameTest extends TestCase { assertTrue(result > 0); } + @Test public void testCompareTo_Longer() throws Exception { DistinguishedName name1 = new DistinguishedName("leaf=someleaf, cn=john doe, ou=Some company, c=SE"); DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); @@ -411,6 +453,7 @@ public class DistinguishedNameTest extends TestCase { assertTrue(result > 0); } + @Test public void testCompareTo_Shorter() throws Exception { DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); DistinguishedName name2 = new DistinguishedName("leaf=someleaf, cn=john doe, ou=Some company, c=SE"); @@ -419,40 +462,33 @@ public class DistinguishedNameTest extends TestCase { assertTrue(result < 0); } + @Test public void testGetLdapRdnForKey() throws Exception { DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); LdapRdn ldapRdn = dn.getLdapRdn("ou"); assertEquals(new LdapRdn("ou=Some company"), ldapRdn); } + @Test(expected = IllegalArgumentException.class) public void testGetLdapRdnForKeyNoMatchingKeyThrowsException() throws Exception { - DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - try { - dn.getLdapRdn("nosuchkey"); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException expected) { - assertTrue(true); - } - } + DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + dn.getLdapRdn("nosuchkey"); + } + @Test public void testGetValue() throws Exception { DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); String value = dn.getValue("ou"); assertEquals("Some company", value); } + @Test(expected = IllegalArgumentException.class) public void testGetValueNoMatchingKeyThrowsException() throws Exception { - DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - try { - dn.getValue("nosuchkey"); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException expected) { - assertTrue(true); - } - } + DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + dn.getValue("nosuchkey"); + } + @Test public void test_longDN() throws InvalidNameException { DistinguishedName name = new DistinguishedName(""); assertNotNull(name); @@ -461,6 +497,7 @@ public class DistinguishedNameTest extends TestCase { /** * Test case to verify correct parsing for issue on forums. */ + @Test public void testParseAtSign() { DistinguishedName name = new DistinguishedName("cn=testname@example.com"); assertNotNull(name); @@ -469,6 +506,7 @@ public class DistinguishedNameTest extends TestCase { /** * Test case to verify correct parsing for issue on forums. */ + @Test public void testParseAtSign2() { DistinguishedName name = new DistinguishedName("cn=te\\+stname@example.com"); assertNotNull(name); @@ -477,24 +515,21 @@ public class DistinguishedNameTest extends TestCase { /** * Test case to verify correct parsing for issue on forums. */ + @Test(expected = BadLdapGrammarException.class) public void testParseInvalidPlus() { - try { - new DistinguishedName("cn=te+stname@example.com"); - fail("BadLdapGrammarException expected"); - } - catch (BadLdapGrammarException expected) { - assertTrue(true); - } - } + new DistinguishedName("cn=te+stname@example.com"); + } /** * Test case to verify correct parsing for issue on forums. */ + @Test public void testParseValidQuotation() { DistinguishedName name = new DistinguishedName("cn=jo\"hn doe"); assertNotNull(name); } + @Test public void testAppendChained() { DistinguishedName tested = new DistinguishedName("dc=mycompany,dc=com"); tested.append("ou", "company1").append("cn", "john doe"); @@ -502,56 +537,37 @@ public class DistinguishedNameTest extends TestCase { assertEquals("cn=john doe,ou=company1,dc=mycompany,dc=com", tested.toString()); } + @Test(expected = UnsupportedOperationException.class) public void testUnmodifiableDistinguishedNameFailsToAddRdn() throws Exception { - DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); - try { - result.add(new LdapRdn("somekey", "somevalue")); - fail("UnsupportedOperationException expected"); - } - catch (UnsupportedOperationException expected) { - assertTrue(true); - } - } + DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); + result.add(new LdapRdn("somekey", "somevalue")); + } + @Test(expected = UnsupportedOperationException.class) public void testUnmodifiableDistinguishedNameFailsToModifyRdn() throws Exception { - DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); - LdapRdn ldapRdn = result.getLdapRdn(0); + DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); + LdapRdn ldapRdn = result.getLdapRdn(0); - try { - ldapRdn.addComponent(new LdapRdnComponent("somekey", "somevalue")); - fail("UnsupportedOperationException expected"); - } - catch (UnsupportedOperationException expected) { - assertTrue(true); - } - } + ldapRdn.addComponent(new LdapRdnComponent("somekey", "somevalue")); + } + @Test(expected = UnsupportedOperationException.class) public void testUnmodifiableDistinguishedNameFailsToModifyRdnComponentKey() throws Exception { - DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); - LdapRdnComponent component = result.getLdapRdn(0).getComponent(); + DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); + LdapRdnComponent component = result.getLdapRdn(0).getComponent(); - try { - component.setKey("somekey"); - fail("UnsupportedOperationException expected"); - } - catch (UnsupportedOperationException expected) { - assertTrue(true); - } - } + component.setKey("somekey"); + } + @Test(expected = UnsupportedOperationException.class) public void testUnmodifiableDistinguishedNameFailsToModifyRdnComponentValue() throws Exception { - DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); - LdapRdnComponent component = result.getLdapRdn(0).getComponent(); + DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); + LdapRdnComponent component = result.getLdapRdn(0).getComponent(); - try { - component.setValue("somevalue"); - fail("UnsupportedOperationException expected"); - } - catch (UnsupportedOperationException expected) { - assertTrue(true); - } - } + component.setValue("somevalue"); + } + @Test public void testUnmodifiableDistinguishedNameEqualsIdenticalMutableOne() throws Exception { DistinguishedName immutable = DistinguishedName.immutableDistinguishedName("cn=john doe"); DistinguishedName mutable = new DistinguishedName("cn=john doe"); @@ -561,6 +577,7 @@ public class DistinguishedNameTest extends TestCase { /** * Test for LDAP-97. */ + @Test public void testDistinguishedNameWithCRParsesProperly() { DistinguishedName name = new DistinguishedName("cn=foo \r bar"); assertNotNull(name); @@ -569,6 +586,7 @@ public class DistinguishedNameTest extends TestCase { /** * Test for http://forum.springsource.org/showthread.php?t=86640. */ + @Test public void testDistinguishedNameWithDotParsesProperly() { DistinguishedName name = new DistinguishedName("cn=first.last,OU=DevTest Users,DC=xyz,DC=com"); assertEquals("cn=first.last,ou=DevTest Users,dc=xyz,dc=com", name.toCompactString()); @@ -580,6 +598,7 @@ public class DistinguishedNameTest extends TestCase { assertEquals("com", dn.getLdapRdn(0).getValue()); } + @Test public void testToStringCompact() { try { DistinguishedName name = new DistinguishedName("cn=john doe, ou=company"); @@ -594,6 +613,7 @@ public class DistinguishedNameTest extends TestCase { } } + @Test public void testKeyCaseFoldNoneShouldEqualOriginalCasedKeys() throws Exception { try { String dnString = "ou=foo,Ou=bar,oU=baz,OU=bim"; @@ -613,6 +633,7 @@ public class DistinguishedNameTest extends TestCase { } } + @Test public void testKeyCaseFoldUpperShouldEqualUpperCasedKeys() throws Exception { try { String dnString = "ou=foo,Ou=bar,oU=baz,OU=bim"; @@ -632,6 +653,7 @@ public class DistinguishedNameTest extends TestCase { } } + @Test public void testKeyCaseFoldLowerShouldEqualLowerCasedKeys() throws Exception { try { String dnString = "ou=foo,Ou=bar,oU=baz,OU=bim"; @@ -651,6 +673,7 @@ public class DistinguishedNameTest extends TestCase { } } + @Test public void testKeyCaseFoldNonsenseShoulddefaultToLowerCasedKeysAndLogWarning() throws Exception { try { String dnString = "ou=foo,Ou=bar,oU=baz,OU=bim"; @@ -670,6 +693,7 @@ public class DistinguishedNameTest extends TestCase { } } + @Test public void testHashSignLdap229() { assertEquals( new DistinguishedName("cn=Foo\\#Bar"), @@ -677,6 +701,7 @@ public class DistinguishedNameTest extends TestCase { ); } + @Test public void testEqualsSignLdap229() { assertEquals( new DistinguishedName("cn=Foo\\=Bar"), @@ -684,6 +709,7 @@ public class DistinguishedNameTest extends TestCase { ); } + @Test public void testSpaceSignLdap229() { assertEquals( new DistinguishedName("cn=Foo\\ Bar"), diff --git a/core/src/test/java/org/springframework/ldap/core/LdapEncoderTest.java b/core/src/test/java/org/springframework/ldap/core/LdapEncoderTest.java index 07f8197b..f6974504 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapEncoderTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapEncoderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,33 +16,26 @@ package org.springframework.ldap.core; +import org.junit.Test; import org.springframework.ldap.BadLdapGrammarException; -import org.springframework.ldap.core.LdapEncoder; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** * Unit test for the LdapEncode class. * * @author Adam Skogman */ -public class LdapEncoderTest extends TestCase { - - /** - * Constructor for LdapEncoderTest. - * - * @param name - */ - public LdapEncoderTest(String name) { - super(name); - } +public class LdapEncoderTest { + @Test public void testFilterEncode() { String correct = "\\2aa\\2ab\\28c\\29d\\2a\\5c"; assertEquals(correct, LdapEncoder.filterEncode("*a*b(c)d*\\")); } + @Test public void testNameEncode() { String res = LdapEncoder.nameEncode("# foo ,+\"\\<>; "); @@ -50,22 +43,18 @@ public class LdapEncoderTest extends TestCase { assertEquals("\\# foo \\,\\+\\\"\\\\\\<\\>\\;\\ ", res); } + @Test public void testNameDecode() { - String res = (String) LdapEncoder + String res = LdapEncoder .nameDecode("\\# foo \\,\\+\\\"\\\\\\<\\>\\;\\ "); assertEquals("# foo ,+\"\\<>; ", res); } + @Test(expected = BadLdapGrammarException.class) public void testNameDecode_slashlast() { - - try { - LdapEncoder.nameDecode("\\"); - fail("Should throw BadLdapGrammarException"); - } catch (BadLdapGrammarException e) { - assertTrue(true); - } + LdapEncoder.nameDecode("\\"); } } diff --git a/core/src/test/java/org/springframework/ldap/core/LdapRdnComponentTest.java b/core/src/test/java/org/springframework/ldap/core/LdapRdnComponentTest.java index 1677267a..37fc84e5 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapRdnComponentTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapRdnComponentTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,25 +15,19 @@ */ package org.springframework.ldap.core; -import org.springframework.ldap.core.LdapRdnComponent; +import org.junit.Test; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * Tests for LdapRdnComponent. * * @author Mattias Hellborg Arthursson */ -public class LdapRdnComponentTest extends TestCase { - - protected void setUp() throws Exception { - super.setUp(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - } +public class LdapRdnComponentTest { + @Test public void testCompareTo_Less() { LdapRdnComponent component1 = new LdapRdnComponent("cn", "john doe"); LdapRdnComponent component2 = new LdapRdnComponent("sn", "doe"); @@ -41,6 +35,7 @@ public class LdapRdnComponentTest extends TestCase { assertTrue(result < 0); } + @Test public void testCompareTo_Greater() { LdapRdnComponent component1 = new LdapRdnComponent("sn", "doe"); LdapRdnComponent component2 = new LdapRdnComponent("cn", "john doe"); @@ -48,6 +43,7 @@ public class LdapRdnComponentTest extends TestCase { assertTrue(result > 0); } + @Test public void testCompareTo_Equal() { LdapRdnComponent component1 = new LdapRdnComponent("cn", "john doe"); LdapRdnComponent component2 = new LdapRdnComponent("cn", "john doe"); diff --git a/core/src/test/java/org/springframework/ldap/core/LdapRdnTest.java b/core/src/test/java/org/springframework/ldap/core/LdapRdnTest.java index 8b7796da..1bd79569 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapRdnTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapRdnTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,21 @@ package org.springframework.ldap.core; -import junit.framework.TestCase; - +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; import org.springframework.ldap.BadLdapGrammarException; -import com.gargoylesoftware.base.testing.EqualsTester; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * Unit test for the LdapRdn class. * * @author Adam Skogman */ -public class LdapRdnTest extends TestCase { +public class LdapRdnTest { + @Test public void testLdapRdn_parse_simple() { LdapRdn rdn = new LdapRdn("foo=bar"); @@ -40,6 +42,7 @@ public class LdapRdnTest extends TestCase { assertEquals("bar", rdn.getValue()); } + @Test public void testLdapRdn_parse_spaces() { LdapRdn rdn = new LdapRdn(" foo = bar "); @@ -49,6 +52,7 @@ public class LdapRdnTest extends TestCase { assertEquals("foo=bar", rdn.getComponent().getLdapEncoded()); } + @Test public void testLdapRdn_parse_escape() { LdapRdn rdn = new LdapRdn("foo=bar\\=fum"); @@ -58,6 +62,7 @@ public class LdapRdnTest extends TestCase { assertEquals("foo=bar\\=fum", rdn.getComponent().getLdapEncoded()); } + @Test public void testLdapRdn_parse_hexEscape() { LdapRdn rdn = new LdapRdn("foo=bar\\0dfum"); @@ -67,18 +72,13 @@ public class LdapRdnTest extends TestCase { assertEquals("foo=bar\\0Dfum", rdn.getComponent().getLdapEncoded()); } + @Test(expected = BadLdapGrammarException.class) public void testLdapRdn_parse_trailingBackslash() { - - try { - new LdapRdn("foo=bar\\"); - fail("Should throw BadLdapGrammarException"); - } catch (BadLdapGrammarException e) { - assertTrue(true); - } + new LdapRdn("foo=bar\\"); } + @Test public void testLdapRdn_parse_spaces_escape() { - LdapRdn rdn = new LdapRdn(" foo = \\ bar\\20 \\ "); assertEquals("foo", rdn.getComponent().getKey()); @@ -86,15 +86,12 @@ public class LdapRdnTest extends TestCase { assertEquals("foo=\\ bar \\ ", rdn.getComponent().getLdapEncoded()); } + @Test(expected = BadLdapGrammarException.class) public void testLdapRdn_parse_tooMuchTrim() { - try { - new LdapRdn("foo=bar\\"); - fail("Should throw BadLdapGrammarException"); - } catch (BadLdapGrammarException e) { - assertTrue(true); - } + new LdapRdn("foo=bar\\"); } + @Test public void testLdapRdn_parse_slash() { LdapRdn rdn = new LdapRdn("ou=Clerical / Secretarial Staff"); @@ -105,15 +102,12 @@ public class LdapRdnTest extends TestCase { .getLdapEncoded()); } + @Test(expected = BadLdapGrammarException.class) public void testLdapRdn_parse_quoteInKey() { - try { - new LdapRdn("\"umanroleid=2583"); - fail("Should throw BadLdapGrammarException"); - } catch (BadLdapGrammarException e) { - assertTrue(true); - } + new LdapRdn("\"umanroleid=2583"); } + @Test public void testLdapRdn_KeyValue_simple() { LdapRdn rdn = new LdapRdn("foo", "bar"); @@ -122,6 +116,7 @@ public class LdapRdnTest extends TestCase { assertEquals("foo=bar", rdn.getComponent().getLdapEncoded()); } + @Test public void testLdapRdn_KeyValue_valueNeedsEscape() { LdapRdn rdn = new LdapRdn("foo", "bar\\"); @@ -130,16 +125,19 @@ public class LdapRdnTest extends TestCase { assertEquals("foo=bar\\\\", rdn.getComponent().getLdapEncoded()); } + @Test public void testEncodeUrl() { LdapRdn rdn = new LdapRdn("o = example.com "); assertEquals("o=example.com", rdn.encodeUrl()); } + @Test public void testEncodeUrl_SpacesInValue() { LdapRdn rdn = new LdapRdn("o = my organization "); assertEquals("o=my%20organization", rdn.encodeUrl()); } + @Test public void testLdapRdn_Parse_MultipleComponents() { LdapRdn rdn = new LdapRdn("cn=John Doe+sn=Doe"); assertEquals("cn=John Doe", rdn.getComponent(0).encodeLdap()); @@ -151,26 +149,19 @@ public class LdapRdnTest extends TestCase { assertEquals("Doe", rdn.getValue("sn")); } + @Test(expected = IllegalArgumentException.class) public void testGetValueNoKeyWithCorrectValue() { LdapRdn tested = new LdapRdn("cn=john doe"); - try { - tested.getValue("sn"); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertTrue(true); - } + tested.getValue("sn"); } + @Test(expected = IllegalArgumentException.class) public void testGetValueNoComponents() { LdapRdn tested = new LdapRdn(); - try { - tested.getValue("sn"); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertTrue(true); - } + tested.getValue("sn"); } + @Test public void testEquals() throws Exception { // original object final Object originalObject = new LdapRdn("cn", "john.doe"); @@ -190,6 +181,7 @@ public class LdapRdnTest extends TestCase { subclassObject); } + @Test public void testCompareTo_Equals() throws Exception { LdapRdn rdn1 = new LdapRdn("cn=john doe"); LdapRdn rdn2 = new LdapRdn("cn=john doe"); @@ -198,6 +190,7 @@ public class LdapRdnTest extends TestCase { assertEquals(0, result); } + @Test public void testCompareTo_EqualsComplex() throws Exception { LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe"); @@ -206,6 +199,7 @@ public class LdapRdnTest extends TestCase { assertEquals(0, result); } + @Test public void testCompareTo_Less() { LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); LdapRdn rdn2 = new LdapRdn("cn=john doe+tn=doe"); @@ -214,6 +208,7 @@ public class LdapRdnTest extends TestCase { assertTrue(result < 0); } + @Test public void testCompareTo_Greater() { LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); LdapRdn rdn2 = new LdapRdn("cn=john doe+an=doe"); @@ -222,6 +217,7 @@ public class LdapRdnTest extends TestCase { assertTrue(result > 0); } + @Test public void testCompareTo_Shorter() { LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe+description=tjo"); @@ -230,6 +226,7 @@ public class LdapRdnTest extends TestCase { assertTrue(result < 0); } + @Test public void testCompareTo_Longer() { LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe+description=tjo"); LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe"); diff --git a/core/src/test/java/org/springframework/ldap/core/LdapTemplateListTest.java b/core/src/test/java/org/springframework/ldap/core/LdapTemplateListTest.java index 9cfafdd0..76632c83 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateListTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateListTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,10 @@ package org.springframework.ldap.core; -import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.LimitExceededException; +import org.springframework.ldap.PartialResultException; import javax.naming.Binding; import javax.naming.Name; @@ -25,170 +28,103 @@ import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.ldap.LdapContext; +import java.util.List; -import junit.framework.TestCase; - -import org.easymock.MockControl; -import org.springframework.ldap.LimitExceededException; -import org.springframework.ldap.PartialResultException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * Unit tests for the list operations in {@link LdapTemplate}. * * @author Ulrik Sandberg */ -public class LdapTemplateListTest extends TestCase { +public class LdapTemplateListTest { private static final String NAME = "o=example.com"; private static final String CLASS = "com.example.SomeClass"; - private MockControl contextSourceControl; - private ContextSource contextSourceMock; - private MockControl dirContextControl; - private DirContext dirContextMock; - private MockControl namingEnumerationControl; - private NamingEnumeration namingEnumerationMock; - private MockControl nameControl; - private Name nameMock; - private MockControl handlerControl; - private NameClassPairCallbackHandler handlerMock; - private MockControl contextMapperControl; - private ContextMapper contextMapperMock; private LdapTemplate tested; - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() throws Exception { // Setup ContextSource mock - contextSourceControl = MockControl.createControl(ContextSource.class); - contextSourceMock = (ContextSource) contextSourceControl.getMock(); + contextSourceMock = mock(ContextSource.class); // Setup LdapContext mock - dirContextControl = MockControl.createControl(LdapContext.class); - dirContextMock = (LdapContext) dirContextControl.getMock(); + dirContextMock = mock(LdapContext.class); // Setup NamingEnumeration mock - namingEnumerationControl = MockControl - .createControl(NamingEnumeration.class); - namingEnumerationMock = (NamingEnumeration) namingEnumerationControl - .getMock(); + namingEnumerationMock = mock(NamingEnumeration.class); // Setup Name mock - nameControl = MockControl.createControl(Name.class); - nameMock = (Name) nameControl.getMock(); + nameMock = mock(Name.class); // Setup Handler mock - handlerControl = MockControl - .createControl(NameClassPairCallbackHandler.class); - handlerMock = (NameClassPairCallbackHandler) handlerControl.getMock(); + handlerMock = mock(NameClassPairCallbackHandler.class); - contextMapperControl = MockControl.createControl(ContextMapper.class); - contextMapperMock = (ContextMapper) contextMapperControl.getMock(); + contextMapperMock = mock(ContextMapper.class); tested = new LdapTemplate(contextSourceMock); } - protected void tearDown() throws Exception { - super.tearDown(); - - contextSourceControl = null; - contextSourceMock = null; - - dirContextControl = null; - dirContextMock = null; - - namingEnumerationControl = null; - namingEnumerationMock = null; - - nameControl = null; - nameMock = null; - - handlerControl = null; - handlerMock = null; - - contextMapperControl = null; - contextMapperMock = null; - } - - protected void replay() { - contextSourceControl.replay(); - dirContextControl.replay(); - namingEnumerationControl.replay(); - nameControl.replay(); - handlerControl.replay(); - contextMapperControl.replay(); - } - - protected void verify() { - contextSourceControl.verify(); - dirContextControl.verify(); - namingEnumerationControl.verify(); - nameControl.verify(); - handlerControl.verify(); - contextMapperControl.verify(); - } - private void expectGetReadOnlyContext() { - contextSourceControl.expectAndReturn(contextSourceMock - .getReadOnlyContext(), dirContextMock); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); } private void setupStringListAndNamingEnumeration(NameClassPair listResult) throws NamingException { - dirContextControl.expectAndReturn(dirContextMock.list(NAME), - namingEnumerationMock); + when(dirContextMock.list(NAME)).thenReturn(namingEnumerationMock); setupNamingEnumeration(listResult); } private void setupListAndNamingEnumeration(NameClassPair listResult) throws NamingException { - dirContextControl.expectAndReturn(dirContextMock.list(nameMock), - namingEnumerationMock); + when(dirContextMock.list(nameMock)).thenReturn(namingEnumerationMock); setupNamingEnumeration(listResult); } private void setupStringListBindingsAndNamingEnumeration( NameClassPair listResult) throws NamingException { - dirContextControl.expectAndReturn(dirContextMock.listBindings(NAME), - namingEnumerationMock); + when(dirContextMock.listBindings(NAME)).thenReturn(namingEnumerationMock); setupNamingEnumeration(listResult); } private void setupListBindingsAndNamingEnumeration(NameClassPair listResult) throws NamingException { - dirContextControl.expectAndReturn( - dirContextMock.listBindings(nameMock), namingEnumerationMock); + when(dirContextMock.listBindings(nameMock)).thenReturn(namingEnumerationMock); setupNamingEnumeration(listResult); } private void setupNamingEnumeration(NameClassPair listResult) throws NamingException { - namingEnumerationControl.expectAndReturn(namingEnumerationMock - .hasMore(), true); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.next(), - listResult); - namingEnumerationControl.expectAndReturn(namingEnumerationMock - .hasMore(), false); - namingEnumerationMock.close(); + when(namingEnumerationMock.hasMore()).thenReturn(true, false); + when(namingEnumerationMock.next()).thenReturn(listResult); } + @Test public void testList_Name() throws NamingException { expectGetReadOnlyContext(); @@ -196,19 +132,17 @@ public class LdapTemplateListTest extends TestCase { setupListAndNamingEnumeration(listResult); - dirContextMock.close(); - - replay(); - List list = tested.list(nameMock); - verify(); + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); assertNotNull(list); assertEquals(1, list.size()); assertSame(NAME, list.get(0)); } + @Test public void testList_String() throws NamingException { expectGetReadOnlyContext(); @@ -216,19 +150,17 @@ public class LdapTemplateListTest extends TestCase { setupStringListAndNamingEnumeration(listResult); - dirContextMock.close(); - - replay(); - List list = tested.list(NAME); - verify(); + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); assertNotNull(list); assertEquals(1, list.size()); assertSame(NAME, list.get(0)); } + @Test public void testList_Name_CallbackHandler() throws NamingException { expectGetReadOnlyContext(); @@ -236,17 +168,14 @@ public class LdapTemplateListTest extends TestCase { setupListAndNamingEnumeration(listResult); - handlerMock.handleNameClassPair(listResult); - - dirContextMock.close(); - - replay(); - tested.list(nameMock, handlerMock); - verify(); + verify(handlerMock).handleNameClassPair(listResult); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); } + @Test public void testList_String_CallbackHandler() throws NamingException { expectGetReadOnlyContext(); @@ -254,26 +183,19 @@ public class LdapTemplateListTest extends TestCase { setupStringListAndNamingEnumeration(listResult); - handlerMock.handleNameClassPair(listResult); - - dirContextMock.close(); - - replay(); - tested.list("o=example.com", handlerMock); - verify(); + verify(handlerMock).handleNameClassPair(listResult); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); } + @Test public void testList_PartialResultException() throws NamingException { expectGetReadOnlyContext(); javax.naming.PartialResultException pre = new javax.naming.PartialResultException(); - dirContextControl.expectAndThrow(dirContextMock.list(NAME), pre); - - dirContextMock.close(); - - replay(); + when(dirContextMock.list(NAME)).thenThrow(pre); try { tested.list(NAME); @@ -282,38 +204,32 @@ public class LdapTemplateListTest extends TestCase { assertTrue(true); } - verify(); + verify(dirContextMock).close(); } + @Test public void testList_PartialResultException_Ignore() throws NamingException { expectGetReadOnlyContext(); javax.naming.PartialResultException pre = new javax.naming.PartialResultException(); - dirContextControl.expectAndThrow(dirContextMock.list(NAME), pre); - - dirContextMock.close(); + when(dirContextMock.list(NAME)).thenThrow(pre); tested.setIgnorePartialResultException(true); - replay(); - List list = tested.list(NAME); - verify(); + verify(dirContextMock).close(); assertNotNull(list); assertEquals(0, list.size()); } + @Test public void testList_NamingException() throws NamingException { expectGetReadOnlyContext(); javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - dirContextControl.expectAndThrow(dirContextMock.list(NAME), ne); - - dirContextMock.close(); - - replay(); + when(dirContextMock.list(NAME)).thenThrow(ne); try { tested.list(NAME); @@ -322,11 +238,12 @@ public class LdapTemplateListTest extends TestCase { assertTrue(true); } - verify(); + verify(dirContextMock).close(); } // Tests for listBindings + @Test public void testListBindings_String() throws NamingException { expectGetReadOnlyContext(); @@ -334,19 +251,17 @@ public class LdapTemplateListTest extends TestCase { setupStringListBindingsAndNamingEnumeration(listResult); - dirContextMock.close(); - - replay(); - List list = tested.listBindings(NAME); - verify(); + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); assertNotNull(list); assertEquals(1, list.size()); assertSame(NAME, list.get(0)); } + @Test public void testListBindings_Name() throws NamingException { expectGetReadOnlyContext(); @@ -354,19 +269,17 @@ public class LdapTemplateListTest extends TestCase { setupListBindingsAndNamingEnumeration(listResult); - dirContextMock.close(); - - replay(); - List list = tested.listBindings(nameMock); - verify(); + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); assertNotNull(list); assertEquals(1, list.size()); assertSame(NAME, list.get(0)); } + @Test public void testListBindings_ContextMapper() throws NamingException { expectGetReadOnlyContext(); @@ -376,22 +289,19 @@ public class LdapTemplateListTest extends TestCase { setupStringListBindingsAndNamingEnumeration(listResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock - .mapFromContext(expectedObject), expectedResult); - - dirContextMock.close(); - - replay(); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); List list = tested.listBindings(NAME, contextMapperMock); - verify(); + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testListBindings_Name_ContextMapper() throws NamingException { expectGetReadOnlyContext(); @@ -401,16 +311,12 @@ public class LdapTemplateListTest extends TestCase { setupListBindingsAndNamingEnumeration(listResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock - .mapFromContext(expectedObject), expectedResult); - - dirContextMock.close(); - - replay(); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); List list = tested.listBindings(nameMock, contextMapperMock); - verify(); + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); assertNotNull(list); assertEquals(1, list.size()); diff --git a/core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java b/core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java index fbeed7d8..21574759 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,155 +16,96 @@ package org.springframework.ldap.core; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.NameNotFoundException; + import javax.naming.Name; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.ldap.LdapContext; -import junit.framework.TestCase; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; -import org.easymock.MockControl; -import org.springframework.ldap.NameNotFoundException; - -public class LdapTemplateLookupTest extends TestCase { +public class LdapTemplateLookupTest { private static final String DEFAULT_BASE_STRING = "o=example.com"; - private MockControl contextSourceControl; - private ContextSource contextSourceMock; - private MockControl dirContextControl; - private DirContext dirContextMock; - private MockControl attributesMapperControl; - private AttributesMapper attributesMapperMock; - private MockControl nameControl; - private Name nameMock; - private MockControl contextMapperControl; - private ContextMapper contextMapperMock; private LdapTemplate tested; - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() throws Exception { // Setup ContextSource mock - contextSourceControl = MockControl.createControl(ContextSource.class); - contextSourceMock = (ContextSource) contextSourceControl.getMock(); + contextSourceMock = mock(ContextSource.class); // Setup LdapContext mock - dirContextControl = MockControl.createControl(LdapContext.class); - dirContextMock = (LdapContext) dirContextControl.getMock(); + dirContextMock = mock(LdapContext.class); // Setup Name mock - nameControl = MockControl.createControl(Name.class); - nameMock = (Name) nameControl.getMock(); + nameMock = mock(Name.class); - contextMapperControl = MockControl.createControl(ContextMapper.class); - contextMapperMock = (ContextMapper) contextMapperControl.getMock(); + contextMapperMock = mock(ContextMapper.class); - attributesMapperControl = MockControl - .createControl(AttributesMapper.class); - attributesMapperMock = (AttributesMapper) attributesMapperControl - .getMock(); + attributesMapperMock = mock(AttributesMapper.class); tested = new LdapTemplate(contextSourceMock); } - protected void tearDown() throws Exception { - super.tearDown(); - - contextSourceControl = null; - contextSourceMock = null; - - dirContextControl = null; - dirContextMock = null; - - nameControl = null; - nameMock = null; - - contextMapperControl = null; - contextMapperMock = null; - - attributesMapperControl = null; - attributesMapperMock = null; - } - - protected void replay() { - contextSourceControl.replay(); - dirContextControl.replay(); - nameControl.replay(); - contextMapperControl.replay(); - attributesMapperControl.replay(); - } - - protected void verify() { - contextSourceControl.verify(); - dirContextControl.verify(); - nameControl.verify(); - contextMapperControl.verify(); - attributesMapperControl.verify(); - } - private void expectGetReadOnlyContext() { - contextSourceControl.expectAndReturn(contextSourceMock - .getReadOnlyContext(), dirContextMock); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); } // Tests for lookup(name) + @Test public void testLookup() throws Exception { expectGetReadOnlyContext(); Object expected = new Object(); - dirContextControl.expectAndReturn(dirContextMock.lookup(nameMock), - expected); - - dirContextMock.close(); - - replay(); + when(dirContextMock.lookup(nameMock)).thenReturn(expected); Object actual = tested.lookup(nameMock); - verify(); + verify(dirContextMock).close(); assertSame(expected, actual); } + @Test public void testLookup_String() throws Exception { expectGetReadOnlyContext(); Object expected = new Object(); - dirContextControl.expectAndReturn(dirContextMock - .lookup(DEFAULT_BASE_STRING), expected); - - dirContextMock.close(); - - replay(); + when(dirContextMock.lookup(DEFAULT_BASE_STRING)).thenReturn(expected); Object actual = tested.lookup(DEFAULT_BASE_STRING); - verify(); + verify(dirContextMock).close(); assertSame(expected, actual); } + @Test public void testLookup_NamingException() throws Exception { expectGetReadOnlyContext(); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - dirContextControl.expectAndThrow(dirContextMock.lookup(nameMock), ne); - - dirContextMock.close(); - - replay(); + when(dirContextMock.lookup(nameMock)).thenThrow(ne); try { tested.lookup(nameMock); @@ -173,63 +114,52 @@ public class LdapTemplateLookupTest extends TestCase { assertTrue(true); } - verify(); + verify(dirContextMock).close(); } // Tests for lookup(name, AttributesMapper) + @Test public void testLookup_AttributesMapper() throws Exception { expectGetReadOnlyContext(); BasicAttributes expectedAttributes = new BasicAttributes(); - dirContextControl.expectAndReturn(dirContextMock - .getAttributes(nameMock), expectedAttributes); - dirContextMock.close(); + when(dirContextMock.getAttributes(nameMock)).thenReturn(expectedAttributes); Object expected = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock - .mapFromAttributes(expectedAttributes), expected); - - replay(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); Object actual = tested.lookup(nameMock, attributesMapperMock); - verify(); + verify(dirContextMock).close(); assertSame(expected, actual); } + @Test public void testLookup_String_AttributesMapper() throws Exception { expectGetReadOnlyContext(); BasicAttributes expectedAttributes = new BasicAttributes(); - dirContextControl.expectAndReturn(dirContextMock - .getAttributes(DEFAULT_BASE_STRING), expectedAttributes); - dirContextMock.close(); + when(dirContextMock.getAttributes(DEFAULT_BASE_STRING)).thenReturn(expectedAttributes); Object expected = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock - .mapFromAttributes(expectedAttributes), expected); - - replay(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); Object actual = tested .lookup(DEFAULT_BASE_STRING, attributesMapperMock); - verify(); + verify(dirContextMock).close(); assertSame(expected, actual); } + @Test public void testLookup_AttributesMapper_NamingException() throws Exception { expectGetReadOnlyContext(); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - dirContextControl.expectAndThrow( - dirContextMock.getAttributes(nameMock), ne); - dirContextMock.close(); - - replay(); + when(dirContextMock.getAttributes(nameMock)).thenThrow(ne); try { tested.lookup(nameMock, attributesMapperMock); @@ -238,64 +168,51 @@ public class LdapTemplateLookupTest extends TestCase { assertTrue(true); } - verify(); + verify(dirContextMock).close(); } // Tests for lookup(name, ContextMapper) + @Test public void testLookup_ContextMapper() throws Exception { expectGetReadOnlyContext(); Object transformed = new Object(); Object expected = new Object(); - dirContextControl.expectAndReturn(dirContextMock.lookup(nameMock), - expected); + when(dirContextMock.lookup(nameMock)).thenReturn(expected); - dirContextMock.close(); - - contextMapperControl.expectAndReturn(contextMapperMock - .mapFromContext(expected), transformed); - - replay(); + when(contextMapperMock.mapFromContext(expected)).thenReturn(transformed); Object actual = tested.lookup(nameMock, contextMapperMock); - verify(); + verify(dirContextMock).close(); assertSame(transformed, actual); } + @Test public void testLookup_String_ContextMapper() throws Exception { expectGetReadOnlyContext(); Object transformed = new Object(); Object expected = new Object(); - dirContextControl.expectAndReturn(dirContextMock - .lookup(DEFAULT_BASE_STRING), expected); + when(dirContextMock.lookup(DEFAULT_BASE_STRING)).thenReturn(expected); - dirContextMock.close(); - - contextMapperControl.expectAndReturn(contextMapperMock - .mapFromContext(expected), transformed); - - replay(); + when(contextMapperMock.mapFromContext(expected)).thenReturn(transformed); Object actual = tested.lookup(DEFAULT_BASE_STRING, contextMapperMock); - verify(); + verify(dirContextMock).close(); assertSame(transformed, actual); } + @Test public void testLookup_ContextMapper_NamingException() throws Exception { expectGetReadOnlyContext(); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - dirContextControl.expectAndThrow(dirContextMock.lookup(nameMock), ne); - - dirContextMock.close(); - - replay(); + when(dirContextMock.lookup(nameMock)).thenThrow(ne); try { tested.lookup(nameMock, contextMapperMock); @@ -304,11 +221,12 @@ public class LdapTemplateLookupTest extends TestCase { assertTrue(true); } - verify(); + verify(dirContextMock).close(); } // Tests for lookup(name, attributes, AttributesMapper) + @Test public void testLookup_ReturnAttributes_AttributesMapper() throws Exception { expectGetReadOnlyContext(); @@ -317,24 +235,20 @@ public class LdapTemplateLookupTest extends TestCase { BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("cn", "Some Name"); - dirContextControl.expectAndReturn(dirContextMock.getAttributes( - nameMock, attributeNames), expectedAttributes); - dirContextMock.close(); + when(dirContextMock.getAttributes(nameMock, attributeNames)).thenReturn(expectedAttributes); Object expected = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock - .mapFromAttributes(expectedAttributes), expected); - - replay(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); Object actual = tested.lookup(nameMock, attributeNames, attributesMapperMock); - verify(); + verify(dirContextMock).close(); assertSame(expected, actual); } + @Test public void testLookup_String_ReturnAttributes_AttributesMapper() throws Exception { expectGetReadOnlyContext(); @@ -344,26 +258,22 @@ public class LdapTemplateLookupTest extends TestCase { BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("cn", "Some Name"); - dirContextControl.expectAndReturn(dirContextMock.getAttributes( - DEFAULT_BASE_STRING, attributeNames), expectedAttributes); - dirContextMock.close(); + when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes); Object expected = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock - .mapFromAttributes(expectedAttributes), expected); - - replay(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames, attributesMapperMock); - verify(); + verify(dirContextMock).close(); assertSame(expected, actual); } // Tests for lookup(name, attributes, ContextMapper) + @Test public void testLookup_ReturnAttributes_ContextMapper() throws Exception { expectGetReadOnlyContext(); @@ -376,23 +286,19 @@ public class LdapTemplateLookupTest extends TestCase { DirContextAdapter adapter = new DirContextAdapter(expectedAttributes, name); - dirContextControl.expectAndReturn(dirContextMock.getAttributes(name, - attributeNames), expectedAttributes); - dirContextMock.close(); + when(dirContextMock.getAttributes(name,attributeNames)).thenReturn(expectedAttributes); Object transformed = new Object(); - contextMapperControl.expectAndReturn(contextMapperMock - .mapFromContext(adapter), transformed); - - replay(); + when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed); Object actual = tested.lookup(name, attributeNames, contextMapperMock); - verify(); + verify(dirContextMock).close(); assertSame(transformed, actual); } + @Test public void testLookup_String_ReturnAttributes_ContextMapper() throws Exception { expectGetReadOnlyContext(); @@ -402,24 +308,19 @@ public class LdapTemplateLookupTest extends TestCase { BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("cn", "Some Name"); - dirContextControl.expectAndReturn(dirContextMock.getAttributes( - DEFAULT_BASE_STRING, attributeNames), expectedAttributes); - dirContextMock.close(); + when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes); DistinguishedName name = new DistinguishedName(DEFAULT_BASE_STRING); DirContextAdapter adapter = new DirContextAdapter(expectedAttributes, name); Object transformed = new Object(); - contextMapperControl.expectAndReturn(contextMapperMock - .mapFromContext(adapter), transformed); - - replay(); + when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed); Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames, contextMapperMock); - verify(); + verify(dirContextMock).close(); assertSame(transformed, actual); } diff --git a/core/src/test/java/org/springframework/ldap/core/LdapTemplateRenameTest.java b/core/src/test/java/org/springframework/ldap/core/LdapTemplateRenameTest.java index 9159f1d6..913d749b 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateRenameTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateRenameTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,115 +16,76 @@ package org.springframework.ldap.core; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.NameAlreadyBoundException; +import org.springframework.ldap.UncategorizedLdapException; + import javax.naming.Name; import javax.naming.directory.DirContext; import javax.naming.ldap.LdapContext; -import junit.framework.TestCase; - -import org.easymock.MockControl; -import org.springframework.ldap.NameAlreadyBoundException; -import org.springframework.ldap.UncategorizedLdapException; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * Unit tests for the rename operations in the LdapTemplate class. * * @author Ulrik Sandberg */ -public class LdapTemplateRenameTest extends TestCase { - - private MockControl contextSourceControl; +public class LdapTemplateRenameTest { private ContextSource contextSourceMock; - private MockControl dirContextControl; - private DirContext dirContextMock; - private MockControl oldNameControl; - private Name oldNameMock; - private MockControl newNameControl; - private Name newNameMock; private LdapTemplate tested; - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() throws Exception { // Setup ContextSource mock - contextSourceControl = MockControl.createControl(ContextSource.class); - contextSourceMock = (ContextSource) contextSourceControl.getMock(); + contextSourceMock = mock(ContextSource.class); // Setup LdapContext mock - dirContextControl = MockControl.createControl(LdapContext.class); - dirContextMock = (LdapContext) dirContextControl.getMock(); + dirContextMock = mock(LdapContext.class); // Setup Name mock for old name - oldNameControl = MockControl.createControl(Name.class); - oldNameMock = (Name) oldNameControl.getMock(); + oldNameMock = mock(Name.class); // Setup Name mock for new name - newNameControl = MockControl.createControl(Name.class); - newNameMock = (Name) newNameControl.getMock(); + newNameMock = mock(Name.class); tested = new LdapTemplate(contextSourceMock); } - protected void tearDown() throws Exception { - super.tearDown(); - - contextSourceControl = null; - contextSourceMock = null; - - dirContextControl = null; - dirContextMock = null; - - oldNameControl = null; - newNameMock = null; - } - - protected void replay() { - contextSourceControl.replay(); - dirContextControl.replay(); - oldNameControl.replay(); - } - - protected void verify() { - contextSourceControl.verify(); - dirContextControl.verify(); - oldNameControl.verify(); - } - private void expectGetReadWriteContext() { - contextSourceControl.expectAndReturn(contextSourceMock - .getReadWriteContext(), dirContextMock); + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); } + @Test public void testRename() throws Exception { expectGetReadWriteContext(); - dirContextMock.rename(oldNameMock, newNameMock); - dirContextMock.close(); - - replay(); - tested.rename(oldNameMock, newNameMock); - verify(); + verify(dirContextMock).rename(oldNameMock, newNameMock); + verify(dirContextMock).close(); } + @Test public void testRename_NameAlreadyBoundException() throws Exception { expectGetReadWriteContext(); - dirContextMock.rename(oldNameMock, newNameMock); javax.naming.NameAlreadyBoundException ne = new javax.naming.NameAlreadyBoundException(); - dirContextControl.setThrowable(ne); - dirContextMock.close(); - - replay(); + doThrow(ne).when(dirContextMock).rename(oldNameMock, newNameMock); try { tested.rename(oldNameMock, newNameMock); @@ -133,18 +94,16 @@ public class LdapTemplateRenameTest extends TestCase { assertTrue(true); } - verify(); + verify(dirContextMock).close(); } + @Test public void testRename_NamingException() throws Exception { expectGetReadWriteContext(); - dirContextMock.rename(oldNameMock, newNameMock); javax.naming.NamingException ne = new javax.naming.NamingException(); - dirContextControl.setThrowable(ne); - dirContextMock.close(); - replay(); + doThrow(ne).when(dirContextMock).rename(oldNameMock, newNameMock); try { tested.rename(oldNameMock, newNameMock); @@ -153,19 +112,16 @@ public class LdapTemplateRenameTest extends TestCase { assertTrue(true); } - verify(); + verify(dirContextMock).close(); } + @Test public void testRename_String() throws Exception { expectGetReadWriteContext(); - dirContextMock.rename("o=example.com", "o=somethingelse.com"); - dirContextMock.close(); - - replay(); - tested.rename("o=example.com", "o=somethingelse.com"); - verify(); + verify(dirContextMock).rename("o=example.com", "o=somethingelse.com"); + verify(dirContextMock).close(); } } diff --git a/core/src/test/java/org/springframework/ldap/core/LdapTemplateTest.java b/core/src/test/java/org/springframework/ldap/core/LdapTemplateTest.java index 6bf21b2e..c70fd87e 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,19 @@ package org.springframework.ldap.core; -import java.util.List; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.Before; +import org.junit.Test; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.ldap.LimitExceededException; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.PartialResultException; +import org.springframework.ldap.UncategorizedLdapException; import javax.naming.Binding; +import javax.naming.CompositeName; import javax.naming.Name; import javax.naming.NamingEnumeration; import javax.naming.directory.BasicAttributes; @@ -27,17 +37,21 @@ import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.LdapContext; +import java.util.List; -import junit.framework.TestCase; - -import org.easymock.AbstractMatcher; -import org.easymock.MockControl; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.ldap.LimitExceededException; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.PartialResultException; -import org.springframework.ldap.UncategorizedLdapException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * Unit tests for the LdapTemplate class. @@ -45,191 +59,84 @@ import org.springframework.ldap.UncategorizedLdapException; * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ -public class LdapTemplateTest extends TestCase { +public class LdapTemplateTest { private static final String DEFAULT_BASE_STRING = "o=example.com"; - private MockControl contextSourceControl; - private ContextSource contextSourceMock; - private MockControl dirContextControl; - private DirContext dirContextMock; - private MockControl attributesMapperControl; - private AttributesMapper attributesMapperMock; - private MockControl namingEnumerationControl; - private NamingEnumeration namingEnumerationMock; - private MockControl nameControl; - private Name nameMock; - private MockControl handlerControl; - private NameClassPairCallbackHandler handlerMock; - private MockControl contextMapperControl; - private ContextMapper contextMapperMock; - private MockControl contextExecutorControl; - private ContextExecutor contextExecutorMock; - private MockControl searchExecutorControl; - private SearchExecutor searchExecutorMock; private LdapTemplate tested; - private MockControl dirContextProcessorControl; - private DirContextProcessor dirContextProcessorMock; - private MockControl dirContextOperationsConrol; - private DirContextOperations dirContextOperationsMock; - private MockControl authenticatedContextControl; - private DirContext authenticatedContextMock; - private MockControl entryContextCallbackControl; - private AuthenticatedLdapEntryContextCallback entryContextCallbackMock; - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { // Setup ContextSource mock - contextSourceControl = MockControl.createControl(ContextSource.class); - contextSourceMock = (ContextSource) contextSourceControl.getMock(); + contextSourceMock = mock(ContextSource.class); // Setup LdapContext mock - dirContextControl = MockControl.createControl(LdapContext.class); - dirContextMock = (LdapContext) dirContextControl.getMock(); + dirContextMock = mock(LdapContext.class); // Setup NamingEnumeration mock - namingEnumerationControl = MockControl.createControl(NamingEnumeration.class); - namingEnumerationMock = (NamingEnumeration) namingEnumerationControl.getMock(); + namingEnumerationMock = mock(NamingEnumeration.class); // Setup Name mock - nameControl = MockControl.createControl(Name.class); - nameMock = (Name) nameControl.getMock(); + nameMock = mock(Name.class); // Setup Handler mock - handlerControl = MockControl.createControl(NameClassPairCallbackHandler.class); - handlerMock = (NameClassPairCallbackHandler) handlerControl.getMock(); + handlerMock = mock(NameClassPairCallbackHandler.class); - contextMapperControl = MockControl.createControl(ContextMapper.class); - contextMapperMock = (ContextMapper) contextMapperControl.getMock(); + contextMapperMock = mock(ContextMapper.class); - attributesMapperControl = MockControl.createControl(AttributesMapper.class); - attributesMapperMock = (AttributesMapper) attributesMapperControl.getMock(); + attributesMapperMock = mock(AttributesMapper.class); - contextExecutorControl = MockControl.createControl(ContextExecutor.class); - contextExecutorMock = (ContextExecutor) contextExecutorControl.getMock(); + contextExecutorMock = mock(ContextExecutor.class); - searchExecutorControl = MockControl.createControl(SearchExecutor.class); - searchExecutorMock = (SearchExecutor) searchExecutorControl.getMock(); + searchExecutorMock = mock(SearchExecutor.class); - dirContextProcessorControl = MockControl.createControl(DirContextProcessor.class); - dirContextProcessorMock = (DirContextProcessor) dirContextProcessorControl.getMock(); + dirContextProcessorMock = mock(DirContextProcessor.class); - dirContextOperationsConrol = MockControl.createControl(DirContextOperations.class); - dirContextOperationsMock = (DirContextOperations) dirContextOperationsConrol.getMock(); + dirContextOperationsMock = mock(DirContextOperations.class); - authenticatedContextControl = MockControl.createControl(DirContext.class); - authenticatedContextMock = (DirContext) authenticatedContextControl.getMock(); + authenticatedContextMock = mock(DirContext.class); - entryContextCallbackControl = MockControl.createControl(AuthenticatedLdapEntryContextCallback.class); - entryContextCallbackMock = (AuthenticatedLdapEntryContextCallback) entryContextCallbackControl.getMock(); + entryContextCallbackMock = mock(AuthenticatedLdapEntryContextCallback.class); tested = new LdapTemplate(contextSourceMock); } - protected void tearDown() throws Exception { - super.tearDown(); - - contextSourceControl = null; - contextSourceMock = null; - - dirContextControl = null; - dirContextMock = null; - - namingEnumerationControl = null; - namingEnumerationMock = null; - - nameControl = null; - nameMock = null; - - handlerControl = null; - handlerMock = null; - - contextMapperControl = null; - contextMapperMock = null; - - attributesMapperControl = null; - attributesMapperMock = null; - - contextExecutorControl = null; - contextExecutorMock = null; - - searchExecutorControl = null; - searchExecutorMock = null; - - dirContextProcessorControl = null; - dirContextProcessorMock = null; - - dirContextOperationsConrol = null; - dirContextOperationsMock = null; - } - - protected void replay() { - contextSourceControl.replay(); - dirContextControl.replay(); - namingEnumerationControl.replay(); - nameControl.replay(); - handlerControl.replay(); - contextMapperControl.replay(); - attributesMapperControl.replay(); - contextExecutorControl.replay(); - searchExecutorControl.replay(); - dirContextProcessorControl.replay(); - dirContextOperationsConrol.replay(); - authenticatedContextControl.replay(); - entryContextCallbackControl.replay(); - } - - protected void verify() { - contextSourceControl.verify(); - dirContextControl.verify(); - namingEnumerationControl.verify(); - nameControl.verify(); - handlerControl.verify(); - contextMapperControl.verify(); - attributesMapperControl.verify(); - contextExecutorControl.verify(); - searchExecutorControl.verify(); - dirContextProcessorControl.verify(); - dirContextOperationsConrol.verify(); - authenticatedContextControl.verify(); - entryContextCallbackControl.verify(); - } - private void expectGetReadWriteContext() { - contextSourceControl.expectAndReturn(contextSourceMock.getReadWriteContext(), dirContextMock); + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); } private void expectGetReadOnlyContext() { - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), dirContextMock); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); } + @Test public void testSearch_CallbackHandler() throws Exception { expectGetReadOnlyContext(); @@ -237,15 +144,13 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(searchControlsOneLevel(), searchResult); - handlerMock.handleNameClassPair(searchResult); - - dirContextMock.close(); - - replay(); tested.search(nameMock, "(ou=somevalue)", 1, true, handlerMock); - verify(); + + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); } + @Test public void testSearch_StringBase_CallbackHandler() throws Exception { expectGetReadOnlyContext(); @@ -255,15 +160,13 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(controls, searchResult); - handlerMock.handleNameClassPair(searchResult); - - dirContextMock.close(); - - replay(); tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, true, handlerMock); - verify(); + + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); } + @Test public void testSearch_CallbackHandler_Defaults() throws Exception { expectGetReadOnlyContext(); @@ -274,15 +177,13 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(controls, searchResult); - handlerMock.handleNameClassPair(searchResult); - - dirContextMock.close(); - - replay(); tested.search(nameMock, "(ou=somevalue)", handlerMock); - verify(); + + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); } + @Test public void testSearch_String_CallbackHandler_Defaults() throws Exception { expectGetReadOnlyContext(); @@ -293,28 +194,25 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(controls, searchResult); - handlerMock.handleNameClassPair(searchResult); - - dirContextMock.close(); - - replay(); tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", handlerMock); - verify(); + + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); } + @Test public void testSearch_NameNotFoundException() throws Exception { expectGetReadOnlyContext(); - SearchControls controls = searchControlsRecursive(); + final SearchControls controls = searchControlsRecursive(); controls.setReturningObjFlag(false); - dirContextControl.setDefaultMatcher(new SearchControlsMatcher()); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException("some text"); - dirContextControl.expectAndThrow(dirContextMock.search(nameMock, "(ou=somevalue)", controls), ne); + when(dirContextMock.search( + eq(nameMock), + eq("(ou=somevalue)"), + argThat(new SearchControlsMatcher(controls)))).thenThrow(ne); - dirContextMock.close(); - - replay(); try { tested.search(nameMock, "(ou=somevalue)", handlerMock); fail("NameNotFoundException expected"); @@ -322,22 +220,22 @@ public class LdapTemplateTest extends TestCase { catch (NameNotFoundException expected) { assertTrue(true); } - verify(); + verify(dirContextMock).close(); } + @Test public void testSearch_NamingException() throws Exception { expectGetReadOnlyContext(); SearchControls controls = searchControlsRecursive(); controls.setReturningObjFlag(false); - dirContextControl.setDefaultMatcher(new SearchControlsMatcher()); javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - dirContextControl.expectAndThrow(dirContextMock.search(nameMock, "(ou=somevalue)", controls), ne); + when(dirContextMock.search( + eq(nameMock), + eq("(ou=somevalue)"), + argThat(new SearchControlsMatcher(controls)))).thenThrow(ne); - dirContextMock.close(); - - replay(); try { tested.search(nameMock, "(ou=somevalue)", handlerMock); fail("LimitExceededException expected"); @@ -345,9 +243,11 @@ public class LdapTemplateTest extends TestCase { catch (LimitExceededException expected) { // expected } - verify(); + + verify(dirContextMock).close(); } + @Test public void testSearch_CallbackHandler_DirContextProcessor() throws Exception { expectGetReadOnlyContext(); @@ -356,21 +256,18 @@ public class LdapTemplateTest extends TestCase { SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); - dirContextProcessorMock.preProcess(dirContextMock); - singleSearchResult(controls, searchResult); - handlerMock.handleNameClassPair(searchResult); - - dirContextProcessorMock.postProcess(dirContextMock); - - dirContextMock.close(); - - replay(); tested.search(nameMock, "(ou=somevalue)", controls, handlerMock, dirContextProcessorMock); - verify(); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); } + @Test public void testSearch_String_CallbackHandler_DirContextProcessor() throws Exception { expectGetReadOnlyContext(); @@ -379,21 +276,18 @@ public class LdapTemplateTest extends TestCase { SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); - dirContextProcessorMock.preProcess(dirContextMock); - singleSearchResultWithStringBase(controls, searchResult); - handlerMock.handleNameClassPair(searchResult); - - dirContextProcessorMock.postProcess(dirContextMock); - - dirContextMock.close(); - - replay(); tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, handlerMock, dirContextProcessorMock); - verify(); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); } + @Test public void testSearch_String_AttributesMapper_DirContextProcessor() throws Exception { expectGetReadOnlyContext(); @@ -403,26 +297,25 @@ public class LdapTemplateTest extends TestCase { BasicAttributes expectedAttributes = new BasicAttributes(); SearchResult searchResult = new SearchResult("", null, expectedAttributes); - dirContextProcessorMock.preProcess(dirContextMock); singleSearchResultWithStringBase(controls, searchResult); Object expectedResult = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock.mapFromAttributes(expectedAttributes), - expectedResult); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - dirContextProcessorMock.postProcess(dirContextMock); - dirContextMock.close(); - - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, attributesMapperMock, dirContextProcessorMock); - verify(); - assertNotNull(list); + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_Name_AttributesMapper_DirContextProcessor() throws Exception { expectGetReadOnlyContext(); @@ -432,25 +325,24 @@ public class LdapTemplateTest extends TestCase { BasicAttributes expectedAttributes = new BasicAttributes(); SearchResult searchResult = new SearchResult("", null, expectedAttributes); - dirContextProcessorMock.preProcess(dirContextMock); singleSearchResult(controls, searchResult); Object expectedResult = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock.mapFromAttributes(expectedAttributes), - expectedResult); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - dirContextProcessorMock.postProcess(dirContextMock); - dirContextMock.close(); - - replay(); List list = tested.search(nameMock, "(ou=somevalue)", controls, attributesMapperMock, dirContextProcessorMock); - verify(); - assertNotNull(list); + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_String_SearchControls_ContextMapper_DirContextProcessor() throws Exception { expectGetReadOnlyContext(); @@ -459,25 +351,25 @@ public class LdapTemplateTest extends TestCase { Object expectedObject = new Object(); SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - dirContextProcessorMock.preProcess(dirContextMock); singleSearchResultWithStringBase(controls, searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextProcessorMock.postProcess(dirContextMock); - dirContextMock.close(); - - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock, dirContextProcessorMock); - verify(); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_Name_SearchControls_ContextMapper_DirContextProcessor() throws Exception { expectGetReadOnlyContext(); @@ -486,24 +378,24 @@ public class LdapTemplateTest extends TestCase { Object expectedObject = new Object(); SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - dirContextProcessorMock.preProcess(dirContextMock); singleSearchResult(controls, searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextProcessorMock.postProcess(dirContextMock); - dirContextMock.close(); - - replay(); List list = tested.search(nameMock, "(ou=somevalue)", controls, contextMapperMock, dirContextProcessorMock); - verify(); - assertNotNull(list); + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_AttributesMapper_ReturningAttrs() throws Exception { expectGetReadOnlyContext(); @@ -519,20 +411,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(controls, searchResult); Object expectedResult = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock.mapFromAttributes(expectedAttributes), - expectedResult); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(nameMock, "(ou=somevalue)", 1, attrs, attributesMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_String_AttributesMapper_ReturningAttrs() throws Exception { expectGetReadOnlyContext(); @@ -548,20 +439,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(controls, searchResult); Object expectedResult = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock.mapFromAttributes(expectedAttributes), - expectedResult); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attrs, attributesMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_AttributesMapper() throws Exception { expectGetReadOnlyContext(); @@ -574,20 +464,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(controls, searchResult); Object expectedResult = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock.mapFromAttributes(expectedAttributes), - expectedResult); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(nameMock, "(ou=somevalue)", 1, attributesMapperMock); - verify(); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_String_AttributesMapper() throws Exception { expectGetReadOnlyContext(); @@ -600,20 +489,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(controls, searchResult); Object expectedResult = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock.mapFromAttributes(expectedAttributes), - expectedResult); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attributesMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_AttributesMapper_Default() throws Exception { expectGetReadOnlyContext(); @@ -626,20 +514,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(controls, searchResult); Object expectedResult = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock.mapFromAttributes(expectedAttributes), - expectedResult); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(nameMock, "(ou=somevalue)", attributesMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_String_AttributesMapper_Default() throws Exception { expectGetReadOnlyContext(); @@ -652,20 +539,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(controls, searchResult); Object expectedResult = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock.mapFromAttributes(expectedAttributes), - expectedResult); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", attributesMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_ContextMapper() throws Exception { expectGetReadOnlyContext(); @@ -675,19 +561,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(searchControlsOneLevel(), searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(nameMock, "(ou=somevalue)", 1, contextMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_ContextMapper_ReturningAttrs() throws Exception { expectGetReadOnlyContext(); @@ -702,19 +588,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(controls, searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(nameMock, "(ou=somevalue)", 1, attrs, contextMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_String_ContextMapper_ReturningAttrs() throws Exception { expectGetReadOnlyContext(); @@ -729,19 +615,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(controls, searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attrs, contextMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_String_ContextMapper() throws Exception { expectGetReadOnlyContext(); @@ -753,19 +639,20 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(controls, searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, contextMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_ContextMapper_Default() throws Exception { expectGetReadOnlyContext(); @@ -775,19 +662,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(searchControlsRecursive(), searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(nameMock, "(ou=somevalue)", contextMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_String_ContextMapper_Default() throws Exception { expectGetReadOnlyContext(); @@ -799,19 +686,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(controls, searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", contextMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_String_SearchControls_ContextMapper() throws Exception { expectGetReadOnlyContext(); @@ -823,19 +710,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(controls, searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock); - verify(); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_String_SearchControls_ContextMapper_ReturningObjFlagNotSet() throws Exception { expectGetReadOnlyContext(); @@ -852,19 +739,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(expectedControls, searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_Name_SearchControls_ContextMapper() throws Exception { expectGetReadOnlyContext(); @@ -876,19 +763,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(controls, searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(nameMock, "(ou=somevalue)", controls, contextMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_String_SearchControls_AttributesMapper() throws Exception { expectGetReadOnlyContext(); @@ -901,20 +788,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResultWithStringBase(controls, searchResult); Object expectedResult = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock.mapFromAttributes(expectedAttributes), - expectedResult); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, attributesMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testSearch_Name_SearchControls_AttributesMapper() throws Exception { expectGetReadOnlyContext(); @@ -927,57 +813,51 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(controls, searchResult); Object expectedResult = new Object(); - attributesMapperControl.expectAndReturn(attributesMapperMock.mapFromAttributes(expectedAttributes), - expectedResult); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); List list = tested.search(nameMock, "(ou=somevalue)", controls, attributesMapperMock); - verify(); - assertNotNull(list); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertNotNull(list); assertEquals(1, list.size()); assertSame(expectedResult, list.get(0)); } + @Test public void testModifyAttributes() throws Exception { expectGetReadWriteContext(); ModificationItem[] mods = new ModificationItem[0]; - dirContextMock.modifyAttributes(nameMock, mods); - dirContextMock.close(); - - replay(); tested.modifyAttributes(nameMock, mods); - verify(); + + verify(dirContextMock).modifyAttributes(nameMock, mods); + verify(dirContextMock).close(); } + @Test public void testModifyAttributes_String() throws Exception { expectGetReadWriteContext(); ModificationItem[] mods = new ModificationItem[0]; - dirContextMock.modifyAttributes(DEFAULT_BASE_STRING, mods); - dirContextMock.close(); - - replay(); tested.modifyAttributes(DEFAULT_BASE_STRING, mods); - verify(); + + verify(dirContextMock).modifyAttributes(DEFAULT_BASE_STRING, mods); + verify(dirContextMock).close(); } + @Test public void testModifyAttributes_NamingException() throws Exception { expectGetReadWriteContext(); ModificationItem[] mods = new ModificationItem[0]; - dirContextMock.modifyAttributes(nameMock, mods); - javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - dirContextControl.setThrowable(ne); - dirContextMock.close(); + javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); + doThrow(ne).when(dirContextMock).modifyAttributes(nameMock, mods); - replay(); try { tested.modifyAttributes(nameMock, mods); fail("LimitExceededException expected"); @@ -985,46 +865,46 @@ public class LdapTemplateTest extends TestCase { catch (LimitExceededException expected) { assertTrue(true); } - verify(); + + verify(dirContextMock).close(); } + @Test public void testBind() throws Exception { expectGetReadWriteContext(); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - dirContextMock.bind(nameMock, expectedObject, expectedAttributes); - dirContextMock.close(); - replay(); tested.bind(nameMock, expectedObject, expectedAttributes); - verify(); - } + verify(dirContextMock).bind(nameMock, expectedObject, expectedAttributes); + verify(dirContextMock).close(); + + } + + @Test public void testBind_String() throws Exception { expectGetReadWriteContext(); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - dirContextMock.bind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); - dirContextMock.close(); - replay(); tested.bind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); - verify(); + + verify(dirContextMock).bind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); + verify(dirContextMock).close(); } + @Test public void testBind_NamingException() throws Exception { expectGetReadWriteContext(); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - dirContextMock.bind(nameMock, expectedObject, expectedAttributes); - javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - dirContextControl.setThrowable(ne); - dirContextMock.close(); + javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); + doThrow(ne).when(dirContextMock).bind(nameMock, expectedObject, expectedAttributes); - replay(); try { tested.bind(nameMock, expectedObject, expectedAttributes); fail("NameNotFoundException expected"); @@ -1032,155 +912,131 @@ public class LdapTemplateTest extends TestCase { catch (NameNotFoundException expected) { assertTrue(true); } - verify(); + + verify(dirContextMock).close(); } - + + @Test public void testBindWithContext() throws Exception { expectGetReadWriteContext(); - dirContextOperationsConrol.expectAndReturn(dirContextOperationsMock - .getDn(), nameMock); - dirContextOperationsConrol.expectAndReturn(dirContextOperationsMock - .isUpdateMode(), false); - dirContextMock.bind(nameMock, dirContextOperationsMock, null); - dirContextMock.close(); + when(dirContextOperationsMock.getDn()).thenReturn(nameMock); + when(dirContextOperationsMock.isUpdateMode()).thenReturn(false); - replay(); tested.bind(dirContextOperationsMock); - verify(); + + verify(dirContextMock).bind(nameMock, dirContextOperationsMock, null); + verify(dirContextMock).close(); } + @Test public void testUnbind() throws Exception { expectGetReadWriteContext(); - dirContextMock.unbind(nameMock); - dirContextMock.close(); - replay(); tested.unbind(nameMock); - verify(); + + verify(dirContextMock).unbind(nameMock); + verify(dirContextMock).close(); } + @Test public void testUnbind_String() throws Exception { expectGetReadWriteContext(); - dirContextMock.unbind(DEFAULT_BASE_STRING); - dirContextMock.close(); - replay(); tested.unbind(DEFAULT_BASE_STRING); - verify(); + + verify(dirContextMock).unbind(DEFAULT_BASE_STRING); + verify(dirContextMock).close(); } - + + @Test public void testRebindWithContext() throws Exception { expectGetReadWriteContext(); - dirContextOperationsConrol.expectAndReturn(dirContextOperationsMock - .getDn(), nameMock); - dirContextOperationsConrol.expectAndReturn(dirContextOperationsMock - .isUpdateMode(), false); - dirContextMock.rebind(nameMock, dirContextOperationsMock, null); - dirContextMock.close(); + when(dirContextOperationsMock.getDn()).thenReturn(nameMock); + when(dirContextOperationsMock.isUpdateMode()).thenReturn(false); - replay(); tested.rebind(dirContextOperationsMock); - verify(); + + verify(dirContextMock).rebind(nameMock, dirContextOperationsMock, null); + verify(dirContextMock).close(); } + @Test public void testUnbindRecursive() throws Exception { expectGetReadWriteContext(); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), true); + when(namingEnumerationMock.hasMore()).thenReturn(true, false, false); Binding binding = new Binding("cn=Some name", null); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.next(), binding); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), false); - namingEnumerationMock.close(); - - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), false); - namingEnumerationMock.close(); + when(namingEnumerationMock.next()).thenReturn(binding); DistinguishedName listDn = new DistinguishedName(DEFAULT_BASE_STRING); - dirContextMock.listBindings(listDn); - dirContextControl.setReturnValue(namingEnumerationMock); + when(dirContextMock.listBindings(listDn)).thenReturn(namingEnumerationMock); DistinguishedName subListDn = new DistinguishedName("cn=Some name, o=example.com"); - dirContextMock.listBindings(subListDn); - dirContextControl.setReturnValue(namingEnumerationMock); + when(dirContextMock.listBindings(subListDn)).thenReturn(namingEnumerationMock); - dirContextMock.unbind(subListDn); - dirContextMock.unbind(listDn); - dirContextMock.close(); + tested.unbind(new CompositeName(DEFAULT_BASE_STRING), true); - // Caused by creating a DistinguishedName from a Name - nameControl.expectAndReturn(nameMock.size(), 1, 2); - nameControl.expectAndReturn(nameMock.get(0), "o=example.com"); - - replay(); - tested.unbind(nameMock, true); - verify(); + verify(dirContextMock).unbind(subListDn); + verify(dirContextMock).unbind(listDn); + verify(namingEnumerationMock, times(2)).close(); + verify(dirContextMock).close(); } + @Test public void testUnbindRecursive_String() throws Exception { expectGetReadWriteContext(); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), true); + when(namingEnumerationMock.hasMore()).thenReturn(true, false, false); Binding binding = new Binding("cn=Some name", null); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.next(), binding); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), false); - namingEnumerationMock.close(); - - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), false); - namingEnumerationMock.close(); + when(namingEnumerationMock.next()).thenReturn(binding); DistinguishedName listDn = new DistinguishedName(DEFAULT_BASE_STRING); - dirContextMock.listBindings(listDn); - dirContextControl.setReturnValue(namingEnumerationMock); + when(dirContextMock.listBindings(listDn)).thenReturn(namingEnumerationMock); DistinguishedName subListDn = new DistinguishedName("cn=Some name, o=example.com"); - dirContextMock.listBindings(subListDn); - dirContextControl.setReturnValue(namingEnumerationMock); + when(dirContextMock.listBindings(subListDn)).thenReturn(namingEnumerationMock); - dirContextMock.unbind(subListDn); - dirContextMock.unbind(listDn); - dirContextMock.close(); - replay(); tested.unbind(DEFAULT_BASE_STRING, true); - verify(); + + verify(dirContextMock).unbind(subListDn); + verify(dirContextMock).unbind(listDn); + verify(namingEnumerationMock, times(2)).close(); + verify(dirContextMock).close(); } + @Test public void testRebind() throws Exception { expectGetReadWriteContext(); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - dirContextMock.rebind(nameMock, expectedObject, expectedAttributes); - dirContextMock.close(); - - replay(); tested.rebind(nameMock, expectedObject, expectedAttributes); - verify(); + + verify(dirContextMock).rebind(nameMock, expectedObject, expectedAttributes); + verify(dirContextMock).close(); } + @Test public void testRebind_String() throws Exception { expectGetReadWriteContext(); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - dirContextMock.rebind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); - dirContextMock.close(); - - replay(); tested.rebind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); - verify(); + + verify(dirContextMock).rebind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); + verify(dirContextMock).close(); } + @Test public void testUnbind_NamingException() throws Exception { expectGetReadWriteContext(); - dirContextMock.unbind(nameMock); - javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - dirContextControl.setThrowable(ne); - dirContextMock.close(); + javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); + doThrow(ne).when(dirContextMock).unbind(nameMock); - replay(); try { tested.unbind(nameMock); fail("NameNotFoundException expected"); @@ -1188,33 +1044,31 @@ public class LdapTemplateTest extends TestCase { catch (NameNotFoundException expected) { assertTrue(true); } - verify(); + + verify(dirContextMock).close(); } + @Test public void testExecuteReadOnly() throws Exception { expectGetReadOnlyContext(); Object object = new Object(); - contextExecutorControl.expectAndReturn(contextExecutorMock.executeWithContext(dirContextMock), object); + when(contextExecutorMock.executeWithContext(dirContextMock)).thenReturn(object); - dirContextMock.close(); - - replay(); Object result = tested.executeReadOnly(contextExecutorMock); - verify(); + + verify(dirContextMock).close(); assertSame(object, result); } + @Test public void testExecuteReadOnly_NamingException() throws Exception { expectGetReadOnlyContext(); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - contextExecutorControl.expectAndThrow(contextExecutorMock.executeWithContext(dirContextMock), ne); + when(contextExecutorMock.executeWithContext(dirContextMock)).thenThrow(ne); - dirContextMock.close(); - - replay(); try { tested.executeReadOnly(contextExecutorMock); fail("NameNotFoundException expected"); @@ -1222,33 +1076,31 @@ public class LdapTemplateTest extends TestCase { catch (NameNotFoundException expected) { assertTrue(true); } - verify(); + + verify(dirContextMock).close(); } + @Test public void testExecuteReadWrite() throws Exception { expectGetReadWriteContext(); Object object = new Object(); - contextExecutorControl.expectAndReturn(contextExecutorMock.executeWithContext(dirContextMock), object); + when(contextExecutorMock.executeWithContext(dirContextMock)).thenReturn(object); - dirContextMock.close(); - - replay(); Object result = tested.executeReadWrite(contextExecutorMock); - verify(); - assertSame(object, result); + verify(dirContextMock).close(); + + assertSame(object, result); } + @Test public void testExecuteReadWrite_NamingException() throws Exception { expectGetReadWriteContext(); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - contextExecutorControl.expectAndThrow(contextExecutorMock.executeWithContext(dirContextMock), ne); + when(contextExecutorMock.executeWithContext(dirContextMock)).thenThrow(ne); - dirContextMock.close(); - - replay(); try { tested.executeReadWrite(contextExecutorMock); fail("NameNotFoundException expected"); @@ -1256,46 +1108,37 @@ public class LdapTemplateTest extends TestCase { catch (NameNotFoundException expected) { assertTrue(true); } - verify(); + + verify(dirContextMock).close(); } + @Test public void testDoSearch_DirContextProcessor() throws Exception { expectGetReadOnlyContext(); SearchResult searchResult = new SearchResult(null, null, null); - dirContextProcessorMock.preProcess(dirContextMock); + when(searchExecutorMock.executeSearch(dirContextMock)).thenReturn(namingEnumerationMock); - searchExecutorControl.expectAndReturn(searchExecutorMock.executeSearch(dirContextMock), namingEnumerationMock); + when(namingEnumerationMock.hasMore()).thenReturn(true, false); + when(namingEnumerationMock.next()).thenReturn(searchResult); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), true); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.next(), searchResult); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), false); - namingEnumerationMock.close(); - - handlerMock.handleNameClassPair(searchResult); - - dirContextProcessorMock.postProcess(dirContextMock); - - dirContextMock.close(); - - replay(); tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); - verify(); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(handlerMock).handleNameClassPair(searchResult); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); } + @Test public void testDoSearch_DirContextProcessor_NamingException() throws Exception { expectGetReadOnlyContext(); - dirContextProcessorMock.preProcess(dirContextMock); - javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - searchExecutorControl.expectAndThrow(searchExecutorMock.executeSearch(dirContextMock), ne); + when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(ne); - dirContextProcessorMock.postProcess(dirContextMock); - dirContextMock.close(); - - replay(); try { tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); fail("LimitExceededException expected"); @@ -1303,39 +1146,37 @@ public class LdapTemplateTest extends TestCase { catch (LimitExceededException expected) { assertTrue(true); } - verify(); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(dirContextMock).close(); } + @Test public void testDoSearch() throws Exception { expectGetReadOnlyContext(); SearchResult searchResult = new SearchResult(null, null, null); - searchExecutorControl.expectAndReturn(searchExecutorMock.executeSearch(dirContextMock), namingEnumerationMock); + when(searchExecutorMock.executeSearch(dirContextMock)).thenReturn(namingEnumerationMock); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), true); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.next(), searchResult); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), false); - namingEnumerationMock.close(); + when(namingEnumerationMock.hasMore()).thenReturn(true, false); + when(namingEnumerationMock.next()).thenReturn(searchResult); - handlerMock.handleNameClassPair(searchResult); - - dirContextMock.close(); - - replay(); tested.search(searchExecutorMock, handlerMock); - verify(); + + verify(handlerMock).handleNameClassPair(searchResult); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); } + @Test public void testDoSearch_NamingException() throws Exception { expectGetReadOnlyContext(); javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - searchExecutorControl.expectAndThrow(searchExecutorMock.executeSearch(dirContextMock), ne); + when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(ne); - dirContextMock.close(); - - replay(); try { tested.search(searchExecutorMock, handlerMock); fail("LimitExceededException expected"); @@ -1343,21 +1184,19 @@ public class LdapTemplateTest extends TestCase { catch (LimitExceededException expected) { assertTrue(true); } - verify(); + + verify(dirContextMock).close(); } + @Test public void testDoSearch_NamingException_NamingEnumeration() throws Exception { expectGetReadOnlyContext(); - searchExecutorControl.expectAndReturn(searchExecutorMock.executeSearch(dirContextMock), namingEnumerationMock); + when(searchExecutorMock.executeSearch(dirContextMock)).thenReturn(namingEnumerationMock); javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - namingEnumerationControl.expectAndThrow(namingEnumerationMock.hasMore(), ne); - namingEnumerationMock.close(); + when(namingEnumerationMock.hasMore()).thenThrow(ne); - dirContextMock.close(); - - replay(); try { tested.search(searchExecutorMock, handlerMock); fail("LimitExceededException expected"); @@ -1365,17 +1204,17 @@ public class LdapTemplateTest extends TestCase { catch (LimitExceededException expected) { assertTrue(true); } - verify(); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); } + @Test public void testDoSearch_NameNotFoundException() throws Exception { expectGetReadOnlyContext(); - searchExecutorControl.expectAndThrow(searchExecutorMock.executeSearch(dirContextMock), - new javax.naming.NameNotFoundException()); - dirContextMock.close(); + when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(new javax.naming.NameNotFoundException()); - replay(); try { tested.search(searchExecutorMock, handlerMock); fail("NameNotFoundException expected"); @@ -1383,20 +1222,17 @@ public class LdapTemplateTest extends TestCase { catch (NameNotFoundException expected) { assertTrue(true); } - verify(); + + verify(dirContextMock).close(); } + @Test public void testSearch_PartialResult_IgnoreNotSet() throws Exception { expectGetReadOnlyContext(); - dirContextProcessorMock.preProcess(dirContextMock); - javax.naming.PartialResultException ex = new javax.naming.PartialResultException(); - searchExecutorControl.expectAndThrow(searchExecutorMock.executeSearch(dirContextMock), ex); - dirContextProcessorMock.postProcess(dirContextMock); - dirContextMock.close(); + when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(ex); - replay(); try { tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); fail("PartialResultException expected"); @@ -1404,27 +1240,28 @@ public class LdapTemplateTest extends TestCase { catch (PartialResultException expected) { assertTrue(true); } - verify(); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(dirContextMock).close(); } + @Test public void testSearch_PartialResult_IgnoreSet() throws Exception { tested.setIgnorePartialResultException(true); expectGetReadOnlyContext(); - dirContextProcessorMock.preProcess(dirContextMock); + when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(new javax.naming.PartialResultException()); - searchExecutorControl.expectAndThrow(searchExecutorMock.executeSearch(dirContextMock), - new javax.naming.PartialResultException()); - - dirContextProcessorMock.postProcess(dirContextMock); - dirContextMock.close(); - - replay(); tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); - verify(); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(dirContextMock).close(); } + @Test public void testLookupContextWithName() { final DirContextAdapter expectedResult = new DirContextAdapter(); @@ -1440,6 +1277,7 @@ public class LdapTemplateTest extends TestCase { } + @Test public void testLookupContextWithString() { final DirContextAdapter expectedResult = new DirContextAdapter(); final String expectedName = "cn=John Doe"; @@ -1455,13 +1293,13 @@ public class LdapTemplateTest extends TestCase { assertSame(expectedResult, result); } + @Test public void testModifyAttributesWithDirContextOperations() throws Exception { final ModificationItem[] expectedModifications = new ModificationItem[0]; - dirContextOperationsConrol.expectAndReturn(dirContextOperationsMock.getDn(), DistinguishedName.EMPTY_PATH); - dirContextOperationsConrol.expectAndReturn(dirContextOperationsMock.isUpdateMode(), true); - dirContextOperationsConrol.expectAndReturn(dirContextOperationsMock.getModificationItems(), - expectedModifications); + when(dirContextOperationsMock.getDn()).thenReturn(DistinguishedName.EMPTY_PATH); + when(dirContextOperationsMock.isUpdateMode()).thenReturn(true); + when(dirContextOperationsMock.getModificationItems()).thenReturn(expectedModifications); LdapTemplate tested = new LdapTemplate() { public void modifyAttributes(Name dn, ModificationItem[] mods) { @@ -1470,15 +1308,14 @@ public class LdapTemplateTest extends TestCase { } }; - replay(); tested.modifyAttributes(dirContextOperationsMock); - verify(); } + @Test public void testModifyAttributesWithDirContextOperationsNotInitializedDn() throws Exception { - dirContextOperationsConrol.expectAndReturn(dirContextOperationsMock.getDn(), DistinguishedName.EMPTY_PATH); - dirContextOperationsConrol.expectAndReturn(dirContextOperationsMock.isUpdateMode(), false); + when(dirContextOperationsMock.getDn()).thenReturn(DistinguishedName.EMPTY_PATH); + when(dirContextOperationsMock.isUpdateMode()).thenReturn(false); LdapTemplate tested = new LdapTemplate() { public void modifyAttributes(Name dn, ModificationItem[] mods) { @@ -1486,7 +1323,6 @@ public class LdapTemplateTest extends TestCase { } }; - replay(); try { tested.modifyAttributes(dirContextOperationsMock); fail("IllegalStateException expected"); @@ -1494,12 +1330,11 @@ public class LdapTemplateTest extends TestCase { catch (IllegalStateException expected) { assertTrue(true); } - verify(); } + @Test public void testModifyAttributesWithDirContextOperationsNotInitializedInUpdateMode() throws Exception { - - dirContextOperationsConrol.expectAndReturn(dirContextOperationsMock.getDn(), null); + when(dirContextOperationsMock.getDn()).thenReturn(null); LdapTemplate tested = new LdapTemplate() { public void modifyAttributes(Name dn, ModificationItem[] mods) { @@ -1507,7 +1342,6 @@ public class LdapTemplateTest extends TestCase { } }; - replay(); try { tested.modifyAttributes(dirContextOperationsMock); fail("IllegalStateException expected"); @@ -1515,9 +1349,9 @@ public class LdapTemplateTest extends TestCase { catch (IllegalStateException expected) { assertTrue(true); } - verify(); } + @Test public void testSearchForObject() throws Exception { expectGetReadOnlyContext(); @@ -1527,18 +1361,17 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(searchControlsRecursive(), searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); Object result = tested.searchForObject(nameMock, "(ou=somevalue)", contextMapperMock); - verify(); - assertNotNull(result); + verify(dirContextMock).close(); + + assertNotNull(result); assertSame(expectedResult, result); } + @Test public void testSearchForObjectWithMultipleResults() throws Exception { expectGetReadOnlyContext(); @@ -1547,24 +1380,18 @@ public class LdapTemplateTest extends TestCase { Object expectedObject = new Object(); SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - dirContextControl.setDefaultMatcher(new SearchControlsMatcher()); - dirContextControl.expectAndReturn(dirContextMock.search(nameMock, "(ou=somevalue)", controls), - namingEnumerationMock); + when(dirContextMock.search( + eq(nameMock), + eq("(ou=somevalue)"), + argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), true); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.next(), searchResult); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), true); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.next(), searchResult); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), false); - namingEnumerationMock.close(); + when(namingEnumerationMock.hasMore()).thenReturn(true, true, false); + when(namingEnumerationMock.next()).thenReturn(searchResult, searchResult); Object expectedResult = expectedObject; - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); - contextMapperControl.expectAndReturn(contextMapperMock.mapFromContext(expectedObject), expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - dirContextMock.close(); - - replay(); try { tested.searchForObject(nameMock, "(ou=somevalue)", contextMapperMock); fail("IncorrectResultSizeDataAccessException expected"); @@ -1572,17 +1399,17 @@ public class LdapTemplateTest extends TestCase { catch (IncorrectResultSizeDataAccessException expected) { assertTrue(true); } - verify(); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); } + @Test public void testSearchForObjectWithNoResults() throws Exception { expectGetReadOnlyContext(); noSearchResults(searchControlsRecursive()); - dirContextMock.close(); - - replay(); try { tested.searchForObject(nameMock, "(ou=somevalue)", contextMapperMock); fail("EmptyResultDataAccessException expected"); @@ -1590,11 +1417,13 @@ public class LdapTemplateTest extends TestCase { catch (EmptyResultDataAccessException expected) { assertTrue(true); } - verify(); - } + verify(dirContextMock).close(); + } + + @Test public void testAuthenticateWithSingleUserFoundShouldBeSuccessful() throws Exception { - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), dirContextMock); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); Object expectedObject = new DirContextAdapter(new BasicAttributes(), new DistinguishedName("cn=john doe"), new DistinguishedName("dc=jayway, dc=se")); @@ -1602,23 +1431,22 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(searchControlsRecursive(), searchResult); - contextSourceControl.expectAndReturn(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password"), - authenticatedContextMock); + when(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password")) + .thenReturn(authenticatedContextMock); entryContextCallbackMock.executeWithContext(authenticatedContextMock, new LdapEntryIdentification( new DistinguishedName("cn=john doe,dc=jayway,dc=se"), new DistinguishedName("cn=john doe"))); - authenticatedContextMock.close(); - dirContextMock.close(); - - replay(); boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); - verify(); + + verify(authenticatedContextMock).close(); + verify(dirContextMock).close(); assertTrue(result); } + @Test public void testAuthenticateWithTwoUsersFoundShouldThrowException() throws Exception { - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), dirContextMock); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); Object expectedObject = new DirContextAdapter(new BasicAttributes(), new DistinguishedName("cn=john doe"), new DistinguishedName("dc=jayway, dc=se")); @@ -1627,9 +1455,6 @@ public class LdapTemplateTest extends TestCase { setupSearchResults(searchControlsRecursive(), new SearchResult[] { searchResult1, searchResult2 }); - dirContextMock.close(); - - replay(); try { tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); fail("IncorrectResultSizeDataAccessException expected"); @@ -1637,25 +1462,26 @@ public class LdapTemplateTest extends TestCase { catch (IncorrectResultSizeDataAccessException expected) { // expected } - verify(); + + verify(dirContextMock).close(); } + @Test public void testAuthenticateWhenNoUserWasFoundShouldFail() throws Exception { - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), dirContextMock); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); noSearchResults(searchControlsRecursive()); - dirContextMock.close(); - - replay(); boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); - verify(); - assertFalse(result); + verify(dirContextMock).close(); + + assertFalse(result); } + @Test public void testAuthenticateWithFailedAuthenticationShouldFail() throws Exception { - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), dirContextMock); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); Object expectedObject = new DirContextAdapter(new BasicAttributes(), new DistinguishedName("cn=john doe"), new DistinguishedName("dc=jayway, dc=se")); @@ -1663,20 +1489,19 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(searchControlsRecursive(), searchResult); - contextSourceControl.expectAndThrow(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password"), - new UncategorizedLdapException("Authentication failed")); + when(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password")) + .thenThrow(new UncategorizedLdapException("Authentication failed")); - dirContextMock.close(); - - replay(); boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); - verify(); - assertFalse(result); + verify(dirContextMock).close(); + + assertFalse(result); } - + + @Test public void testAuthenticateWithErrorInCallbackShouldFail() throws Exception { - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), dirContextMock); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); Object expectedObject = new DirContextAdapter(new BasicAttributes(), new DistinguishedName("cn=john doe"), new DistinguishedName("dc=jayway, dc=se")); @@ -1684,53 +1509,60 @@ public class LdapTemplateTest extends TestCase { singleSearchResult(searchControlsRecursive(), searchResult); - contextSourceControl.expectAndReturn(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password"), - authenticatedContextMock); - entryContextCallbackMock.executeWithContext(authenticatedContextMock, new LdapEntryIdentification( - new DistinguishedName("cn=john doe,dc=jayway,dc=se"), new DistinguishedName("cn=john doe"))); - entryContextCallbackControl.setThrowable(new UncategorizedLdapException("Authentication failed")); + when(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password")) + .thenReturn(authenticatedContextMock); + doThrow(new UncategorizedLdapException("Authentication failed")).when(entryContextCallbackMock) + .executeWithContext(authenticatedContextMock, + new LdapEntryIdentification( + new DistinguishedName("cn=john doe,dc=jayway,dc=se"), new DistinguishedName("cn=john doe"))); - authenticatedContextMock.close(); - dirContextMock.close(); - - replay(); boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); - verify(); - assertFalse(result); + verify(authenticatedContextMock).close(); + verify(dirContextMock).close(); + + assertFalse(result); } private void noSearchResults(SearchControls controls) throws Exception { - setupSearchResults(controls, new SearchResult[] {}); - } + when(dirContextMock.search( + eq(nameMock), + eq("(ou=somevalue)"), + argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); + + when(namingEnumerationMock.hasMore()).thenReturn(false); + } private void singleSearchResult(SearchControls controls, SearchResult searchResult) throws Exception { setupSearchResults(controls, new SearchResult[] { searchResult }); } private void setupSearchResults(SearchControls controls, SearchResult[] searchResults) throws Exception { - dirContextControl.setDefaultMatcher(new SearchControlsMatcher()); - dirContextControl.expectAndReturn(dirContextMock.search(nameMock, "(ou=somevalue)", controls), - namingEnumerationMock); + when(dirContextMock.search( + eq(nameMock), + eq("(ou=somevalue)"), + argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); - for (int i = 0; i < searchResults.length; i++) { - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), true); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.next(), searchResults[i]); - } - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), false); - namingEnumerationMock.close(); + if(searchResults.length == 1) { + when(namingEnumerationMock.hasMore()).thenReturn(true, false); + when(namingEnumerationMock.next()).thenReturn(searchResults[0]); + } else if(searchResults.length ==2) { + when(namingEnumerationMock.hasMore()).thenReturn(true, true, false); + when(namingEnumerationMock.next()).thenReturn(searchResults[0], searchResults[1]); + } else { + throw new IllegalArgumentException("Cannot handle " + searchResults.length + " search results"); + } } private void singleSearchResultWithStringBase(SearchControls controls, SearchResult searchResult) throws Exception { - dirContextControl.setDefaultMatcher(new SearchControlsMatcher()); - dirContextControl.expectAndReturn(dirContextMock.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls), - namingEnumerationMock); + when(dirContextMock.search( + eq(DEFAULT_BASE_STRING), + eq("(ou=somevalue)"), + argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), true); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.next(), searchResult); - namingEnumerationControl.expectAndReturn(namingEnumerationMock.hasMore(), false); - namingEnumerationMock.close(); + when(namingEnumerationMock.hasMore()).thenReturn(true, false); + when(namingEnumerationMock.next()).thenReturn(searchResult); } private SearchControls searchControlsRecursive() { @@ -1747,26 +1579,32 @@ public class LdapTemplateTest extends TestCase { return controls; } - /** - * Needed to verify search control values. - * - * @author Mattias Hellborg Arthursson - */ - private static class SearchControlsMatcher extends AbstractMatcher { - protected boolean argumentMatches(Object expected, Object actual) { - if (expected instanceof SearchControls && actual instanceof SearchControls) { - SearchControls s0 = (SearchControls) expected; - SearchControls s1 = (SearchControls) actual; + private static class SearchControlsMatcher extends BaseMatcher { + private final SearchControls controls; - return s0.getSearchScope() == s1.getSearchScope() - && s0.getReturningObjFlag() == s1.getReturningObjFlag() - && s0.getDerefLinkFlag() == s1.getDerefLinkFlag() && s0.getCountLimit() == s1.getCountLimit() - && s0.getTimeLimit() == s1.getTimeLimit() - && s0.getReturningAttributes() == s1.getReturningAttributes(); - } - else { - return super.argumentMatches(expected, actual); - } - } - } + public SearchControlsMatcher(SearchControls controls) { + this.controls = controls; + } + + @Override + public boolean matches(Object item) { + if (item instanceof SearchControls) { + SearchControls s1 = (SearchControls) item; + + return controls.getSearchScope() == s1.getSearchScope() + && controls.getReturningObjFlag() == s1.getReturningObjFlag() + && controls.getDerefLinkFlag() == s1.getDerefLinkFlag() && controls.getCountLimit() == s1.getCountLimit() + && controls.getTimeLimit() == s1.getTimeLimit() + && controls.getReturningAttributes() == s1.getReturningAttributes(); + } + else { + throw new IllegalArgumentException(); + } + } + + @Override + public void describeTo(Description description) { + description.appendText("SearchControls matches"); + } + } } diff --git a/core/src/test/java/org/springframework/ldap/core/RequestControlMatcher.java b/core/src/test/java/org/springframework/ldap/core/RequestControlMatcher.java deleted file mode 100644 index 4601641e..00000000 --- a/core/src/test/java/org/springframework/ldap/core/RequestControlMatcher.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import javax.naming.ldap.Control; - -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; -import org.easymock.AbstractMatcher; - -/** - * Custom argument matcher that matches javax.naming.ldap.Control objects. - * - * @author Adam Skogman - */ -public class RequestControlMatcher extends AbstractMatcher { - - /** - * @see org.easymock.AbstractMatcher#argumentMatches(java.lang.Object, - * java.lang.Object) - */ - protected boolean argumentMatches(Object expected, Object actual) { - - // null checks - if (expected == null && actual == null) { - return true; - } - if (expected == null || actual == null) { - return false; - } - - // Both params should be arrays - Object[] expArray = (Object[]) expected; - Object[] actArray = (Object[]) actual; - - if (expArray.length != actArray.length) { - return false; - } - - // Compary each object - for (int i = 0; i < expArray.length; i++) { - if (!controlMatches((Control) expArray[i], (Control) actArray[i])) { - return false; - } - } - return true; - - } - - private boolean controlMatches(Control expected, Control actual) { - - // Compare SortControl - return StringUtils.equals(expected.getID(), actual.getID()) - && expected.isCritical() == actual.isCritical() - && ArrayUtils.isEquals(expected.getEncodedValue(), actual - .getEncodedValue()); - } -} diff --git a/core/src/test/java/org/springframework/ldap/core/support/AggregateDirContextProcessorTest.java b/core/src/test/java/org/springframework/ldap/core/support/AggregateDirContextProcessorTest.java index 843d0037..b6396f38 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/AggregateDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/AggregateDirContextProcessorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,38 +15,30 @@ */ package org.springframework.ldap.core.support; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.DirContextProcessor; + import javax.naming.NamingException; -import junit.framework.TestCase; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; -import org.easymock.MockControl; -import org.springframework.ldap.core.DirContextProcessor; -import org.springframework.ldap.core.support.AggregateDirContextProcessor; - -public class AggregateDirContextProcessorTest extends TestCase { - - private MockControl processor1Control; +public class AggregateDirContextProcessorTest { private DirContextProcessor processor1Mock; - private MockControl processor2Control; - private DirContextProcessor processor2Mock; private AggregateDirContextProcessor tested; - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() throws Exception { // Create processor1 mock - processor1Control = MockControl - .createControl(DirContextProcessor.class); - processor1Mock = (DirContextProcessor) processor1Control.getMock(); + processor1Mock = mock(DirContextProcessor.class); // Create processor2 mock - processor2Control = MockControl - .createControl(DirContextProcessor.class); - processor2Mock = (DirContextProcessor) processor2Control.getMock(); + processor2Mock = mock(DirContextProcessor.class); tested = new AggregateDirContextProcessor(); tested.addDirContextProcessor(processor1Mock); @@ -54,47 +46,20 @@ public class AggregateDirContextProcessorTest extends TestCase { } - protected void tearDown() throws Exception { - super.tearDown(); - - processor1Control = null; - processor1Mock = null; - - processor2Control = null; - processor2Mock = null; - } - - protected void replay() { - processor1Control.replay(); - processor2Control.replay(); - - } - - protected void verify() { - processor1Control.verify(); - processor2Control.verify(); - } - + @Test public void testPreProcess() throws NamingException { - processor1Mock.preProcess(null); - processor2Mock.preProcess(null); - - replay(); - tested.preProcess(null); - verify(); + verify(processor1Mock).preProcess(null); + verify(processor2Mock).preProcess(null); } + @Test public void testPostProcess() throws NamingException { - processor1Mock.postProcess(null); - processor2Mock.postProcess(null); - - replay(); - tested.postProcess(null); - - verify(); + + verify(processor1Mock).postProcess(null); + verify(processor2Mock).postProcess(null); } } diff --git a/core/src/test/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessorTest.java b/core/src/test/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessorTest.java index 554ef842..7e4a7e6b 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,66 +15,54 @@ */ package org.springframework.ldap.core.support; -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.ldap.core.DistinguishedName; -import junit.framework.TestCase; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * Unit tests for {@link BaseLdapPathBeanPostProcessor}. * * @author Mattias Hellborg Arthursson */ -public class BaseLdapPathBeanPostProcessorTest extends TestCase { +public class BaseLdapPathBeanPostProcessorTest { private BaseLdapPathBeanPostProcessor tested; - private MockControl ldapPathAwareControl; - private BaseLdapPathAware ldapPathAwareMock; - private MockControl applicationContextControl; - private ApplicationContext applicationContextMock; - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { tested = new BaseLdapPathBeanPostProcessor(); - ldapPathAwareControl = MockControl.createControl(BaseLdapPathAware.class); - ldapPathAwareMock = (BaseLdapPathAware) ldapPathAwareControl.getMock(); + ldapPathAwareMock = mock(BaseLdapPathAware.class); - applicationContextControl = MockControl.createControl(ApplicationContext.class); - applicationContextMock = (ApplicationContext) applicationContextControl.getMock(); + applicationContextMock = mock(ApplicationContext.class); tested.setApplicationContext(applicationContextMock); } - protected void tearDown() throws Exception { - tested = null; - ldapPathAwareControl = null; - ldapPathAwareMock = null; - - applicationContextControl = null; - applicationContextMock = null; - } - + @Test public void testPostProcessBeforeInitializationWithLdapPathAwareBasePathSet() throws Exception { String expectedPath = "dc=example, dc=com"; tested.setBasePath(new DistinguishedName(expectedPath)); - ldapPathAwareMock.setBaseLdapPath(new DistinguishedName(expectedPath)); - - ldapPathAwareControl.replay(); - Object result = tested.postProcessBeforeInitialization(ldapPathAwareMock, "someName"); - ldapPathAwareControl.verify(); + verify(ldapPathAwareMock).setBaseLdapPath(new DistinguishedName(expectedPath)); assertSame(ldapPathAwareMock, result); } + @Test public void testPostProcessBeforeInitializationWithLdapPathAwareNoBasePathSet() throws Exception { final LdapContextSource expectedContextSource = new LdapContextSource(); String expectedPath = "dc=example, dc=com"; @@ -86,74 +74,48 @@ public class BaseLdapPathBeanPostProcessorTest extends TestCase { } }; - ldapPathAwareMock.setBaseLdapPath(new DistinguishedName(expectedPath)); - - ldapPathAwareControl.replay(); - Object result = tested.postProcessBeforeInitialization(ldapPathAwareMock, "someName"); - ldapPathAwareControl.verify(); + verify(ldapPathAwareMock).setBaseLdapPath(new DistinguishedName(expectedPath)); assertSame(ldapPathAwareMock, result); } + @Test public void testGetAbstractContextSourceFromApplicationContext() throws Exception { - applicationContextControl.expectAndReturn(applicationContextMock - .getBeanNamesForType(BaseLdapPathSource.class), new String[] { "contextSource" }); + when(applicationContextMock.getBeanNamesForType(BaseLdapPathSource.class)) + .thenReturn(new String[]{"contextSource"}); LdapContextSource expectedContextSource = new LdapContextSource(); - applicationContextControl.expectAndReturn(applicationContextMock.getBean("contextSource"), - expectedContextSource); - - applicationContextControl.replay(); + when(applicationContextMock.getBean("contextSource")).thenReturn(expectedContextSource); BaseLdapPathSource result = tested.getBaseLdapPathSourceFromApplicationContext(); - applicationContextControl.verify(); assertSame(expectedContextSource, result); } + @Test(expected = NoSuchBeanDefinitionException.class) public void testGetAbstractContextSourceFromApplicationContextNoContextSource() throws Exception { - applicationContextControl.expectAndReturn(applicationContextMock - .getBeanNamesForType(BaseLdapPathSource.class), new String[0]); + when(applicationContextMock.getBeanNamesForType(BaseLdapPathSource.class)) + .thenReturn(new String[0]); - applicationContextControl.replay(); - - try { - tested.getBaseLdapPathSourceFromApplicationContext(); - fail("NoSuchBeanDefinitionException expected"); - } - catch (NoSuchBeanDefinitionException expected) { - assertTrue(true); - } - applicationContextControl.verify(); - } + tested.getBaseLdapPathSourceFromApplicationContext(); + } + @Test(expected = NoSuchBeanDefinitionException.class) public void testGetAbstractContextSourceFromApplicationContextTwoContextSources() throws Exception { - applicationContextControl.expectAndReturn(applicationContextMock - .getBeanNamesForType(BaseLdapPathSource.class), new String[2]); + when(applicationContextMock + .getBeanNamesForType(BaseLdapPathSource.class)).thenReturn(new String[2]); - applicationContextControl.replay(); - - try { - tested.getBaseLdapPathSourceFromApplicationContext(); - fail("NoSuchBeanDefinitionException expected"); - } - catch (NoSuchBeanDefinitionException expected) { - assertTrue(true); - } - applicationContextControl.verify(); - } + tested.getBaseLdapPathSourceFromApplicationContext(); + } + @Test public void testGetAbstractContextSourceFromApplicationContextTwoContextSourcesAndSpecifiedName() throws Exception { LdapContextSource expectedContextSource = new LdapContextSource(); tested.setBaseLdapPathSourceName("myContextSource"); - applicationContextControl.expectAndReturn(applicationContextMock.getBean("myContextSource"), - expectedContextSource); - - applicationContextControl.replay(); + when(applicationContextMock.getBean("myContextSource")).thenReturn(expectedContextSource); tested.getBaseLdapPathSourceFromApplicationContext(); - applicationContextControl.verify(); } } diff --git a/core/src/test/java/org/springframework/ldap/core/support/CountNameClassPairResultCallbackHandlerTest.java b/core/src/test/java/org/springframework/ldap/core/support/CountNameClassPairResultCallbackHandlerTest.java index dcf8db25..9150b65c 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/CountNameClassPairResultCallbackHandlerTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/CountNameClassPairResultCallbackHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,30 +15,23 @@ */ package org.springframework.ldap.core.support; +import org.junit.Before; +import org.junit.Test; + import javax.naming.directory.SearchResult; -import org.springframework.ldap.core.support.CountNameClassPairCallbackHandler; +import static org.junit.Assert.assertEquals; +public class CountNameClassPairResultCallbackHandlerTest { -import junit.framework.TestCase; - -public class CountNameClassPairResultCallbackHandlerTest extends TestCase { - - private CountNameClassPairCallbackHandler tested; - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() throws Exception { tested = new CountNameClassPairCallbackHandler(); } - protected void tearDown() throws Exception { - super.tearDown(); - - tested = null; - } - + @Test public void testHandleSearchResult() throws Exception { SearchResult dummy = new SearchResult(null, null, null); tested.handleNameClassPair(dummy); diff --git a/core/src/test/java/org/springframework/ldap/core/support/DefaultDirObjectFactoryTest.java b/core/src/test/java/org/springframework/ldap/core/support/DefaultDirObjectFactoryTest.java index 67adead4..38c00a95 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/DefaultDirObjectFactoryTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/DefaultDirObjectFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,23 +15,24 @@ */ package org.springframework.ldap.core.support; -import java.util.Hashtable; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DistinguishedName; import javax.naming.CompositeName; import javax.naming.Context; import javax.naming.InvalidNameException; import javax.naming.Name; import javax.naming.directory.BasicAttributes; +import java.util.Hashtable; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; -import org.easymock.MockControl; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DistinguishedName; - -public class DefaultDirObjectFactoryTest extends TestCase { - - private MockControl contextControl; +public class DefaultDirObjectFactoryTest { private Context contextMock; @@ -41,107 +42,67 @@ public class DefaultDirObjectFactoryTest extends TestCase { private DefaultDirObjectFactory tested; - private MockControl contextControl2; - private Context contextMock2; - protected void setUp() throws Exception { - super.setUp(); - - contextControl = MockControl.createControl(Context.class); - contextMock = (Context) contextControl.getMock(); - - contextControl2 = MockControl.createControl(Context.class); - contextMock2 = (Context) contextControl2.getMock(); + @Before + public void setUp() throws Exception { + contextMock = mock(Context.class); + contextMock2 = mock(Context.class); tested = new DefaultDirObjectFactory(); } - protected void tearDown() throws Exception { - super.tearDown(); - - contextControl = null; - contextMock = null; - - contextControl2 = null; - contextMock2 = null; - - tested = null; - } - - protected void replay() { - contextControl.replay(); - contextControl2.replay(); - } - - protected void verify() { - contextControl.verify(); - contextControl2.verify(); - } - + @Test public void testGetObjectInstance() throws Exception { BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("someAttribute", "someValue"); - contextMock.close(); - - replay(); - DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, DN, null, new Hashtable(), expectedAttributes); - verify(); + verify(contextMock).close(); assertEquals(DN, adapter.getDn()); assertEquals(expectedAttributes, adapter.getAttributes()); } + @Test public void testGetObjectInstance_CompositeName() throws Exception { BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("someAttribute", "someValue"); - contextMock.close(); - - replay(); - CompositeName name = new CompositeName(); name.add(DN_STRING); DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, name, null, new Hashtable(), expectedAttributes); - verify(); + verify(contextMock).close(); assertEquals(DN, adapter.getDn()); assertEquals(expectedAttributes, adapter.getAttributes()); } + @Test public void testGetObjectInstance_nullObject() throws Exception { BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("someAttribute", "someValue"); - replay(); - DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(null, DN, null, new Hashtable(), expectedAttributes); - verify(); - assertEquals(DN, adapter.getDn()); assertEquals(expectedAttributes, adapter.getAttributes()); } + @Test public void testGetObjectInstance_ObjectNotContext() throws Exception { BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("someAttribute", "someValue"); - replay(); - DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(new Object(), DN, null, new Hashtable(), expectedAttributes); - verify(); - assertEquals(DN, adapter.getDn()); assertEquals(expectedAttributes, adapter.getAttributes()); } @@ -151,25 +112,24 @@ public class DefaultDirObjectFactoryTest extends TestCase { * * @throws Exception */ + @Test public void testGetObjectInstance_BaseSet() throws Exception { BasicAttributes expectedAttributes = new BasicAttributes(); expectedAttributes.put("someAttribute", "someValue"); - contextControl2.expectAndReturn(contextMock2.getNameInNamespace(), "dc=jayway, dc=se"); - contextMock.close(); - - replay(); + when(contextMock2.getNameInNamespace()).thenReturn("dc=jayway, dc=se"); DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, new DistinguishedName( "ou=some unit"), contextMock2, new Hashtable(), expectedAttributes); - verify(); + verify(contextMock).close(); assertEquals("ou=some unit", adapter.getDn().toString()); assertEquals("ou=some unit,dc=jayway,dc=se", adapter.getNameInNamespace()); assertEquals(expectedAttributes, adapter.getAttributes()); } + @Test public void testConstructAdapterFromName() throws InvalidNameException { CompositeName name = new CompositeName(); name.add("ldap://localhost:389/ou=People,o=JNDITutorial"); @@ -180,6 +140,7 @@ public class DefaultDirObjectFactoryTest extends TestCase { assertEquals("ldap://localhost:389", result.getReferralUrl().toString()); } + @Test public void testConstructAdapterFromName_Ldaps() throws InvalidNameException { CompositeName name = new CompositeName(); name.add("ldaps://localhost:389/ou=People,o=JNDITutorial"); @@ -190,6 +151,7 @@ public class DefaultDirObjectFactoryTest extends TestCase { assertEquals("ldaps://localhost:389", result.getReferralUrl().toString()); } + @Test public void testConstructAdapterFromName_EmptyName() throws InvalidNameException { CompositeName name = new CompositeName(); name.add("ldap://localhost:389"); @@ -200,7 +162,7 @@ public class DefaultDirObjectFactoryTest extends TestCase { assertEquals("ldap://localhost:389", result.getReferralUrl().toString()); } - + @Test public void testConstructAdapterFromName_OnlySlash() throws InvalidNameException { CompositeName name = new CompositeName(); name.add("ldap://localhost:389/"); diff --git a/core/src/test/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapperTest.java b/core/src/test/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapperTest.java index fc092d26..d69d17de 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapperTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapperTest.java @@ -16,34 +16,34 @@ package org.springframework.ldap.core.support; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + /** * IncrementalAttributesMapper Tester. * * @author Marius Scurtescu * @author Mattias Hellborg Arthursson */ -public class DefaultIncrementalAttributesMapperTest extends TestCase { +public class DefaultIncrementalAttributesMapperTest { private DefaultIncrementalAttributesMapper tested; - public DefaultIncrementalAttributesMapperTest(String name) { - super(name); - } - + @Before public void setUp() throws Exception { tested = new DefaultIncrementalAttributesMapper("member"); } - public void tearDown() throws Exception { - tested = null; - } - + @Test public void testGetAttributesArray() throws Exception { String[] attributes = tested.getAttributesForLookup(); @@ -58,6 +58,7 @@ public class DefaultIncrementalAttributesMapperTest extends TestCase { assertEquals("member;Range=0-10", attributes[0]); } + @Test public void testGetAttributesArrayWithTwoAttributes() { tested = new DefaultIncrementalAttributesMapper(20, new String[]{"member", "cn"}); String[] attributes = tested.getAttributesForLookup(); @@ -68,6 +69,7 @@ public class DefaultIncrementalAttributesMapperTest extends TestCase { assertEquals("cn;Range=0-20", attributes[1]); } + @Test public void testLoopEmpty() throws Exception { assertTrue(tested.hasMore()); @@ -79,6 +81,7 @@ public class DefaultIncrementalAttributesMapperTest extends TestCase { assertNull(tested.getValues("member")); } + @Test public void testLoop() throws Exception { Attributes attributes = createAttributes("member", new RangeOption(0, 10)); @@ -95,6 +98,7 @@ public class DefaultIncrementalAttributesMapperTest extends TestCase { assertEquals(16, tested.getValues("member").size()); } + @Test public void test1LoopWithPageSizeExact() throws Exception { tested = new DefaultIncrementalAttributesMapper(10, "member"); @@ -106,6 +110,7 @@ public class DefaultIncrementalAttributesMapperTest extends TestCase { assertEquals(11, tested.getValues("member").size()); } + @Test public void test2LoopsWithPageSizeExact() throws Exception { tested = new DefaultIncrementalAttributesMapper(20, "member"); @@ -124,6 +129,7 @@ public class DefaultIncrementalAttributesMapperTest extends TestCase { assertEquals(31, tested.getValues("member").size()); } + @Test public void test2LoopsWithPageSize() throws Exception { tested = new DefaultIncrementalAttributesMapper(20, "member"); @@ -142,6 +148,7 @@ public class DefaultIncrementalAttributesMapperTest extends TestCase { assertEquals(16, tested.getValues("member").size()); } + @Test public void testLoopWithTwoRangedAttributesLoopOnOneAttribute() throws Exception { tested = new DefaultIncrementalAttributesMapper(10, new String[]{"member", "cn"}); @@ -163,6 +170,7 @@ public class DefaultIncrementalAttributesMapperTest extends TestCase { assertFalse(tested.hasMore()); assertEquals(11, tested.getValues("member").size()); } + private Attributes createAttributes(String attributeName, RangeOption range) { return createAttributes(attributeName, range, range.getTerminal() - range.getInitial() + 1); } @@ -174,7 +182,6 @@ public class DefaultIncrementalAttributesMapperTest extends TestCase { attributes.put(attribute); return attributes; - } private Attribute createRangeAttribute(String attributeName, RangeOption range, int valueCnt) { diff --git a/core/src/test/java/org/springframework/ldap/core/support/LdapContextSourceTest.java b/core/src/test/java/org/springframework/ldap/core/support/LdapContextSourceTest.java index 5d5e0a34..5d028244 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/LdapContextSourceTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/LdapContextSourceTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,16 @@ package org.springframework.ldap.core.support; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.DistinguishedName; + +import javax.naming.Context; import java.util.HashMap; import java.util.Hashtable; -import javax.naming.Context; - -import junit.framework.TestCase; - -import org.springframework.ldap.core.DistinguishedName; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; /** * Unit tests for the LdapContextSource class. @@ -31,28 +33,21 @@ import org.springframework.ldap.core.DistinguishedName; * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ -public class LdapContextSourceTest extends TestCase { +public class LdapContextSourceTest { private LdapContextSource tested; - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { tested = new LdapContextSource(); } - protected void tearDown() throws Exception { - tested = null; - } - + @Test(expected = IllegalArgumentException.class) public void testAfterPropertiesSet_NoUrl() throws Exception { - try { - tested.afterPropertiesSet(); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException expected) { - assertTrue(true); - } - } + tested.afterPropertiesSet(); + } + @Test(expected = IllegalArgumentException.class) public void testAfterPropertiesSet_BaseAndTooEarlyJdk() throws Exception { tested = new LdapContextSource() { String getJdkVersion() { @@ -62,15 +57,10 @@ public class LdapContextSourceTest extends TestCase { tested.setUrl("http://ldap.example.com:389"); tested.setBase("dc=jayway,dc=se"); - try { - tested.afterPropertiesSet(); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException expected) { - assertTrue(true); - } - } + tested.afterPropertiesSet(); + } + @Test public void testGetAnonymousEnv() throws Exception { tested.setBase("dc=example,dc=se"); tested.setUrl("ldap://ldap.example.com:389"); @@ -101,6 +91,7 @@ public class LdapContextSourceTest extends TestCase { assertEquals(new DistinguishedName("dc=example,dc=se"), env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)); } + @Test public void testGetAnonymousEnvWithNoBaseSet() throws Exception { tested.setUrl("ldap://ldap.example.com:389"); tested.afterPropertiesSet(); @@ -111,6 +102,7 @@ public class LdapContextSourceTest extends TestCase { assertNull(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)); } + @Test public void testGetAnonymousEnvWithBaseEnvironment() throws Exception { tested.setUrl("ldap://ldap.example.com:389"); HashMap map = new HashMap(); @@ -122,6 +114,7 @@ public class LdapContextSourceTest extends TestCase { assertNull(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)); } + @Test public void testGetAnonymousEnvWithPoolingInBaseEnvironmentAndPoolingOff() throws Exception { tested.setUrl("ldap://ldap.example.com:389"); HashMap map = new HashMap(); @@ -134,6 +127,7 @@ public class LdapContextSourceTest extends TestCase { assertNull(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)); } + @Test public void testGetAnonymousEnvWithEmptyBaseSet() throws Exception { tested.setUrl("ldap://ldap.example.com:389"); tested.setBase(null); @@ -145,6 +139,7 @@ public class LdapContextSourceTest extends TestCase { assertNull(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)); } + @Test public void testOldJdkWithNoBaseSetShouldWork() throws Exception { tested = new LdapContextSource() { String getJdkVersion() { @@ -159,6 +154,7 @@ public class LdapContextSourceTest extends TestCase { assertNull(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)); } + @Test(expected = IllegalArgumentException.class) public void testOldJdkWithBaseSetShouldNotWork() throws Exception { tested = new LdapContextSource() { String getJdkVersion() { @@ -167,15 +163,10 @@ public class LdapContextSourceTest extends TestCase { }; tested.setUrl("ldap://ldap.example.com:389"); tested.setBase("dc=example,dc=com"); - try { - tested.afterPropertiesSet(); - fail("IllegalArgumentException expected"); - } - catch (IllegalArgumentException expected) { - assertTrue(true); - } - } + tested.afterPropertiesSet(); + } + @Test public void testOldJdkWithBaseSetToEmptyPathShouldWork() throws Exception { tested = new LdapContextSource() { String getJdkVersion() { @@ -191,6 +182,7 @@ public class LdapContextSourceTest extends TestCase { assertNull(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)); } + @Test public void testGetAuthenticatedEnv() throws Exception { tested.setBase("dc=example,dc=se"); tested.setUrl("ldap://ldap.example.com:389"); @@ -209,6 +201,7 @@ public class LdapContextSourceTest extends TestCase { assertEquals(new DistinguishedName("dc=example,dc=se"), env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)); } + @Test public void testGetAnonymousEnvWhenCacheIsOff() throws Exception { tested.setBase("dc=example,dc=se"); tested.setUrl("ldap://ldap.example.com:389"); diff --git a/core/src/test/java/org/springframework/ldap/core/support/RangeOptionTest.java b/core/src/test/java/org/springframework/ldap/core/support/RangeOptionTest.java index 52620097..2af694fa 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/RangeOptionTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/RangeOptionTest.java @@ -16,18 +16,21 @@ package org.springframework.ldap.core.support; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; /** * IncrementalAttributesMapper Tester. * * @author Marius Scurtescu */ -public class RangeOptionTest extends TestCase { - public RangeOptionTest(String name) { - super(name); - } +public class RangeOptionTest { + @Test public void testConstructorInvalid() { try { new RangeOption(101, 100); @@ -62,6 +65,7 @@ public class RangeOptionTest extends TestCase { } } + @Test public void testToString() throws Exception { RangeOption range = new RangeOption(0, 100); assertEquals("Range=0-100", range.toString()); @@ -73,6 +77,7 @@ public class RangeOptionTest extends TestCase { assertEquals("Range=0", range.toString()); } + @Test public void testParse() throws Exception { RangeOption range = RangeOption.parse("Range=0-100"); assertEquals(0, range.getInitial()); @@ -95,6 +100,7 @@ public class RangeOptionTest extends TestCase { assertEquals(RangeOption.TERMINAL_MISSING, range.getTerminal()); } + @Test public void testParseInvalid() { assertNull(RangeOption.parse("Range=10-")); assertNull(RangeOption.parse("Range=10-a")); @@ -105,6 +111,7 @@ public class RangeOptionTest extends TestCase { assertNull(RangeOption.parse("Range=10-100;lang-de")); } + @Test public void testCompare() { RangeOption range1 = RangeOption.parse("Range=10-500"); RangeOption range2 = RangeOption.parse("Range=10-500"); @@ -132,6 +139,7 @@ public class RangeOptionTest extends TestCase { assertTrue(range2.compareTo(range1) < 0); } + @Test public void testCompareInvalid() { RangeOption range1 = RangeOption.parse("Range=10-500"); RangeOption range2 = RangeOption.parse("Range=11-500"); @@ -167,6 +175,7 @@ public class RangeOptionTest extends TestCase { } } + @Test public void testNext() { RangeOption range = RangeOption.parse("Range=0-100"); diff --git a/core/src/test/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategyTest.java b/core/src/test/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategyTest.java index eb016fee..e231ff4f 100755 --- a/core/src/test/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategyTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategyTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,21 +15,24 @@ */ package org.springframework.ldap.core.support; -import java.util.Hashtable; +import org.junit.Before; +import org.junit.Test; import javax.naming.Context; +import java.util.Hashtable; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -public class SimpleDirContextAuthenticationStrategyTest extends TestCase { +public class SimpleDirContextAuthenticationStrategyTest { private SimpleDirContextAuthenticationStrategy tested; - protected void setUp() throws Exception { - super.setUp(); - + @Before + public void setUp() throws Exception { tested = new SimpleDirContextAuthenticationStrategy(); } + @Test public void testSetupEnvironment() { Hashtable env = new Hashtable(); tested.setupEnvironment(env, "cn=John Doe", "pw"); @@ -39,10 +42,13 @@ public class SimpleDirContextAuthenticationStrategyTest extends TestCase { assertEquals("pw", env.get(Context.SECURITY_CREDENTIALS)); } + @Test public void testProcessContextAfterCreation() { Hashtable env = new Hashtable(); tested.processContextAfterCreation(null, "cn=John Doe", "pw"); assertTrue(env.isEmpty()); } + + } diff --git a/core/src/test/java/org/springframework/ldap/filter/AbstractFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/AbstractFilterTest.java index 96f96634..a9b34902 100644 --- a/core/src/test/java/org/springframework/ldap/filter/AbstractFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/AbstractFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,29 +16,20 @@ package org.springframework.ldap.filter; -import org.springframework.ldap.filter.AbstractFilter; +import org.junit.Test; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** * @author Adam Skogman */ -public class AbstractFilterTest extends TestCase { - - /** - * Constructor for AbstractFilterTest. - * - * @param name - */ - public AbstractFilterTest(String name) { - super(name); - } +public class AbstractFilterTest { /* * Test for String encode() */ + @Test public void testEncode() { - AbstractFilter af = new AbstractFilter() { public StringBuffer encode(StringBuffer buff) { return buff.append("foo"); @@ -52,6 +43,7 @@ public class AbstractFilterTest extends TestCase { /* * Test for toString() */ + @Test public void testToString() { AbstractFilter af = new AbstractFilter() { diff --git a/core/src/test/java/org/springframework/ldap/filter/AndFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/AndFilterTest.java index f63436c4..baae8417 100644 --- a/core/src/test/java/org/springframework/ldap/filter/AndFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/AndFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,39 +16,31 @@ package org.springframework.ldap.filter; -import org.springframework.ldap.filter.AndFilter; -import org.springframework.ldap.filter.EqualsFilter; - import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** * @author Adam Skogman */ -public class AndFilterTest extends TestCase { - - /** - * Constructor for AndFilterTest. - * - * @param name - */ - public AndFilterTest(String name) { - super(name); - } +public class AndFilterTest { + @Test public void testZero() { AndFilter aq = new AndFilter(); assertEquals("", aq.encode()); } + @Test public void testOne() { AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")); assertEquals("(a=b)", aq.encode()); } + @Test public void testTwo() { AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")).and( new EqualsFilter("c", "d")); @@ -56,6 +48,7 @@ public class AndFilterTest extends TestCase { assertEquals("(&(a=b)(c=d))", aq.encode()); } + @Test public void testThree() { AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")).and( new EqualsFilter("c", "d")).and(new EqualsFilter("e", "f")); @@ -63,6 +56,7 @@ public class AndFilterTest extends TestCase { assertEquals("(&(a=b)(c=d)(e=f))", aq.encode()); } + @Test public void testEquals() { EqualsFilter filter = new EqualsFilter("a", "b"); AndFilter originalObject = new AndFilter().and(filter); diff --git a/core/src/test/java/org/springframework/ldap/filter/EqualsFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/EqualsFilterTest.java index a428b56a..ae14a24c 100644 --- a/core/src/test/java/org/springframework/ldap/filter/EqualsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/EqualsFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,26 +16,17 @@ package org.springframework.ldap.filter; -import org.springframework.ldap.filter.EqualsFilter; - import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** * @author Adam Skogman */ -public class EqualsFilterTest extends TestCase { - - /** - * Constructor for EqualsQueryTest. - * - * @param name - */ - public EqualsFilterTest(String name) { - super(name); - } +public class EqualsFilterTest { + @Test public void testEncode() { EqualsFilter eqq = new EqualsFilter("foo", "*bar(fie)"); @@ -47,6 +38,7 @@ public class EqualsFilterTest extends TestCase { } + @Test public void testEncodeInt() { EqualsFilter eqq = new EqualsFilter("foo", 456); @@ -58,6 +50,7 @@ public class EqualsFilterTest extends TestCase { } + @Test public void testEquals() { EqualsFilter originalObject = new EqualsFilter("a", "b"); EqualsFilter identicalObject = new EqualsFilter("a", "b"); diff --git a/core/src/test/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilterTest.java index d3e9de07..b1a2f052 100644 --- a/core/src/test/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,26 +16,17 @@ package org.springframework.ldap.filter; -import org.springframework.ldap.filter.GreaterThanOrEqualsFilter; - import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** * @author Mattias Hellborg Arthursson */ -public class GreaterThanOrEqualsFilterTest extends TestCase { - - /** - * Constructor for EqualsQueryTest. - * - * @param name - */ - public GreaterThanOrEqualsFilterTest(String name) { - super(name); - } +public class GreaterThanOrEqualsFilterTest { + @Test public void testEncode() { GreaterThanOrEqualsFilter eqq = new GreaterThanOrEqualsFilter("foo", @@ -48,6 +39,7 @@ public class GreaterThanOrEqualsFilterTest extends TestCase { } + @Test public void testEncodeInt() { GreaterThanOrEqualsFilter eqq = new GreaterThanOrEqualsFilter("foo", @@ -60,6 +52,7 @@ public class GreaterThanOrEqualsFilterTest extends TestCase { } + @Test public void testEquals() { String attribute = "a"; String value = "b"; diff --git a/core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java index 14887857..3e154ded 100644 --- a/core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,20 +15,19 @@ */ package org.springframework.ldap.filter; -import junit.framework.TestCase; - -import org.springframework.ldap.filter.AndFilter; -import org.springframework.ldap.filter.NotFilter; - import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; /** * Unit tests for the HardcodedFilter class. * * @author Ulrik Sandberg */ -public class HardcodedFilterTest extends TestCase { +public class HardcodedFilterTest { + @Test public void testHardcodedFilter() { HardcodedFilter filter = new HardcodedFilter("(foo=a*b)"); assertEquals("(foo=a*b)", filter.encode()); @@ -47,6 +46,7 @@ public class HardcodedFilterTest extends TestCase { assertEquals("(&(foo=a*b)(!(bar=a*b)))", andFilter.encode()); } + @Test public void testEquals() { String attribute = "(foo=a*b)"; HardcodedFilter originalObject = new HardcodedFilter(attribute); diff --git a/core/src/test/java/org/springframework/ldap/filter/LessThanOrEqualsFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/LessThanOrEqualsFilterTest.java index 66b847ba..7e7d0402 100644 --- a/core/src/test/java/org/springframework/ldap/filter/LessThanOrEqualsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/LessThanOrEqualsFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,26 +16,17 @@ package org.springframework.ldap.filter; -import org.springframework.ldap.filter.LessThanOrEqualsFilter; - import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** * @author Mattias Hellborg Arthursson */ -public class LessThanOrEqualsFilterTest extends TestCase { - - /** - * Constructor for EqualsQueryTest. - * - * @param name - */ - public LessThanOrEqualsFilterTest(String name) { - super(name); - } +public class LessThanOrEqualsFilterTest { + @Test public void testEncode() { LessThanOrEqualsFilter eqq = new LessThanOrEqualsFilter("foo", @@ -48,6 +39,7 @@ public class LessThanOrEqualsFilterTest extends TestCase { } + @Test public void testEncodeInt() { LessThanOrEqualsFilter eqq = new LessThanOrEqualsFilter("foo", 456); @@ -59,6 +51,7 @@ public class LessThanOrEqualsFilterTest extends TestCase { } + @Test public void testEquals() { String attribute = "a"; String value = "b"; diff --git a/core/src/test/java/org/springframework/ldap/filter/LikeFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/LikeFilterTest.java index d8f9530a..1b45ff35 100644 --- a/core/src/test/java/org/springframework/ldap/filter/LikeFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/LikeFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,30 +16,23 @@ package org.springframework.ldap.filter; -import org.springframework.ldap.filter.LikeFilter; - import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** * @author Anders Henja */ -public class LikeFilterTest extends TestCase { - /** - * Constructor for LikeFilterTest. - * - * @param name - */ - public LikeFilterTest(String name) { - super(name); - } +public class LikeFilterTest { + @Test public void testEncodeValue_blank() { assertEquals("", new LikeFilter("", null).getEncodedValue()); assertEquals(" ", new LikeFilter("", " ").getEncodedValue()); } + @Test public void testEncodeValue_normal() { assertEquals("foo", new LikeFilter("", "foo").getEncodedValue()); assertEquals("foo*bar", new LikeFilter("", "foo*bar").getEncodedValue()); @@ -49,12 +42,14 @@ public class LikeFilterTest extends TestCase { .getEncodedValue()); } + @Test public void testEncodeValue_escape() { assertEquals("*\\28*\\29*", new LikeFilter("", "*(*)*") .getEncodedValue()); assertEquals("*\\5c2a*", new LikeFilter("", "*\\2a*").getEncodedValue()); } + @Test public void testEquals() { String attribute = "a"; String value = "b"; diff --git a/core/src/test/java/org/springframework/ldap/filter/NotFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/NotFilterTest.java index f9506af6..221f1651 100644 --- a/core/src/test/java/org/springframework/ldap/filter/NotFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/NotFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,19 @@ package org.springframework.ldap.filter; -import org.springframework.ldap.filter.EqualsFilter; -import org.springframework.ldap.filter.NotFilter; - import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** * Unit tests for the NotFilter class. * * @author Mattias Hellborg Arthursson */ -public class NotFilterTest extends TestCase { +public class NotFilterTest { + @Test public void testConstructor() { EqualsFilter filter = new EqualsFilter("a", "b"); NotFilter notFilter = new NotFilter(filter); @@ -37,6 +36,7 @@ public class NotFilterTest extends TestCase { assertEquals("(!(a=b))", notFilter.encode()); } + @Test public void testEquals() { EqualsFilter filter = new EqualsFilter("a", "b"); NotFilter originalObject = new NotFilter(filter); diff --git a/core/src/test/java/org/springframework/ldap/filter/NotPresentFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/NotPresentFilterTest.java index e658e874..ef6c8516 100644 --- a/core/src/test/java/org/springframework/ldap/filter/NotPresentFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/NotPresentFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,20 +15,19 @@ */ package org.springframework.ldap.filter; -import junit.framework.TestCase; - -import org.springframework.ldap.filter.AndFilter; -import org.springframework.ldap.filter.NotFilter; - import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; /** * Unit tests for the NotPresentFilter class. * * @author Ulrik Sandberg */ -public class NotPresentFilterTest extends TestCase { +public class NotPresentFilterTest { + @Test public void testNotPresentFilter() { NotPresentFilter filter = new NotPresentFilter("foo"); assertEquals("(!(foo=*))", filter.encode()); @@ -47,6 +46,7 @@ public class NotPresentFilterTest extends TestCase { assertEquals("(&(!(foo=*))(!(!(bar=*))))", andFilter.encode()); } + @Test public void testEquals() { String attribute = "foo"; NotPresentFilter originalObject = new NotPresentFilter(attribute); diff --git a/core/src/test/java/org/springframework/ldap/filter/OrFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/OrFilterTest.java index 11840e24..f927bc78 100644 --- a/core/src/test/java/org/springframework/ldap/filter/OrFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/OrFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,39 +16,32 @@ package org.springframework.ldap.filter; -import org.springframework.ldap.filter.EqualsFilter; -import org.springframework.ldap.filter.OrFilter; +import org.junit.Test; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** * Unit tests for the OrFilter class. * * @author Adam Skogman */ -public class OrFilterTest extends TestCase { - - /** - * Constructor for OrFilterTest. - * - * @param name - */ - public OrFilterTest(String name) { - super(name); - } +public class OrFilterTest { + @Test public void testZero() { OrFilter of = new OrFilter(); assertEquals("", of.encode()); } + @Test public void testOne() { OrFilter of = new OrFilter().or(new EqualsFilter("a", "b")); assertEquals("(a=b)", of.encode()); } + @Test public void testTwo() { OrFilter of = new OrFilter().or(new EqualsFilter("a", "b")).or( new EqualsFilter("c", "d")); @@ -56,6 +49,7 @@ public class OrFilterTest extends TestCase { assertEquals("(|(a=b)(c=d))", of.encode()); } + @Test public void testThree() { OrFilter of = new OrFilter().or(new EqualsFilter("a", "b")).or( new EqualsFilter("c", "d")).or(new EqualsFilter("e", "f")); diff --git a/core/src/test/java/org/springframework/ldap/filter/PresentFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/PresentFilterTest.java index fc5bc8dd..209f047b 100644 --- a/core/src/test/java/org/springframework/ldap/filter/PresentFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/PresentFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,20 +15,19 @@ */ package org.springframework.ldap.filter; -import junit.framework.TestCase; - -import org.springframework.ldap.filter.AndFilter; -import org.springframework.ldap.filter.NotFilter; - import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; /** * Unit tests for the PresentFilter class. * * @author Ulrik Sandberg */ -public class PresentFilterTest extends TestCase { +public class PresentFilterTest { + @Test public void testPresentFilter() { PresentFilter filter = new PresentFilter("foo"); assertEquals("(foo=*)", filter.encode()); @@ -47,6 +46,7 @@ public class PresentFilterTest extends TestCase { assertEquals("(&(foo=*)(!(bar=*)))", andFilter.encode()); } + @Test public void testEquals() { String attribute = "foo"; PresentFilter originalObject = new PresentFilter(attribute); diff --git a/core/src/test/java/org/springframework/ldap/filter/WhitespaceWildcardsFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/WhitespaceWildcardsFilterTest.java index 64b6906a..128d8c4d 100644 --- a/core/src/test/java/org/springframework/ldap/filter/WhitespaceWildcardsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/WhitespaceWildcardsFilterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,18 @@ package org.springframework.ldap.filter; -import org.springframework.ldap.filter.WhitespaceWildcardsFilter; +import org.junit.Test; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; /** * Unit tests for the WhitespaceWildcardsFilter class. * * @author Adam Skogman */ -public class WhitespaceWildcardsFilterTest extends TestCase { - - public WhitespaceWildcardsFilterTest(String name) { - super(name); - } +public class WhitespaceWildcardsFilterTest { + @Test public void testEncodeValue_blank() { // blank @@ -45,6 +42,7 @@ public class WhitespaceWildcardsFilterTest extends TestCase { } + @Test public void testEncodeValue_normal() { assertEquals("*foo*", new WhitespaceWildcardsFilter("", "foo") @@ -58,6 +56,7 @@ public class WhitespaceWildcardsFilterTest extends TestCase { " \t foo \n bar \r ").getEncodedValue()); } + @Test public void testEncodeValue_escape() { assertEquals("*\\28\\2a\\29*", new WhitespaceWildcardsFilter("", "(*)") diff --git a/core/src/test/java/org/springframework/ldap/pool/AbstractPoolTestCase.java b/core/src/test/java/org/springframework/ldap/pool/AbstractPoolTestCase.java index 8e034d53..8a04f8d2 100644 --- a/core/src/test/java/org/springframework/ldap/pool/AbstractPoolTestCase.java +++ b/core/src/test/java/org/springframework/ldap/pool/AbstractPoolTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,109 +15,43 @@ */ package org.springframework.ldap.pool; +import org.apache.commons.pool.KeyedObjectPool; +import org.junit.Before; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.pool.validation.DirContextValidator; + import javax.naming.Context; import javax.naming.directory.DirContext; import javax.naming.ldap.LdapContext; -import org.apache.commons.pool.KeyedObjectPool; -import org.easymock.MockControl; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.pool.validation.DirContextValidator; - -import junit.framework.TestCase; +import static org.mockito.Mockito.mock; /** * Contains mocks common to many tests for the connection pool. * * @author Ulrik Sandberg */ -public abstract class AbstractPoolTestCase extends TestCase { - - protected MockControl contextControl; +public abstract class AbstractPoolTestCase { protected Context contextMock; - protected MockControl dirContextControl; - protected DirContext dirContextMock; - protected MockControl ldapContextControl; - protected LdapContext ldapContextMock; - protected MockControl keyedObjectPoolControl; - protected KeyedObjectPool keyedObjectPoolMock; - protected MockControl contextSourceControl; - protected ContextSource contextSourceMock; - protected MockControl dirContextValidatorControl; - protected DirContextValidator dirContextValidatorMock; - protected void setUp() throws Exception { - super.setUp(); - - contextControl = MockControl.createControl(Context.class); - contextMock = (Context) contextControl.getMock(); - - dirContextControl = MockControl.createControl(DirContext.class); - dirContextMock = (DirContext) dirContextControl.getMock(); - - ldapContextControl = MockControl.createControl(LdapContext.class); - ldapContextMock = (LdapContext) ldapContextControl.getMock(); - - keyedObjectPoolControl = MockControl - .createControl(KeyedObjectPool.class); - keyedObjectPoolMock = (KeyedObjectPool) keyedObjectPoolControl - .getMock(); - - contextSourceControl = MockControl.createControl(ContextSource.class); - contextSourceMock = (ContextSource) contextSourceControl.getMock(); - - dirContextValidatorControl = MockControl.createControl(DirContextValidator.class); - dirContextValidatorMock = (DirContextValidator) dirContextValidatorControl.getMock(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - - contextControl = null; - contextMock = null; - - dirContextControl = null; - dirContextMock = null; - - ldapContextControl = null; - ldapContextMock = null; - - keyedObjectPoolControl = null; - keyedObjectPoolMock = null; - - contextSourceControl = null; - contextSourceMock = null; - - dirContextValidatorControl = null; - dirContextValidatorMock = null; - } - - protected void replay() { - contextControl.replay(); - dirContextControl.replay(); - ldapContextControl.replay(); - keyedObjectPoolControl.replay(); - contextSourceControl.replay(); - dirContextValidatorControl.replay(); - } - - protected void verify() { - contextControl.verify(); - dirContextControl.verify(); - ldapContextControl.verify(); - keyedObjectPoolControl.verify(); - contextSourceControl.verify(); - dirContextValidatorControl.verify(); + @Before + public void setUp() throws Exception { + contextMock = mock(Context.class); + dirContextMock = mock(DirContext.class); + ldapContextMock = mock(LdapContext.class); + keyedObjectPoolMock = mock(KeyedObjectPool.class); + contextSourceMock = mock(ContextSource.class); + dirContextValidatorMock = mock(DirContextValidator.class); } } diff --git a/core/src/test/java/org/springframework/ldap/pool/DelegatingContextTest.java b/core/src/test/java/org/springframework/ldap/pool/DelegatingContextTest.java index 82026565..2416ee26 100644 --- a/core/src/test/java/org/springframework/ldap/pool/DelegatingContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/DelegatingContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,22 @@ */ package org.springframework.ldap.pool; +import org.apache.commons.pool.KeyedObjectPool; +import org.junit.Test; + import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; -import org.apache.commons.pool.KeyedObjectPool; -import org.easymock.MockControl; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * @author Eric Dalquist eric.dalquist@doit.wisc.edu */ public class DelegatingDirContextTest extends AbstractPoolTestCase { + @Test public void testConstructorAssertions() { - replay(); - try { new DelegatingDirContext(keyedObjectPoolMock, null, DirContextType.READ_ONLY); @@ -46,16 +54,10 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { } catch (IllegalArgumentException expected) { assertTrue(true); } - - verify(); } + @Test public void testHelperMethods() throws Exception { - keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, - dirContextMock); - keyedObjectPoolControl.setVoidCallable(1); - - replay(); // Wrap the DirContext once final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( @@ -76,14 +78,7 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { delegatingDirContext.assertOpen(); // Wrap the wrapper - MockControl secondKeyedObjectPoolControl = MockControl - .createControl(KeyedObjectPool.class); - KeyedObjectPool secondKeyedObjectPoolMock = (KeyedObjectPool) secondKeyedObjectPoolControl - .getMock(); - secondKeyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, - delegatingDirContext); - secondKeyedObjectPoolControl.setVoidCallable(1); - secondKeyedObjectPoolControl.replay(); + KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class); final DelegatingDirContext delegatingDirContext2 = new DelegatingDirContext( secondKeyedObjectPoolMock, delegatingDirContext, @@ -135,23 +130,17 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { // Expected } - secondKeyedObjectPoolControl.verify(); - verify(); + verify(secondKeyedObjectPoolMock) + .returnObject(DirContextType.READ_ONLY, dirContextMock); + verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, dirContextMock); } + @Test public void testObjectMethods() throws Exception { - keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, - dirContextMock); - keyedObjectPoolControl.setVoidCallable(1); - - replay(); - // Wrap the DirContext once final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); - assertEquals( - "EasyMock for interface javax.naming.directory.DirContext", - delegatingDirContext.toString()); + assertEquals(dirContextMock.toString(), delegatingDirContext.toString()); delegatingDirContext.hashCode(); // Run it to make sure it doesn't // fail @@ -179,13 +168,11 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { assertFalse(delegatingDirContext2.equals(delegatingDirContext)); assertFalse(delegatingDirContext.equals(dirContextMock)); - verify(); + verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, dirContextMock); } - // nice + @Test public void testUnsupportedMethods() throws Exception { - replay(); - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); @@ -225,17 +212,10 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { } catch (UnsupportedOperationException uoe) { // Expected } - - verify(); } + @Test public void testAllMethodsOpened() throws Exception { - // override with a nice control - dirContextControl = MockControl.createNiceControl(DirContext.class); - dirContextMock = (DirContext) dirContextControl.getMock(); - - replay(); - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); @@ -259,17 +239,10 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { delegatingDirContext.search((String) null, null); delegatingDirContext.search((String) null, null, null, null); delegatingDirContext.search((String) null, (String) null, null); - - verify(); } + @Test public void testAllMethodsClosed() throws Exception { - keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, - dirContextMock); - keyedObjectPoolControl.setVoidCallable(1); - - replay(); - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); @@ -396,16 +369,11 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { // Expected } - verify(); + verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, dirContextMock); } + @Test public void testDoubleClose() throws Exception { - keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, - dirContextMock); - keyedObjectPoolControl.setVoidCallable(1); - - replay(); - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); @@ -414,6 +382,6 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { // noop close delegatingDirContext.close(); - verify(); + verify(keyedObjectPoolMock, times(1)).returnObject(DirContextType.READ_ONLY, dirContextMock); } } \ No newline at end of file diff --git a/core/src/test/java/org/springframework/ldap/pool/DelegatingLdapContextTest.java b/core/src/test/java/org/springframework/ldap/pool/DelegatingLdapContextTest.java index a2144082..15c6b1ab 100644 --- a/core/src/test/java/org/springframework/ldap/pool/DelegatingLdapContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/DelegatingLdapContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,21 +15,29 @@ */ package org.springframework.ldap.pool; +import org.apache.commons.pool.KeyedObjectPool; +import org.junit.Test; + import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.ldap.LdapContext; -import org.apache.commons.pool.KeyedObjectPool; -import org.easymock.MockControl; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; /** * @author Eric Dalquist eric.dalquist@doit.wisc.edu */ public class DelegatingLdapContextTest extends AbstractPoolTestCase { + @Test public void testConstructorAssertions() { - replay(); - try { new DelegatingLdapContext(keyedObjectPoolMock, null, DirContextType.READ_ONLY); @@ -45,17 +53,10 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { } catch (IllegalArgumentException expected) { assertTrue(true); } - - verify(); } + @Test public void testHelperMethods() throws Exception { - keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, - ldapContextMock); - keyedObjectPoolControl.setVoidCallable(1); - - replay(); - // Wrap the LdapContext once final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); @@ -75,15 +76,7 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { delegatingLdapContext.assertOpen(); // Wrap the wrapper - MockControl secondKeyedObjectPoolControl = MockControl - .createControl(KeyedObjectPool.class); - KeyedObjectPool secondKeyedObjectPoolMock = (KeyedObjectPool) secondKeyedObjectPoolControl - .getMock(); - - secondKeyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, - delegatingLdapContext); - secondKeyedObjectPoolControl.setVoidCallable(1); - secondKeyedObjectPoolControl.replay(); + KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class); final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext( secondKeyedObjectPoolMock, delegatingLdapContext, @@ -135,21 +128,17 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { // Expected } - secondKeyedObjectPoolControl.verify(); - verify(); + verify(secondKeyedObjectPoolMock) + .returnObject(DirContextType.READ_ONLY, ldapContextMock); + verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); } + @Test public void testObjectMethods() throws Exception { - keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, - ldapContextMock); - keyedObjectPoolControl.setVoidCallable(1); - - replay(); - // Wrap the LdapContext once final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); - assertEquals("EasyMock for interface javax.naming.ldap.LdapContext", + assertEquals(ldapContextMock.toString(), delegatingLdapContext.toString()); delegatingLdapContext.hashCode(); // Run it to make sure it doesn't fail @@ -177,12 +166,11 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { assertFalse(delegatingLdapContext2.equals(delegatingLdapContext)); assertFalse(delegatingLdapContext.equals(ldapContextMock)); - verify(); + verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); } + @Test public void testUnsupportedMethods() throws Exception { - replay(); - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); @@ -204,18 +192,11 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { } catch (UnsupportedOperationException uoe) { // Expected } - - verify(); } // nice + @Test public void testAllMethodsOpened() throws Exception { - MockControl ldapContextControl = MockControl.createNiceControl(LdapContext.class); - LdapContext ldapContextMock = (LdapContext) ldapContextControl.getMock(); - - ldapContextControl.replay(); - replay(); - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); @@ -223,18 +204,10 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { delegatingLdapContext.getConnectControls(); delegatingLdapContext.getRequestControls(); delegatingLdapContext.getResponseControls(); - - ldapContextControl.verify(); - verify(); } + @Test public void testAllMethodsClosed() throws Exception { - keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, - ldapContextMock); - keyedObjectPoolControl.setVoidCallable(1); - - replay(); - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); @@ -264,16 +237,12 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { } catch (NamingException ne) { // Expected } - verify(); + + verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); } + @Test public void testDoubleClose() throws Exception { - keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, - ldapContextMock); - keyedObjectPoolControl.setVoidCallable(1); - - replay(); - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); @@ -282,6 +251,6 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { // noop close delegatingLdapContext.close(); - verify(); + verify(keyedObjectPoolMock, times(1)).returnObject(DirContextType.READ_ONLY, ldapContextMock); } } diff --git a/core/src/test/java/org/springframework/ldap/pool/MutableDelegatingLdapContextTest.java b/core/src/test/java/org/springframework/ldap/pool/MutableDelegatingLdapContextTest.java index 02293b70..109cde76 100644 --- a/core/src/test/java/org/springframework/ldap/pool/MutableDelegatingLdapContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/MutableDelegatingLdapContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,21 +15,23 @@ */ package org.springframework.ldap.pool; +import org.junit.Test; + +import static org.mockito.Mockito.verify; + /** * Unit tests for the MutableDelegatingLdapContext class. * * @author Ulrik Sandberg */ public class MutableDelegatingLdapContextTest extends AbstractPoolTestCase { + @Test public void testSupportedMethodsAllowedToCall() throws Exception { - ldapContextMock.setRequestControls(null); - replay(); - final MutableDelegatingLdapContext delegatingLdapContext = new MutableDelegatingLdapContext( keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); delegatingLdapContext.setRequestControls(null); - verify(); + verify(ldapContextMock).setRequestControls(null); } } diff --git a/core/src/test/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactoryTest.java b/core/src/test/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactoryTest.java index 5a268b29..d11ea9b0 100644 --- a/core/src/test/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactoryTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,24 +15,33 @@ */ package org.springframework.ldap.pool.factory; -import javax.naming.directory.DirContext; - -import org.easymock.MockControl; +import org.junit.Test; +import org.mockito.Mockito; import org.springframework.ldap.core.ContextSource; import org.springframework.ldap.pool.AbstractPoolTestCase; import org.springframework.ldap.pool.DirContextType; import org.springframework.ldap.pool.validation.DirContextValidator; +import javax.naming.directory.DirContext; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + /** * @author Eric Dalquist */ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { + @Test public void testProperties() throws Exception { final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory(); - replay(); - try { objectFactory.setContextSource(null); fail("DirContextPoolableObjectFactory.setContextSource should have thrown an IllegalArgumentException"); @@ -57,14 +66,12 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { objectFactory.setDirContextValidator(dirContextValidatorMock); final DirContextValidator dirContextValidator2 = objectFactory.getDirContextValidator(); assertEquals(dirContextValidatorMock, dirContextValidator2); - verify(); } - + + @Test public void testMakeObjectAssertions() throws Exception { final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory(); - replay(); - try { objectFactory.makeObject(DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); @@ -80,55 +87,39 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { } catch (IllegalArgumentException expected) { assertTrue(true); } - - verify(); } - + + @Test public void testMakeObjectReadOnly() throws Exception { final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory(); - MockControl readOnlyContextControl = MockControl.createControl(DirContext.class); - DirContext readOnlyContextMock = (DirContext) readOnlyContextControl.getMock(); + DirContext readOnlyContextMock = mock(DirContext.class); - readOnlyContextControl.replay(); - - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), readOnlyContextMock, 1); + when(contextSourceMock.getReadOnlyContext()).thenReturn(readOnlyContextMock); objectFactory.setContextSource(contextSourceMock); - replay(); - final Object createdDirContext = objectFactory.makeObject(DirContextType.READ_ONLY); - - readOnlyContextControl.verify(); - verify(); assertEquals(readOnlyContextMock, createdDirContext); } - + + @Test public void testMakeObjectReadWrite() throws Exception { final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory(); - MockControl readWriteContextControl = MockControl.createControl(DirContext.class); - DirContext readWriteContextMock = (DirContext) readWriteContextControl.getMock(); + DirContext readWriteContextMock = mock(DirContext.class); - readWriteContextControl.replay(); - - contextSourceControl.expectAndReturn(contextSourceMock.getReadWriteContext(), readWriteContextMock, 1); + when(contextSourceMock.getReadWriteContext()).thenReturn(readWriteContextMock); objectFactory.setContextSource(contextSourceMock); - replay(); - + final Object createdDirContext = objectFactory.makeObject(DirContextType.READ_WRITE); - - readWriteContextControl.verify(); - verify(); assertEquals(readWriteContextMock, createdDirContext); } + @Test public void testValidateObjectAssertions() throws Exception { final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory(); - replay(); - try { objectFactory.validateObject(DirContextType.READ_ONLY, dirContextMock); fail("IllegalArgumentException expected"); @@ -165,17 +156,14 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { } catch (IllegalArgumentException expected) { assertTrue(true); } - - verify(); } - - public void testValidateObject() throws Exception { - dirContextValidatorControl.expectAndReturn(dirContextValidatorMock - .validateDirContext(DirContextType.READ_ONLY, dirContextMock), - true); - replay(); - + @Test + public void testValidateObject() throws Exception { + when(dirContextValidatorMock + .validateDirContext(DirContextType.READ_ONLY, dirContextMock)) + .thenReturn(true); + final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory(); objectFactory.setDirContextValidator(dirContextValidatorMock); @@ -183,25 +171,20 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { assertTrue(valid); //Check exception in validator - MockControl secondDirContextValidatorControl = MockControl.createControl(DirContextValidator.class); - DirContextValidator secondDirContextValidatorMock = (DirContextValidator) secondDirContextValidatorControl.getMock(); + DirContextValidator secondDirContextValidatorMock = mock(DirContextValidator.class); - secondDirContextValidatorControl.expectAndThrow(secondDirContextValidatorMock.validateDirContext(DirContextType.READ_ONLY, dirContextMock), new RuntimeException("Failed to validate")); - secondDirContextValidatorControl.replay(); + when(secondDirContextValidatorMock.validateDirContext(DirContextType.READ_ONLY, dirContextMock)) + .thenThrow(new RuntimeException("Failed to validate")); objectFactory.setDirContextValidator(secondDirContextValidatorMock); final boolean valid2 = objectFactory.validateObject(DirContextType.READ_ONLY, dirContextMock); assertFalse(valid2); - - secondDirContextValidatorControl.verify(); - verify(); } - + + @Test public void testDestroyObjectAssertions() throws Exception { final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory(); - replay(); - try { objectFactory.destroyObject(DirContextType.READ_ONLY, null); fail("IllegalArgumentException expected"); @@ -215,29 +198,20 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { } catch (IllegalArgumentException expected) { assertTrue(true); } - - verify(); } - + + @Test public void testDestroyObject() throws Exception { - dirContextMock.close(); - dirContextControl.setVoidCallable(1); - - replay(); - final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory(); objectFactory.destroyObject(DirContextType.READ_ONLY, dirContextMock); - MockControl throwingDirContextControl = MockControl.createControl(DirContext.class); - DirContext throwingDirContextMock = (DirContext) throwingDirContextControl.getMock(); + DirContext throwingDirContextMock = Mockito.mock(DirContext.class); + + doThrow(new RuntimeException("Failed to close")) + .when(throwingDirContextMock).close(); - throwingDirContextMock.close(); - throwingDirContextControl.setThrowable(new RuntimeException("Failed to close")); - throwingDirContextControl.replay(); - objectFactory.destroyObject(DirContextType.READ_ONLY, throwingDirContextMock); - throwingDirContextControl.verify(); - verify(); + verify(dirContextMock).close(); } } diff --git a/core/src/test/java/org/springframework/ldap/pool/factory/MutablePoolingContextSourceTest.java b/core/src/test/java/org/springframework/ldap/pool/factory/MutablePoolingContextSourceTest.java index 112fe55d..f861dcc4 100644 --- a/core/src/test/java/org/springframework/ldap/pool/factory/MutablePoolingContextSourceTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/factory/MutablePoolingContextSourceTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,15 @@ */ package org.springframework.ldap.pool.factory; -import javax.naming.directory.DirContext; - +import org.junit.Test; import org.springframework.ldap.pool.AbstractPoolTestCase; import org.springframework.ldap.pool.MutableDelegatingLdapContext; +import javax.naming.directory.DirContext; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + /** * Unit tests for the MutablePoolingContextSource class. * @@ -27,20 +31,17 @@ import org.springframework.ldap.pool.MutableDelegatingLdapContext; */ public class MutablePoolingContextSourceTest extends AbstractPoolTestCase { + @Test public void testGetReadOnlyLdapContext() throws Exception { - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), ldapContextMock); - - replay(); + when(contextSourceMock.getReadOnlyContext()).thenReturn(ldapContextMock); final MutablePoolingContextSource poolingContextSource = new MutablePoolingContextSource(); poolingContextSource.setContextSource(contextSourceMock); // Get a context final DirContext result = poolingContextSource.getReadOnlyContext(); - - verify(); - + assertEquals(MutableDelegatingLdapContext.class, result.getClass()); } } diff --git a/core/src/test/java/org/springframework/ldap/pool/factory/PoolingContextSourceTest.java b/core/src/test/java/org/springframework/ldap/pool/factory/PoolingContextSourceTest.java index 71e0eb56..c11ab2b1 100644 --- a/core/src/test/java/org/springframework/ldap/pool/factory/PoolingContextSourceTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/factory/PoolingContextSourceTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,26 +15,30 @@ */ package org.springframework.ldap.pool.factory; -import javax.naming.directory.DirContext; -import javax.naming.ldap.LdapContext; - import org.apache.commons.pool.impl.GenericKeyedObjectPool; -import org.easymock.MockControl; +import org.junit.Test; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.ldap.core.ContextSource; import org.springframework.ldap.pool.AbstractPoolTestCase; import org.springframework.ldap.pool.validation.DirContextValidator; +import javax.naming.directory.DirContext; +import javax.naming.ldap.LdapContext; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** * @author Eric Dalquist */ public class PoolingContextSourceTest extends AbstractPoolTestCase { - + + @Test public void testProperties() throws Exception { final PoolingContextSource poolingContextSource = new PoolingContextSource(); - - replay(); - + try { poolingContextSource.setContextSource(null); fail("PoolingContextSource.setBaseName should have thrown an IllegalArgumentException"); @@ -112,15 +116,12 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { assertEquals(0, numIdle); } + @Test public void testGetReadOnlyContextPool() throws Exception { - MockControl secondDirContextControl = MockControl.createControl(DirContext.class); - DirContext secondDirContextMock = (DirContext) secondDirContextControl.getMock(); - - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), dirContextMock); - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), secondDirContextMock); - - replay(); + DirContext secondDirContextMock = mock(DirContext.class); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock, secondDirContextMock); + final PoolingContextSource poolingContextSource = new PoolingContextSource(); poolingContextSource.setContextSource(contextSourceMock); @@ -157,16 +158,13 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { assertEquals(0, poolingContextSource.getNumActive()); assertEquals(2, poolingContextSource.getNumIdle()); } - + + @Test public void testGetReadWriteContextPool() throws Exception { - MockControl secondDirContextControl = MockControl.createControl(DirContext.class); - DirContext secondDirContextMock = (DirContext) secondDirContextControl.getMock(); - - contextSourceControl.expectAndReturn(contextSourceMock.getReadWriteContext(), dirContextMock); - contextSourceControl.expectAndReturn(contextSourceMock.getReadWriteContext(), secondDirContextMock); - - replay(); + DirContext secondDirContextMock = mock(DirContext.class); + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock, secondDirContextMock); + final PoolingContextSource poolingContextSource = new PoolingContextSource(); poolingContextSource.setContextSource(contextSourceMock); @@ -204,11 +202,11 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { assertEquals(2, poolingContextSource.getNumIdle()); } + @Test public void testGetContextException() throws Exception { - contextSourceControl.expectAndThrow(contextSourceMock.getReadWriteContext(), new RuntimeException("Problem getting context")); - - replay(); - + when(contextSourceMock.getReadWriteContext()) + .thenThrow(new RuntimeException("Problem getting context")); + final PoolingContextSource poolingContextSource = new PoolingContextSource(); poolingContextSource.setContextSource(contextSourceMock); @@ -221,17 +219,12 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { } } + @Test public void testGetReadOnlyLdapContext() throws Exception { - MockControl secondLdapContextControl = MockControl.createControl(LdapContext.class); - LdapContext secondLdapContextMock = (LdapContext) secondLdapContextControl.getMock(); + LdapContext secondLdapContextMock = mock(LdapContext.class); + + when(contextSourceMock.getReadOnlyContext()).thenReturn(ldapContextMock, secondLdapContextMock); - secondLdapContextControl.replay(); - - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), ldapContextMock); - contextSourceControl.expectAndReturn(contextSourceMock.getReadOnlyContext(), secondLdapContextMock); - - replay(); - final PoolingContextSource poolingContextSource = new PoolingContextSource(); poolingContextSource.setContextSource(contextSourceMock); @@ -267,7 +260,5 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { readOnlyContext3.close(); assertEquals(0, poolingContextSource.getNumActive()); assertEquals(2, poolingContextSource.getNumIdle()); - - secondLdapContextControl.verify(); } } diff --git a/core/src/test/java/org/springframework/ldap/pool/validation/DefaultDirContextValidatorTest.java b/core/src/test/java/org/springframework/ldap/pool/validation/DefaultDirContextValidatorTest.java index a9fd2230..44756718 100644 --- a/core/src/test/java/org/springframework/ldap/pool/validation/DefaultDirContextValidatorTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/validation/DefaultDirContextValidatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,79 +15,60 @@ */ package org.springframework.ldap.pool.validation; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.pool.DirContextType; + import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.SearchControls; -import junit.framework.TestCase; - -import org.easymock.MockControl; -import org.springframework.ldap.pool.DirContextType; -import org.springframework.ldap.pool.validation.DefaultDirContextValidator; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * @author Eric Dalquist eric.dalquist@doit.wisc.edu */ -public class DefaultDirContextValidatorTest extends TestCase { - - private MockControl namingEnumerationControl; +public class DefaultDirContextValidatorTest { private NamingEnumeration namingEnumerationMock; - private MockControl dirContextControl; - private DirContext dirContextMock; - protected void setUp() throws Exception { - super.setUp(); - namingEnumerationControl = MockControl - .createControl(NamingEnumeration.class); - namingEnumerationMock = (NamingEnumeration) namingEnumerationControl - .getMock(); - - dirContextControl = MockControl.createControl(DirContext.class); - dirContextMock = (DirContext) dirContextControl.getMock(); + @Before + public void setUp() throws Exception { + namingEnumerationMock = mock(NamingEnumeration.class); + dirContextMock = mock(DirContext.class); } - protected void tearDown() throws Exception { - super.tearDown(); - namingEnumerationControl = null; - namingEnumerationMock = null; - - dirContextControl = null; - dirContextMock = null; - } - - protected void replay() { - namingEnumerationControl.replay(); - dirContextControl.replay(); - } - - protected void verify() { - namingEnumerationControl.verify(); - dirContextControl.verify(); - } - // LDAP-189 + @Test public void testSearchScopeOneLevelScopeSetInConstructorIsUsed() throws Exception { DefaultDirContextValidator tested = new DefaultDirContextValidator(SearchControls.ONELEVEL_SCOPE); assertEquals("ONELEVEL_SCOPE, ", SearchControls.ONELEVEL_SCOPE, tested.getSearchControls().getSearchScope()); } // LDAP-189 + @Test public void testSearchScopeSubTreeScopeSetInConstructorIsUsed() throws Exception { DefaultDirContextValidator tested = new DefaultDirContextValidator(SearchControls.SUBTREE_SCOPE); assertEquals("SUBTREE_SCOPE, ", SearchControls.SUBTREE_SCOPE, tested.getSearchControls().getSearchScope()); } // LDAP-189 + @Test public void testSearchScopeObjectScopeSetInConstructorIsUsed() throws Exception { DefaultDirContextValidator tested = new DefaultDirContextValidator(SearchControls.OBJECT_SCOPE); assertEquals("OBJECT_SCOPE, ", SearchControls.OBJECT_SCOPE, tested.getSearchControls().getSearchScope()); } - + + @Test public void testProperties() throws Exception { final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); @@ -117,6 +98,7 @@ public class DefaultDirContextValidatorTest extends TestCase { assertEquals(sc, sc2); } + @Test public void testValidateDirContextAssertions() throws Exception { final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); @@ -128,8 +110,6 @@ public class DefaultDirContextValidatorTest extends TestCase { assertTrue(true); } - replay(); - try { dirContextValidator.validateDirContext(null, dirContextMock); fail("IllegalArgumentException expected"); @@ -138,6 +118,7 @@ public class DefaultDirContextValidatorTest extends TestCase { } } + @Test public void testValidateDirContextHasResult() throws Exception { final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); @@ -146,20 +127,16 @@ public class DefaultDirContextValidatorTest extends TestCase { final SearchControls searchControls = dirContextValidator .getSearchControls(); - namingEnumerationControl.expectAndReturn(namingEnumerationMock - .hasMore(), true); - dirContextControl.expectAndReturn(dirContextMock.search(baseName, - filter, searchControls), namingEnumerationMock); - - replay(); + when(namingEnumerationMock.hasMore()).thenReturn(true); + when(dirContextMock.search(baseName, filter, searchControls)) + .thenReturn(namingEnumerationMock); final boolean valid = dirContextValidator.validateDirContext( DirContextType.READ_ONLY, dirContextMock); - - verify(); assertTrue(valid); } + @Test public void testValidateDirContextNoResult() throws Exception { final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); @@ -168,20 +145,17 @@ public class DefaultDirContextValidatorTest extends TestCase { final SearchControls searchControls = dirContextValidator .getSearchControls(); - namingEnumerationControl.expectAndReturn(namingEnumerationMock - .hasMore(), false); - dirContextControl.expectAndReturn(dirContextMock.search(baseName, - filter, searchControls), namingEnumerationMock); - - replay(); + when(namingEnumerationMock.hasMore()).thenReturn(false); + when(dirContextMock.search(baseName, filter, searchControls)) + .thenReturn(namingEnumerationMock); final boolean valid = dirContextValidator.validateDirContext( DirContextType.READ_ONLY, dirContextMock); - verify(); assertFalse(valid); } + @Test public void testValidateDirContextException() throws Exception { final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); @@ -190,16 +164,12 @@ public class DefaultDirContextValidatorTest extends TestCase { final SearchControls searchControls = dirContextValidator .getSearchControls(); - dirContextControl.expectAndThrow(dirContextMock.search(baseName, - filter, searchControls), - new NamingException("Failed to search")); - - replay(); + when(dirContextMock.search(baseName, filter, searchControls)) + .thenThrow(new NamingException("Failed to search")); final boolean valid = dirContextValidator.validateDirContext( DirContextType.READ_ONLY, dirContextMock); - verify(); assertFalse(valid); } } diff --git a/core/src/test/java/org/springframework/ldap/support/LdapUtilsTest.java b/core/src/test/java/org/springframework/ldap/support/LdapUtilsTest.java index ad3d3215..f1191459 100644 --- a/core/src/test/java/org/springframework/ldap/support/LdapUtilsTest.java +++ b/core/src/test/java/org/springframework/ldap/support/LdapUtilsTest.java @@ -1,36 +1,46 @@ +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.ldap.support; -import java.util.LinkedList; +import org.apache.commons.lang.ArrayUtils; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.NoSuchAttributeException; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; +import java.util.LinkedList; -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; -import org.apache.commons.lang.ArrayUtils; -import org.easymock.MockControl; -import org.springframework.ldap.NoSuchAttributeException; - -public class LdapUtilsTest extends TestCase { - - private MockControl handlerControl; +public class LdapUtilsTest { private AttributeValueCallbackHandler handlerMock; - protected void setUp() throws Exception { - super.setUp(); - - handlerControl = MockControl.createControl(AttributeValueCallbackHandler.class); - handlerMock = (AttributeValueCallbackHandler) handlerControl.getMock(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - - handlerControl = null; - handlerMock = null; + @Before + public void setUp() throws Exception { + handlerMock = mock(AttributeValueCallbackHandler.class); } + @Test public void testCollectAttributeValues() { String expectedAttributeName = "someAttribute"; BasicAttribute expectedAttribute = new BasicAttribute(expectedAttributeName); @@ -48,6 +58,7 @@ public class LdapUtilsTest extends TestCase { assertEquals("value2", list.get(1)); } + @Test public void testCollectAttributeValuesThrowsExceptionWhenAttributeNotPresent() { String expectedAttributeName = "someAttribute"; BasicAttributes attributes = new BasicAttributes(); @@ -62,6 +73,7 @@ public class LdapUtilsTest extends TestCase { } } + @Test public void testIterateAttributeValues() { String expectedAttributeName = "someAttribute"; @@ -69,31 +81,25 @@ public class LdapUtilsTest extends TestCase { expectedAttribute.add("value1"); expectedAttribute.add("value2"); - handlerMock.handleAttributeValue(expectedAttributeName, "value1", 0); - handlerMock.handleAttributeValue(expectedAttributeName, "value2", 1); - - handlerControl.replay(); - LdapUtils.iterateAttributeValues(expectedAttribute, handlerMock); - handlerControl.verify(); + verify(handlerMock).handleAttributeValue(expectedAttributeName, "value1", 0); + verify(handlerMock).handleAttributeValue(expectedAttributeName, "value2", 1); } + @Test public void testIterateAttributeValuesWithEmptyAttribute() { String expectedAttributeName = "someAttribute"; BasicAttribute expectedAttribute = new BasicAttribute(expectedAttributeName); - handlerControl.replay(); - LdapUtils.iterateAttributeValues(expectedAttribute, handlerMock); - - handlerControl.verify(); } /** * Example SID from "http://www.pcreview.co.uk/forums/thread-1458615.php". */ + @Test public void testConvertBinarySidToString() throws Exception { byte[] sid = { (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, @@ -109,6 +115,7 @@ public class LdapUtilsTest extends TestCase { /** * Example SID from "http://blogs.msdn.com/oldnewthing/archive/2004/03/15/89753.aspx". */ + @Test public void testConvertAnotherBinarySidToString() throws Exception { byte[] sid = { (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, @@ -124,6 +131,7 @@ public class LdapUtilsTest extends TestCase { /** * Hand-crafted SID. */ + @Test public void testConvertHandCraftedBinarySidToString() throws Exception { byte[] sid = { (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, @@ -135,7 +143,8 @@ public class LdapUtilsTest extends TestCase { String result = LdapUtils.convertBinarySidToString(sid); assertEquals("S-1-5-21-1-2-3-4", result); } - + + @Test public void testSmallNumberToBytesBigEndian() throws Exception { byte[] result = LdapUtils.numberToBytes("5", 6, true); assertEquals(6, result.length); @@ -146,7 +155,8 @@ public class LdapUtilsTest extends TestCase { assertEquals(0, result[4]); assertEquals(5, result[5]); } - + + @Test public void testLargeNumberToBytesBigEndian() throws Exception { byte[] result = LdapUtils.numberToBytes("1183728", 6, true); assertEquals(6, result.length); @@ -157,7 +167,8 @@ public class LdapUtilsTest extends TestCase { assertEquals(15, result[4]); assertEquals(-16, result[5]); } - + + @Test public void testSmallNumberToBytesLittleEndian() throws Exception { byte[] result = LdapUtils.numberToBytes("21", 4, false); assertEquals(4, result.length); @@ -166,7 +177,8 @@ public class LdapUtilsTest extends TestCase { assertEquals(0, result[2]); assertEquals(0, result[3]); } - + + @Test public void testLargeNumberToBytesLittleEndian() throws Exception { byte[] result = LdapUtils.numberToBytes("2127521184", 4, false); assertEquals(4, result.length); @@ -179,6 +191,7 @@ public class LdapUtilsTest extends TestCase { /** * Hand-crafted SID. */ + @Test public void testConvertHandCraftedStringSidToBinary() throws Exception { byte[] expectedSid = { (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, @@ -197,6 +210,7 @@ public class LdapUtilsTest extends TestCase { /** * Example SID from "http://www.pcreview.co.uk/forums/thread-1458615.php". */ + @Test public void testConvertStringSidToBinary() throws Exception { byte[] expectedSid = { (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationExecutorTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationExecutorTest.java index 51621fd2..78297693 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationExecutorTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationExecutorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,38 +15,26 @@ */ package org.springframework.ldap.transaction.compensating; -import javax.naming.directory.BasicAttributes; - -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.transaction.compensating.BindOperationExecutor; -public class BindOperationExecutorTest extends TestCase { - private MockControl ldapOperationsControl; +import javax.naming.directory.BasicAttributes; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +public class BindOperationExecutorTest { private LdapOperations ldapOperationsMock; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); - } - - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - } - - protected void replay() { - ldapOperationsControl.replay(); - } - - protected void verify() { - ldapOperationsControl.verify(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); } + @Test public void testPerformOperation() { DistinguishedName expectedDn = new DistinguishedName("cn=john doe"); Object expectedObject = new Object(); @@ -55,14 +43,13 @@ public class BindOperationExecutorTest extends TestCase { ldapOperationsMock, expectedDn, expectedObject, expectedAttributes); - ldapOperationsMock.bind(expectedDn, expectedObject, expectedAttributes); - - replay(); // perform teste tested.performOperation(); - verify(); + + verify(ldapOperationsMock).bind(expectedDn, expectedObject, expectedAttributes); } + @Test public void testCommit() { DistinguishedName expectedDn = new DistinguishedName("cn=john doe"); Object expectedObject = new Object(); @@ -71,25 +58,22 @@ public class BindOperationExecutorTest extends TestCase { ldapOperationsMock, expectedDn, expectedObject, expectedAttributes); - // Nothing to do here. + verifyNoMoreInteractions(ldapOperationsMock); - replay(); // perform teste tested.commit(); - verify(); } + @Test public void testRollback() { DistinguishedName expectedDn = new DistinguishedName("cn=john doe"); BindOperationExecutor tested = new BindOperationExecutor( ldapOperationsMock, expectedDn, null, null); - ldapOperationsMock.unbind(expectedDn); - - replay(); // perform teste tested.rollback(); - verify(); + + verify(ldapOperationsMock).unbind(expectedDn); } } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationRecorderTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationRecorderTest.java index 95f5de96..52abafcf 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationRecorderTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationRecorderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,33 +15,29 @@ */ package org.springframework.ldap.transaction.compensating; -import javax.naming.directory.BasicAttributes; - -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.transaction.compensating.BindOperationExecutor; -import org.springframework.ldap.transaction.compensating.BindOperationRecorder; import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -public class BindOperationRecorderTest extends TestCase { - private MockControl ldapOperationsControl; +import javax.naming.directory.BasicAttributes; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +public class BindOperationRecorderTest { private LdapOperations ldapOperationsMock; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); } - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - } - + @Test public void testRecordOperation_DistinguishedName() { BindOperationRecorder tested = new BindOperationRecorder( ldapOperationsMock); @@ -63,6 +59,7 @@ public class BindOperationRecorderTest extends TestCase { .getOriginalAttributes()); } + @Test public void testPerformOperation_String() { BindOperationRecorder tested = new BindOperationRecorder( ldapOperationsMock); @@ -81,18 +78,13 @@ public class BindOperationRecorderTest extends TestCase { assertSame(ldapOperationsMock, rollbackOperation.getLdapOperations()); } + @Test(expected = IllegalArgumentException.class) public void testPerformOperation_Invalid() { BindOperationRecorder tested = new BindOperationRecorder( ldapOperationsMock); Object expectedDn = new Object(); - try { - // Perform test. - tested.recordOperation(new Object[] { expectedDn }); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertTrue(true); - } - + // Perform test. + tested.recordOperation(new Object[]{expectedDn}); } } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactoryTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactoryTest.java index 97bfcb56..6d803c58 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactoryTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,40 +15,32 @@ */ package org.springframework.ldap.transaction.compensating; -import javax.naming.directory.DirContext; - -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.LdapOperations; import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; -public class LdapCompensatingTransactionOperationFactoryTest extends TestCase { - private MockControl ldapOperationsControl; +import javax.naming.directory.DirContext; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +public class LdapCompensatingTransactionOperationFactoryTest { private LdapOperations ldapOperationsMock; - private MockControl renamingStrategyControl; - private TempEntryRenamingStrategy renamingStrategyMock; - private MockControl dirContextControl; - private DirContext dirContextMock; private LdapCompensatingTransactionOperationFactory tested; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); - - renamingStrategyControl = MockControl - .createControl(TempEntryRenamingStrategy.class); - renamingStrategyMock = (TempEntryRenamingStrategy) renamingStrategyControl - .getMock(); - - dirContextControl = MockControl.createControl(DirContext.class); - dirContextMock = (DirContext) dirContextControl.getMock(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); + renamingStrategyMock = mock(TempEntryRenamingStrategy.class); + dirContextMock = mock(DirContext.class); tested = new LdapCompensatingTransactionOperationFactory( renamingStrategyMock) { @@ -60,31 +52,7 @@ public class LdapCompensatingTransactionOperationFactoryTest extends TestCase { }; } - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - - renamingStrategyControl = null; - renamingStrategyMock = null; - - dirContextControl = null; - dirContextMock = null; - - tested = null; - } - - protected void replay() { - ldapOperationsControl.replay(); - renamingStrategyControl.replay(); - dirContextControl.replay(); - } - - protected void verify() { - ldapOperationsControl.verify(); - renamingStrategyControl.verify(); - dirContextControl.verify(); - } - + @Test public void testGetRecordingOperation_Bind() throws Exception { CompensatingTransactionOperationRecorder result = tested @@ -95,6 +63,7 @@ public class LdapCompensatingTransactionOperationFactoryTest extends TestCase { .getLdapOperations()); } + @Test public void testGetRecordingOperation_Rebind() throws Exception { CompensatingTransactionOperationRecorder result = tested .createRecordingOperation(dirContextMock, "rebind"); @@ -106,6 +75,7 @@ public class LdapCompensatingTransactionOperationFactoryTest extends TestCase { .getRenamingStrategy()); } + @Test public void testGetRecordingOperation_Rename() throws Exception { CompensatingTransactionOperationRecorder result = tested .createRecordingOperation(dirContextMock, "rename"); @@ -114,6 +84,7 @@ public class LdapCompensatingTransactionOperationFactoryTest extends TestCase { assertSame(ldapOperationsMock, recordingOperation.getLdapOperations()); } + @Test public void testGetRecordingOperation_ModifyAttributes() throws Exception { CompensatingTransactionOperationRecorder result = tested .createRecordingOperation(dirContextMock, "modifyAttributes"); @@ -122,6 +93,7 @@ public class LdapCompensatingTransactionOperationFactoryTest extends TestCase { assertSame(ldapOperationsMock, recordingOperation.getLdapOperations()); } + @Test public void testGetRecordingOperation_Unbind() throws Exception { CompensatingTransactionOperationRecorder result = tested .createRecordingOperation(dirContextMock, "unbind"); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtilsTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtilsTest.java index 7e10365d..a2926a01 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtilsTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtilsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,57 +15,44 @@ */ package org.springframework.ldap.transaction.compensating; -import javax.naming.NamingException; -import javax.naming.directory.DirContext; - -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.support.LdapUtils; import org.springframework.transaction.support.TransactionSynchronizationManager; -public class LdapTransactionUtilsTest extends TestCase { +import javax.naming.NamingException; +import javax.naming.directory.DirContext; - private MockControl dirContextControl; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class LdapTransactionUtilsTest { private DirContext dirContextMock; - protected void setUp() throws Exception { - dirContextControl = MockControl.createControl(DirContext.class); - dirContextMock = (DirContext) dirContextControl.getMock(); + @Before + public void setUp() throws Exception { + dirContextMock = mock(DirContext.class); if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.clearSynchronization(); } } - protected void tearDown() throws Exception { - dirContextControl = null; - dirContextMock = null; - } - - protected void replay() { - dirContextControl.replay(); - } - - protected void verify() { - dirContextControl.verify(); - } - + @Test public void testCloseContext() throws NamingException { - dirContextMock.close(); - - replay(); LdapUtils.closeContext(dirContextMock); - verify(); + verify(dirContextMock).close(); } + @Test public void testCloseContext_NullContext() throws NamingException { - replay(); LdapUtils.closeContext(null); - verify(); } + @Test public void testIsSupportedWriteTransactionOperation() { assertTrue(LdapTransactionUtils .isSupportedWriteTransactionOperation("bind")); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutorTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutorTest.java index 180dd770..a7a14296 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutorTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,40 +15,27 @@ */ package org.springframework.ldap.transaction.compensating; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.core.LdapOperations; + import javax.naming.Name; import javax.naming.directory.ModificationItem; -import org.easymock.MockControl; -import org.easymock.internal.ArrayMatcher; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.transaction.compensating.ModifyAttributesOperationExecutor; - -import junit.framework.TestCase; - -public class ModifyAttributesOperationExecutorTest extends TestCase { - private MockControl ldapOperationsControl; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +public class ModifyAttributesOperationExecutorTest { private LdapOperations ldapOperationsMock; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); - } - - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - } - - protected void replay() { - ldapOperationsControl.replay(); - } - - protected void verify() { - ldapOperationsControl.verify(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); } + @Test public void testPerformOperation() { ModificationItem[] expectedCompensatingItems = new ModificationItem[0]; ModificationItem[] expectedActualItems = new ModificationItem[0]; @@ -58,16 +45,13 @@ public class ModifyAttributesOperationExecutorTest extends TestCase { ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, expectedDn, expectedActualItems, expectedCompensatingItems); - ldapOperationsMock.modifyAttributes(expectedDn, expectedActualItems); - ldapOperationsControl.setMatcher(new ArrayMatcher()); - - replay(); // Perform test tested.performOperation(); - verify(); + verify(ldapOperationsMock).modifyAttributes(expectedDn, expectedActualItems); } + @Test public void testCommit() { ModificationItem[] expectedCompensatingItems = new ModificationItem[0]; ModificationItem[] expectedActualItems = new ModificationItem[0]; @@ -78,14 +62,13 @@ public class ModifyAttributesOperationExecutorTest extends TestCase { expectedDn, expectedActualItems, expectedCompensatingItems); // No operation here + verifyNoMoreInteractions(ldapOperationsMock); - replay(); // Perform test tested.commit(); - - verify(); } + @Test public void testRollback() { ModificationItem[] expectedCompensatingItems = new ModificationItem[0]; ModificationItem[] expectedActualItems = new ModificationItem[0]; @@ -95,14 +78,9 @@ public class ModifyAttributesOperationExecutorTest extends TestCase { ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, expectedDn, expectedActualItems, expectedCompensatingItems); - ldapOperationsMock.modifyAttributes(expectedDn, expectedCompensatingItems); - ldapOperationsControl.setMatcher(new ArrayMatcher()); - - replay(); // Perform test tested.rollback(); - verify(); + verify(ldapOperationsMock).modifyAttributes(expectedDn, expectedCompensatingItems); } - } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorderTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorderTest.java index 60bd92c5..19f0f86d 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorderTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorderTest.java @@ -16,11 +16,11 @@ package org.springframework.ldap.transaction.compensating; -import junit.framework.TestCase; -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.LdapOperations; import org.springframework.ldap.core.IncrementalAttributesMapper; +import org.springframework.ldap.core.LdapOperations; import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; import javax.naming.NamingException; @@ -31,49 +31,28 @@ import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; -public class ModifyAttributesOperationRecorderTest extends TestCase { - private MockControl ldapOperationsControl; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +public class ModifyAttributesOperationRecorderTest { private LdapOperations ldapOperationsMock; - private MockControl attributesMapperControl; - private IncrementalAttributesMapper attributesMapperMock; private ModifyAttributesOperationRecorder tested; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); - - attributesMapperControl = MockControl - .createControl(IncrementalAttributesMapper.class); - attributesMapperMock = (IncrementalAttributesMapper) attributesMapperControl - .getMock(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); + attributesMapperMock = mock(IncrementalAttributesMapper.class); tested = new ModifyAttributesOperationRecorder(ldapOperationsMock); } - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - - attributesMapperControl = null; - attributesMapperMock = null; - - tested = null; - } - - protected void replay() { - ldapOperationsControl.replay(); - attributesMapperControl.replay(); - } - - protected void verify() { - ldapOperationsControl.verify(); - attributesMapperControl.verify(); - } - + @Test public void testRecordOperation() { final ModificationItem incomingItem = new ModificationItem( DirContext.ADD_ATTRIBUTE, new BasicAttribute("attribute1")); @@ -98,26 +77,18 @@ public class ModifyAttributesOperationRecorderTest extends TestCase { }; DistinguishedName expectedName = new DistinguishedName("cn=john doe"); - ldapOperationsControl.setDefaultMatcher(MockControl.ARRAY_MATCHER); - attributesMapperControl.expectAndReturn( - attributesMapperMock.hasMore(), true); - attributesMapperControl.expectAndReturn( - attributesMapperMock.getAttributesForLookup(), - new String[]{"attribute1"}); - ldapOperationsControl.expectAndReturn( - ldapOperationsMock.lookup(expectedName, new String[]{"attribute1"}, attributesMapperMock), - expectedAttributes); - attributesMapperControl.expectAndReturn(attributesMapperMock.hasMore(), false); - attributesMapperControl.expectAndReturn( - attributesMapperMock.getCollectedAttributes(), - expectedAttributes); + when(attributesMapperMock.hasMore()).thenReturn(true, false); + when(attributesMapperMock.getAttributesForLookup()) + .thenReturn(new String[]{"attribute1"}); + when(ldapOperationsMock.lookup(expectedName, new String[]{"attribute1"}, attributesMapperMock)) + .thenReturn(expectedAttributes); + when(attributesMapperMock.getCollectedAttributes()) + .thenReturn(expectedAttributes); - replay(); // Perform test CompensatingTransactionOperationExecutor operation = tested .recordOperation(new Object[]{expectedName, incomingMods}); - verify(); // Verify outcome assertTrue(operation instanceof ModifyAttributesOperationExecutor); @@ -132,6 +103,7 @@ public class ModifyAttributesOperationRecorderTest extends TestCase { .getCompensatingModifications()[0]); } + @Test public void testGetCompensatingModificationItem_RemoveFullExistingAttribute() throws NamingException { BasicAttribute attribute = new BasicAttribute("someattr"); @@ -156,6 +128,7 @@ public class ModifyAttributesOperationRecorderTest extends TestCase { assertEquals("value2", resultAttribute.get(1)); } + @Test public void testGetCompensatingModificationItem_RemoveTwoAttributeValues() throws NamingException { BasicAttribute attribute = new BasicAttribute("someattr"); @@ -184,6 +157,7 @@ public class ModifyAttributesOperationRecorderTest extends TestCase { assertEquals("value2", resultAttribute.get(1)); } + @Test public void testGetCompensatingModificationItem_ReplaceExistingAttribute() throws NamingException { BasicAttribute attribute = new BasicAttribute("someattr"); @@ -211,6 +185,7 @@ public class ModifyAttributesOperationRecorderTest extends TestCase { assertEquals("value2", resultAttribute.get(1)); } + @Test public void testGetCompensatingModificationItem_ReplaceNonExistingAttribute() throws NamingException { Attributes attributes = new BasicAttributes(); @@ -232,6 +207,7 @@ public class ModifyAttributesOperationRecorderTest extends TestCase { assertEquals(0, resultAttribute.size()); } + @Test public void testGetCompensatingModificationItem_AddNonExistingAttribute() throws NamingException { Attributes attributes = new BasicAttributes(); @@ -253,6 +229,7 @@ public class ModifyAttributesOperationRecorderTest extends TestCase { assertEquals(0, resultAttribute.size()); } + @Test public void testGetCompensatingModificationItem_AddExistingAttribute() throws NamingException { BasicAttribute attribute = new BasicAttribute("someattr"); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutorTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutorTest.java index 34be5737..8635faab 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutorTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,39 +15,26 @@ */ package org.springframework.ldap.transaction.compensating; -import javax.naming.directory.BasicAttributes; - -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.transaction.compensating.RebindOperationExecutor; -public class RebindOperationExecutorTest extends TestCase { +import javax.naming.directory.BasicAttributes; - private MockControl ldapOperationsControl; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class RebindOperationExecutorTest { private LdapOperations ldapOperationsMock; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); - } - - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - } - - protected void replay() { - ldapOperationsControl.replay(); - } - - protected void verify() { - ldapOperationsControl.verify(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); } + @Test public void testPerformOperation() { DistinguishedName expectedOriginalDn = new DistinguishedName( "cn=john doe"); @@ -59,16 +46,14 @@ public class RebindOperationExecutorTest extends TestCase { ldapOperationsMock, expectedOriginalDn, expectedTempDn, expectedObject, expectedAttributes); - ldapOperationsMock.rename(expectedOriginalDn, expectedTempDn); - ldapOperationsMock.bind(expectedOriginalDn, expectedObject, - expectedAttributes); - - replay(); // perform test tested.performOperation(); - verify(); + verify(ldapOperationsMock).rename(expectedOriginalDn, expectedTempDn); + verify(ldapOperationsMock) + .bind(expectedOriginalDn, expectedObject, expectedAttributes); } + @Test public void testCommit() { DistinguishedName expectedOriginalDn = new DistinguishedName( "cn=john doe"); @@ -80,14 +65,12 @@ public class RebindOperationExecutorTest extends TestCase { ldapOperationsMock, expectedOriginalDn, expectedTempDn, expectedObject, expectedAttributes); - ldapOperationsMock.unbind(expectedTempDn); - - replay(); // perform test tested.commit(); - verify(); + verify(ldapOperationsMock).unbind(expectedTempDn); } + @Test public void testRollback() { DistinguishedName expectedOriginalDn = new DistinguishedName( "cn=john doe"); @@ -99,12 +82,10 @@ public class RebindOperationExecutorTest extends TestCase { ldapOperationsMock, expectedOriginalDn, expectedTempDn, expectedObject, expectedAttributes); - ldapOperationsMock.unbind(expectedOriginalDn); - ldapOperationsMock.rename(expectedTempDn, expectedOriginalDn); - - replay(); // perform test tested.rollback(); - verify(); + + verify(ldapOperationsMock).unbind(expectedOriginalDn); + verify(ldapOperationsMock).rename(expectedTempDn, expectedOriginalDn); } } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorderTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorderTest.java index dad00ca6..21e73db2 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorderTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,57 +15,32 @@ */ package org.springframework.ldap.transaction.compensating; -import javax.naming.directory.BasicAttributes; - -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.transaction.compensating.RebindOperationExecutor; -import org.springframework.ldap.transaction.compensating.RebindOperationRecorder; -import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -public class RebindOperationRecorderTest extends TestCase { - private MockControl ldapOperationsControl; +import javax.naming.directory.BasicAttributes; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class RebindOperationRecorderTest { private LdapOperations ldapOperationsMock; - private MockControl renamingStrategyControl; - private TempEntryRenamingStrategy renamingStrategyMock; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); - - renamingStrategyControl = MockControl - .createControl(TempEntryRenamingStrategy.class); - renamingStrategyMock = (TempEntryRenamingStrategy) renamingStrategyControl - .getMock(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); + renamingStrategyMock = mock(TempEntryRenamingStrategy.class); } - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - - renamingStrategyControl = null; - renamingStrategyMock = null; - - } - - protected void replay() { - ldapOperationsControl.replay(); - renamingStrategyControl.replay(); - } - - protected void verify() { - ldapOperationsControl.verify(); - renamingStrategyControl.verify(); - } - + @Test public void testRecordOperation() { final DistinguishedName expectedDn = new DistinguishedName( "cn=john doe"); @@ -74,10 +49,9 @@ public class RebindOperationRecorderTest extends TestCase { RebindOperationRecorder tested = new RebindOperationRecorder( ldapOperationsMock, renamingStrategyMock); - renamingStrategyControl.expectAndReturn(renamingStrategyMock - .getTemporaryName(expectedDn), expectedTempDn); + when(renamingStrategyMock.getTemporaryName(expectedDn)) + .thenReturn(expectedTempDn); - replay(); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); @@ -85,8 +59,6 @@ public class RebindOperationRecorderTest extends TestCase { CompensatingTransactionOperationExecutor result = tested .recordOperation(new Object[] { expectedDn, expectedObject, expectedAttributes }); - verify(); - assertTrue(result instanceof RebindOperationExecutor); RebindOperationExecutor rollbackOperation = (RebindOperationExecutor) result; assertSame(ldapOperationsMock, rollbackOperation.getLdapOperations()); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutorTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutorTest.java index 758e5112..70122f8f 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutorTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,52 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.ldap.transaction.compensating; -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.transaction.compensating.RenameOperationExecutor; -import junit.framework.TestCase; - -public class RenameOperationExecutorTest extends TestCase { - private MockControl ldapOperationsControl; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +public class RenameOperationExecutorTest { private LdapOperations ldapOperationsMock; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class);; } - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - } - protected void replay() { - ldapOperationsControl.replay(); - } - - protected void verify() { - ldapOperationsControl.verify(); - } + @Test public void testPerformOperation() { DistinguishedName expectedNewName = new DistinguishedName("ou=newOu"); DistinguishedName expectedOldName = new DistinguishedName("ou=someou"); RenameOperationExecutor tested = new RenameOperationExecutor( ldapOperationsMock, expectedOldName, expectedNewName); - ldapOperationsMock.rename(expectedOldName, expectedNewName); - - replay(); // Perform test. tested.performOperation(); - verify(); + + verify(ldapOperationsMock).rename(expectedOldName, expectedNewName); } + @Test public void testCommit() { DistinguishedName expectedNewName = new DistinguishedName("ou=newOu"); DistinguishedName expectedOldName = new DistinguishedName("ou=someou"); @@ -66,25 +56,23 @@ public class RenameOperationExecutorTest extends TestCase { ldapOperationsMock, expectedOldName, expectedNewName); // Nothing to do for this operation. + verifyNoMoreInteractions(ldapOperationsMock); - replay(); // Perform test. tested.commit(); - verify(); } + @Test public void testRollback() { DistinguishedName expectedNewName = new DistinguishedName("ou=newOu"); DistinguishedName expectedOldName = new DistinguishedName("ou=someou"); RenameOperationExecutor tested = new RenameOperationExecutor( ldapOperationsMock, expectedOldName, expectedNewName); - ldapOperationsMock.rename(expectedNewName, expectedOldName); - - replay(); // Perform test. tested.rollback(); - verify(); + + verify(ldapOperationsMock).rename(expectedNewName, expectedOldName); } } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorderTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorderTest.java index 691aa131..c0f4ef74 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorderTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,47 +15,33 @@ */ package org.springframework.ldap.transaction.compensating; -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.transaction.compensating.RenameOperationExecutor; -import org.springframework.ldap.transaction.compensating.RenameOperationRecorder; import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -public class RenameOperationRecorderTest extends TestCase { +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; - private MockControl ldapOperationsControl; +public class RenameOperationRecorderTest { private LdapOperations ldapOperationsMock; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); - } - - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - } - - protected void replay() { - ldapOperationsControl.replay(); - } - - protected void verify() { - ldapOperationsControl.verify(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class);; } + @Test public void testRecordOperation() { RenameOperationRecorder tested = new RenameOperationRecorder( ldapOperationsMock); - replay(); // Perform test CompensatingTransactionOperationExecutor operation = tested .recordOperation(new Object[] { "ou=someou", "ou=newou" }); - verify(); assertTrue(operation instanceof RenameOperationExecutor); RenameOperationExecutor rollbackOperation = (RenameOperationExecutor) operation; @@ -63,5 +49,4 @@ public class RenameOperationRecorderTest extends TestCase { assertEquals("ou=newou", rollbackOperation.getNewDn().toString()); assertEquals("ou=someou", rollbackOperation.getOriginalDn().toString()); } - } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutorTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutorTest.java index 259d3ca6..0490a4cb 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutorTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,77 +15,58 @@ */ package org.springframework.ldap.transaction.compensating; -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.transaction.compensating.UnbindOperationExecutor; -public class UnbindOperationExecutorTest extends TestCase { - private MockControl ldapOperationsControl; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +public class UnbindOperationExecutorTest { private LdapOperations ldapOperationsMock; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); - - } - - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - - } - - protected void replay() { - ldapOperationsControl.replay(); - } - - protected void verify() { - ldapOperationsControl.verify(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class);; } + @Test public void testPerformOperation() { DistinguishedName expectedOldName = new DistinguishedName("cn=oldDn"); DistinguishedName expectedTempName = new DistinguishedName("cn=newDn"); UnbindOperationExecutor tested = new UnbindOperationExecutor( ldapOperationsMock, expectedOldName, expectedTempName); - ldapOperationsMock.rename(expectedOldName, expectedTempName); - - replay(); // Perform test tested.performOperation(); - verify(); + + verify(ldapOperationsMock).rename(expectedOldName, expectedTempName); } + @Test public void testCommit() { DistinguishedName expectedOldName = new DistinguishedName("cn=oldDn"); DistinguishedName expectedTempName = new DistinguishedName("cn=newDn"); UnbindOperationExecutor tested = new UnbindOperationExecutor( ldapOperationsMock, expectedOldName, expectedTempName); - ldapOperationsMock.unbind(expectedTempName); - - replay(); // Perform test tested.commit(); - verify(); + verify(ldapOperationsMock).unbind(expectedTempName); } + @Test public void testRollback() { DistinguishedName expectedOldName = new DistinguishedName("cn=oldDn"); DistinguishedName expectedTempName = new DistinguishedName("cn=newDn"); UnbindOperationExecutor tested = new UnbindOperationExecutor( ldapOperationsMock, expectedOldName, expectedTempName); - ldapOperationsMock.rename(expectedTempName, expectedOldName); - replay(); + // Perform test tested.rollback(); - verify(); + verify(ldapOperationsMock).rename(expectedTempName, expectedOldName); } } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorderTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorderTest.java index 0723c76e..b4bbd631 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorderTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,55 +15,30 @@ */ package org.springframework.ldap.transaction.compensating; -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.DistinguishedName; import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; -import org.springframework.ldap.transaction.compensating.UnbindOperationExecutor; -import org.springframework.ldap.transaction.compensating.UnbindOperationRecorder; import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -public class UnbindOperationRecorderTest extends TestCase { - private MockControl ldapOperationsControl; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +public class UnbindOperationRecorderTest { private LdapOperations ldapOperationsMock; - private MockControl renamingStrategyControl; - private TempEntryRenamingStrategy renamingStrategyMock; - protected void setUp() throws Exception { - ldapOperationsControl = MockControl.createControl(LdapOperations.class); - ldapOperationsMock = (LdapOperations) ldapOperationsControl.getMock(); - - renamingStrategyControl = MockControl - .createControl(TempEntryRenamingStrategy.class); - renamingStrategyMock = (TempEntryRenamingStrategy) renamingStrategyControl - .getMock(); + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class);; + renamingStrategyMock = mock(TempEntryRenamingStrategy.class); } - protected void tearDown() throws Exception { - ldapOperationsControl = null; - ldapOperationsMock = null; - - renamingStrategyControl = null; - renamingStrategyMock = null; - - } - - protected void replay() { - ldapOperationsControl.replay(); - renamingStrategyControl.replay(); - } - - protected void verify() { - ldapOperationsControl.verify(); - renamingStrategyControl.verify(); - } - + @Test public void testRecordOperation() { final DistinguishedName expectedTempName = new DistinguishedName( "cn=john doe_temp"); @@ -72,14 +47,12 @@ public class UnbindOperationRecorderTest extends TestCase { UnbindOperationRecorder tested = new UnbindOperationRecorder( ldapOperationsMock, renamingStrategyMock); - renamingStrategyControl.expectAndReturn(renamingStrategyMock - .getTemporaryName(expectedDn), expectedTempName); + when(renamingStrategyMock.getTemporaryName(expectedDn)) + .thenReturn(expectedTempName); - replay(); // Perform test CompensatingTransactionOperationExecutor operation = tested .recordOperation(new Object[] { expectedDn }); - verify(); // Verify result assertTrue(operation instanceof UnbindOperationExecutor); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerTest.java index 0200bcba..b9299ab1 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,17 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.ldap.transaction.compensating.manager; -import java.sql.Connection; - -import javax.naming.directory.DirContext; -import javax.sql.DataSource; - -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.ldap.UncategorizedLdapException; import org.springframework.ldap.core.ContextSource; @@ -39,79 +32,49 @@ import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.DefaultTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; -public class ContextSourceTransactionManagerTest extends TestCase { +import javax.naming.directory.DirContext; +import javax.sql.DataSource; +import java.sql.Connection; - private MockControl contextSourceControl; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class ContextSourceTransactionManagerTest { private ContextSource contextSourceMock; - - private MockControl contextControl; - private DirContext contextMock; private ContextSourceTransactionManager tested; - - private MockControl transactionDefinitionControl; - - private MockControl transactionDataManagerControl; - private CompensatingTransactionOperationManager transactionDataManagerMock; private TransactionDefinition transactionDefinitionMock; - private MockControl renamingStrategyControl; - private TempEntryRenamingStrategy renamingStrategyMock; - protected void setUp() throws Exception { - super.setUp(); + @Before + public void setUp() throws Exception { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.clearSynchronization(); } - contextSourceControl = MockControl.createControl(ContextSource.class); - contextSourceMock = (ContextSource) contextSourceControl.getMock(); - - contextControl = MockControl.createControl(DirContext.class); - contextMock = (DirContext) contextControl.getMock(); - - transactionDefinitionControl = MockControl.createControl(TransactionDefinition.class); - transactionDefinitionMock = (TransactionDefinition) transactionDefinitionControl.getMock(); - - transactionDataManagerControl = MockControl.createControl(CompensatingTransactionOperationManager.class); - transactionDataManagerMock = (CompensatingTransactionOperationManager) transactionDataManagerControl.getMock(); - - renamingStrategyControl = MockControl.createControl(TempEntryRenamingStrategy.class); - renamingStrategyMock = (TempEntryRenamingStrategy) renamingStrategyControl.getMock(); + contextSourceMock = mock(ContextSource.class); + contextMock = mock(DirContext.class); + transactionDefinitionMock = mock(TransactionDefinition.class); + transactionDataManagerMock = mock(CompensatingTransactionOperationManager.class); + renamingStrategyMock = mock(TempEntryRenamingStrategy.class); tested = new ContextSourceTransactionManager(); tested.setContextSource(contextSourceMock); tested.setRenamingStrategy(renamingStrategyMock); } - protected void tearDown() throws Exception { - super.tearDown(); - - contextControl = null; - contextMock = null; - - contextSourceControl = null; - contextSourceMock = null; - - transactionDefinitionControl = null; - transactionDefinitionMock = null; - - transactionDataManagerControl = null; - transactionDataManagerMock = null; - - renamingStrategyControl = null; - renamingStrategyMock = null; - - if (TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.clearSynchronization(); - } - } - + @Test public void testDoGetTransaction() { Object result = tested.doGetTransaction(); @@ -121,6 +84,7 @@ public class ContextSourceTransactionManagerTest extends TestCase { assertNull(transactionObject.getHolder()); } + @Test public void testDoGetTransactionTransactionActive() { CompensatingTransactionHolderSupport expectedContextHolder = new DirContextHolder(null, null); TransactionSynchronizationManager.bindResource(contextSourceMock, expectedContextHolder); @@ -128,52 +92,44 @@ public class ContextSourceTransactionManagerTest extends TestCase { assertSame(expectedContextHolder, ((CompensatingTransactionObject) result).getHolder()); } + @Test public void testDoBegin() { - contextSourceControl.expectAndReturn(contextSourceMock.getReadWriteContext(), contextMock); - - contextSourceControl.replay(); + when(contextSourceMock.getReadWriteContext()).thenReturn(contextMock); CompensatingTransactionObject expectedTransactionObject = new CompensatingTransactionObject(null); tested.doBegin(expectedTransactionObject, transactionDefinitionMock); - contextSourceControl.verify(); - DirContextHolder foundContextHolder = (DirContextHolder) TransactionSynchronizationManager .getResource(contextSourceMock); assertSame(contextMock, foundContextHolder.getCtx()); } - public void testDoCommit() { - } - - public void testDoRollback() { - + @Test + public void testDoRollback() { DirContextHolder expectedContextHolder = new DirContextHolder(null, contextMock); expectedContextHolder.setTransactionOperationManager(transactionDataManagerMock); TransactionSynchronizationManager.bindResource(contextSourceMock, expectedContextHolder); - transactionDataManagerMock.rollback(); - transactionDataManagerControl.replay(); CompensatingTransactionObject transactionObject = new CompensatingTransactionObject(null); transactionObject.setHolder(expectedContextHolder); tested.doRollback(new DefaultTransactionStatus(transactionObject, false, false, false, false, null)); - transactionDataManagerControl.verify(); + + verify(transactionDataManagerMock).rollback(); } + @Test public void testDoCleanupAfterCompletion() throws Exception { DirContextHolder expectedContextHolder = new DirContextHolder(null, contextMock); TransactionSynchronizationManager.bindResource(contextSourceMock, expectedContextHolder); - contextMock.close(); - contextControl.replay(); - tested.doCleanupAfterCompletion(new CompensatingTransactionObject(expectedContextHolder)); - contextControl.verify(); assertNull(TransactionSynchronizationManager.getResource(contextSourceMock)); assertNull(expectedContextHolder.getTransactionOperationManager()); + verify(contextMock).close(); } + @Test public void testSetContextSource_Proxy() { TransactionAwareContextSourceProxy proxy = new TransactionAwareContextSourceProxy(contextSourceMock); @@ -185,26 +141,19 @@ public class ContextSourceTransactionManagerTest extends TestCase { assertSame(contextSourceMock, result); } + @Test public void testTransactionSuspension_UnconnectableDataSource() throws Exception { - MockControl connectionControl = MockControl.createControl(Connection.class); - Connection connectionMock = (Connection) connectionControl.getMock(); - MockControl dataSourceControl=MockControl.createControl(DataSource.class); - DataSource dataSourceMock = (DataSource) dataSourceControl.getMock(); + Connection connectionMock = mock(Connection.class); + DataSource dataSourceMock = mock(DataSource.class); - dataSourceControl.expectAndReturn(dataSourceMock.getConnection(), connectionMock); - connectionControl.expectAndReturn(connectionMock.getAutoCommit(), false); - connectionMock.rollback(); + when(dataSourceMock.getConnection()).thenReturn(connectionMock); + when(connectionMock.getAutoCommit()).thenReturn(false); - MockControl unconnectableContextSourceControl = MockControl.createControl(ContextSource.class); - ContextSource unconnectableContextSourceMock = (ContextSource) unconnectableContextSourceControl.getMock(); + ContextSource unconnectableContextSourceMock = mock(ContextSource.class); UncategorizedLdapException connectException = new UncategorizedLdapException("dummy"); - unconnectableContextSourceControl.expectAndThrow(unconnectableContextSourceMock.getReadWriteContext(), connectException); - - connectionControl.replay(); - dataSourceControl.replay(); - unconnectableContextSourceControl.replay(); - + when(unconnectableContextSourceMock.getReadWriteContext()).thenThrow(connectException); + try { // Create an outer transaction final PlatformTransactionManager txMgrOuter = new DataSourceTransactionManager(dataSourceMock); @@ -245,9 +194,6 @@ public class ContextSourceTransactionManagerTest extends TestCase { assertSame("Should be thrown exception", connectException, expected.getCause()); } - connectionControl.verify(); - dataSourceControl.verify(); - unconnectableContextSourceControl.verify(); - - } + verify(connectionMock).rollback(); + } } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxyTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxyTest.java index 2801c488..7fb3e084 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxyTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxyTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,73 +15,46 @@ */ package org.springframework.ldap.transaction.compensating.manager; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.DirContextProxy; + import javax.naming.directory.DirContext; import javax.naming.ldap.LdapContext; -import junit.framework.TestCase; - -import org.easymock.MockControl; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.core.DirContextProxy; -import org.springframework.ldap.transaction.compensating.manager.TransactionAwareContextSourceProxy; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Tests for {@link TransactionAwareContextSourceProxy}. * * @author Mattias Hellborg Arthursson */ -public class TransactionAwareContextSourceProxyTest extends TestCase { - private MockControl contextSourceControl; - +public class TransactionAwareContextSourceProxyTest { private ContextSource contextSourceMock; - private TransactionAwareContextSourceProxy tested; - - private MockControl ldapContextControl; - private LdapContext ldapContextMock; - - private MockControl dirContextControl; - private DirContext dirContextMock; - protected void setUp() throws Exception { - - contextSourceControl = MockControl.createControl(ContextSource.class); - contextSourceMock = (ContextSource) contextSourceControl.getMock(); - - ldapContextControl = MockControl.createControl(LdapContext.class); - ldapContextMock = (LdapContext) ldapContextControl.getMock(); - - dirContextControl = MockControl.createControl(DirContext.class); - dirContextMock = (DirContext) dirContextControl.getMock(); + @Before + public void setUp() throws Exception { + contextSourceMock = mock(ContextSource.class); + ldapContextMock = mock(LdapContext.class); + dirContextMock = mock(DirContext.class); tested = new TransactionAwareContextSourceProxy(contextSourceMock); } - protected void tearDown() throws Exception { - contextSourceControl = null; - contextSourceMock = null; - - ldapContextControl = null; - ldapContextMock = null; - - dirContextControl = null; - dirContextMock = null; - - tested = null; - } - + @Test public void testGetReadWriteContext_LdapContext() { - contextSourceControl.expectAndReturn(contextSourceMock - .getReadWriteContext(), ldapContextMock); - - contextSourceControl.replay(); + when(contextSourceMock.getReadWriteContext()).thenReturn(ldapContextMock); DirContext result = tested.getReadWriteContext(); - contextSourceControl.verify(); - assertNotNull("Result should not be null", result); assertTrue("Should be an LdapContext instance", result instanceof LdapContext); @@ -89,16 +62,12 @@ public class TransactionAwareContextSourceProxyTest extends TestCase { result instanceof DirContextProxy); } + @Test public void testGetReadWriteContext_DirContext() { - contextSourceControl.expectAndReturn(contextSourceMock - .getReadWriteContext(), dirContextMock); - - contextSourceControl.replay(); + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); DirContext result = tested.getReadWriteContext(); - contextSourceControl.verify(); - assertNotNull("Result should not be null", result); assertTrue("Should be a DirContext instance", result instanceof DirContext); @@ -108,16 +77,12 @@ public class TransactionAwareContextSourceProxyTest extends TestCase { result instanceof DirContextProxy); } + @Test public void testGetReadOnlyContext_LdapContext() { - contextSourceControl.expectAndReturn(contextSourceMock - .getReadWriteContext(), ldapContextMock); - - contextSourceControl.replay(); + when(contextSourceMock.getReadWriteContext()).thenReturn(ldapContextMock); DirContext result = tested.getReadOnlyContext(); - contextSourceControl.verify(); - assertNotNull("Result should not be null", result); assertTrue("Should be an LdapContext instance", result instanceof LdapContext); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandlerTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandlerTest.java index 3ebbcbad..5d3ca226 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandlerTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,99 +15,63 @@ */ package org.springframework.ldap.transaction.compensating.manager; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.ContextSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; + import javax.naming.NamingException; import javax.naming.directory.DirContext; -import junit.framework.TestCase; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; -import org.easymock.MockControl; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.transaction.compensating.manager.TransactionAwareDirContextInvocationHandler; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -public class TransactionAwareDirContextInvocationHandlerTest extends TestCase { - - private MockControl contextSourceControl; +public class TransactionAwareDirContextInvocationHandlerTest { private ContextSource contextSourceMock; - - private MockControl dirContextControl; - private DirContext dirContextMock; - private TransactionAwareDirContextInvocationHandler tested; - private DirContextHolder holder; - protected void setUp() throws Exception { - dirContextControl = MockControl.createControl(DirContext.class); - dirContextMock = (DirContext) dirContextControl.getMock(); - - contextSourceControl = MockControl.createControl(ContextSource.class); - contextSourceMock = (ContextSource) contextSourceControl.getMock(); + @Before + public void setUp() throws Exception { + dirContextMock = mock(DirContext.class); + contextSourceMock = mock(ContextSource.class); holder = new DirContextHolder(null, dirContextMock); tested = new TransactionAwareDirContextInvocationHandler(null, null); } - protected void tearDown() throws Exception { - dirContextControl = null; - dirContextMock = null; - - contextSourceControl = null; - contextSourceMock = null; - - holder = null; - - tested = null; - } - - protected void replay() { - dirContextControl.replay(); - contextSourceControl.replay(); - } - - protected void verify() { - dirContextControl.verify(); - contextSourceControl.verify(); - } - + @Test public void testDoCloseConnection_NoTransaction() throws NamingException { - dirContextMock.close(); - - replay(); tested.doCloseConnection(dirContextMock, contextSourceMock); - verify(); + + verify(dirContextMock).close(); } + @Test public void testDoCloseConnection_ActiveTransaction() throws NamingException { TransactionSynchronizationManager.bindResource(contextSourceMock, holder); // Context should not be closed. + verifyNoMoreInteractions(dirContextMock); - replay(); tested.doCloseConnection(dirContextMock, contextSourceMock); - verify(); } + @Test public void testDoCloseConnection_NotTransactionalContext() throws NamingException { TransactionSynchronizationManager.bindResource(contextSourceMock, holder); - MockControl dirContextControl2 = MockControl - .createControl(DirContext.class); - DirContext dirContextMock2 = (DirContext) dirContextControl2.getMock(); + DirContext dirContextMock2 = mock(DirContext.class); - dirContextMock2.close(); - - dirContextControl2.replay(); - replay(); tested.doCloseConnection(dirContextMock2, contextSourceMock); - verify(); - dirContextControl2.verify(); + verify(dirContextMock2).close(); } } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategyTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategyTest.java index f7a5b51d..829ce470 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategyTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategyTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,15 +15,17 @@ */ package org.springframework.ldap.transaction.compensating.support; +import org.junit.Test; +import org.springframework.ldap.core.DistinguishedName; + import javax.naming.Name; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.transaction.compensating.support.DefaultTempEntryRenamingStrategy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; -import junit.framework.TestCase; - -public class DefaultTempEntryRenamingStrategyTest extends TestCase { +public class DefaultTempEntryRenamingStrategyTest { + @Test public void testGetTemporaryName() { DistinguishedName expectedOriginalName = new DistinguishedName( "cn=john doe, ou=somecompany, c=SE"); @@ -35,6 +37,7 @@ public class DefaultTempEntryRenamingStrategyTest extends TestCase { assertNotSame(expectedOriginalName, result); } + @Test public void testGetTemporaryDN_MultivalueDN() { DistinguishedName expectedOriginalName = new DistinguishedName( "cn=john doe+sn=doe, ou=somecompany, c=SE"); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategyTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategyTest.java index baa5f135..3f8ed526 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategyTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategyTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,15 +15,15 @@ */ package org.springframework.ldap.transaction.compensating.support; +import org.junit.Test; +import org.springframework.ldap.core.DistinguishedName; + import javax.naming.Name; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.transaction.compensating.support.DifferentSubtreeTempEntryRenamingStrategy; - -import junit.framework.TestCase; - -public class DifferentSubtreeTempEntryRenamingStrategyTest extends TestCase { +import static org.junit.Assert.assertEquals; +public class DifferentSubtreeTempEntryRenamingStrategyTest { + @Test public void testGetTemporaryName() { DistinguishedName originalName = new DistinguishedName( "cn=john doe, ou=somecompany, c=SE"); diff --git a/core/src/test/java/org/springframework/transaction/compensating/support/CompensatingTransactionUtilsTest.java b/core/src/test/java/org/springframework/transaction/compensating/support/CompensatingTransactionUtilsTest.java index 7bae221c..6ec997bd 100644 --- a/core/src/test/java/org/springframework/transaction/compensating/support/CompensatingTransactionUtilsTest.java +++ b/core/src/test/java/org/springframework/transaction/compensating/support/CompensatingTransactionUtilsTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,74 +15,39 @@ */ package org.springframework.transaction.compensating.support; -import java.lang.reflect.Method; - -import javax.naming.directory.DirContext; - -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.ldap.core.ContextSource; import org.springframework.ldap.transaction.compensating.manager.DirContextHolder; import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; -import org.springframework.transaction.compensating.support.CompensatingTransactionHolderSupport; -import org.springframework.transaction.compensating.support.CompensatingTransactionUtils; import org.springframework.transaction.support.TransactionSynchronizationManager; -public class CompensatingTransactionUtilsTest extends TestCase { +import javax.naming.directory.DirContext; +import java.lang.reflect.Method; - private MockControl dirContextControl; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class CompensatingTransactionUtilsTest { private DirContext dirContextMock; - private MockControl contextSourceControl; - private ContextSource contextSourceMock; - private MockControl operationManagerControl; - private CompensatingTransactionOperationManager operationManagerMock; - protected void setUp() throws Exception { - dirContextControl = MockControl.createControl(DirContext.class); - dirContextMock = (DirContext) dirContextControl.getMock(); - - contextSourceControl = MockControl.createControl(ContextSource.class); - contextSourceMock = (ContextSource) contextSourceControl.getMock(); - - operationManagerControl = MockControl - .createControl(CompensatingTransactionOperationManager.class); - operationManagerMock = (CompensatingTransactionOperationManager) operationManagerControl - .getMock(); + @Before + public void setUp() throws Exception { + dirContextMock = mock(DirContext.class); + contextSourceMock = mock(ContextSource.class); + operationManagerMock = mock(CompensatingTransactionOperationManager.class); if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.clearSynchronization(); } } - protected void tearDown() throws Exception { - dirContextControl = null; - dirContextMock = null; - - contextSourceControl = null; - contextSourceMock = null; - - operationManagerControl = null; - operationManagerMock = null; - } - - protected void replay() { - dirContextControl.replay(); - contextSourceControl.replay(); - operationManagerControl.replay(); - } - - protected void verify() { - dirContextControl.verify(); - contextSourceControl.verify(); - operationManagerControl.verify(); - } - + @Test public void testPerformOperation() throws Throwable { CompensatingTransactionHolderSupport holder = new DirContextHolder( null, dirContextMock); @@ -92,23 +57,20 @@ public class CompensatingTransactionUtilsTest extends TestCase { holder); Object[] expectedArgs = new Object[] { "someDn" }; - operationManagerMock.performOperation(dirContextMock, "unbind", - expectedArgs); - replay(); CompensatingTransactionUtils.performOperation(contextSourceMock, dirContextMock, getUnbindMethod(), expectedArgs); - verify(); + verify(operationManagerMock).performOperation(dirContextMock, "unbind", + expectedArgs); } + @Test public void testPerformOperation_NoTransaction() throws Throwable { Object[] expectedArgs = new Object[] { "someDn" }; - dirContextMock.unbind("someDn"); - replay(); CompensatingTransactionUtils.performOperation(contextSourceMock, dirContextMock, getUnbindMethod(), expectedArgs); - verify(); + verify(dirContextMock).unbind("someDn"); } private Method getUnbindMethod() throws NoSuchMethodException { diff --git a/core/src/test/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManagerTest.java b/core/src/test/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManagerTest.java index f68688bd..64ed29da 100644 --- a/core/src/test/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManagerTest.java +++ b/core/src/test/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2010 the original author or authors. + * Copyright 2005-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,154 +15,94 @@ */ package org.springframework.transaction.compensating.support; -import java.util.Stack; - -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; import org.springframework.transaction.compensating.CompensatingTransactionOperationFactory; import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; -import org.springframework.transaction.compensating.support.DefaultCompensatingTransactionOperationManager; -public class DefaultCompensatingTransactionOperationManagerTest extends - TestCase { +import java.util.Stack; - private MockControl operationExecutorControl; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class DefaultCompensatingTransactionOperationManagerTest { private CompensatingTransactionOperationExecutor operationExecutorMock; - - private MockControl operationFactoryControl; - private CompensatingTransactionOperationFactory operationFactoryMock; - - private MockControl operationRecorderControl; - private CompensatingTransactionOperationRecorder operationRecorderMock; - protected void setUp() throws Exception { - super.setUp(); - operationExecutorControl = MockControl - .createControl(CompensatingTransactionOperationExecutor.class); - operationExecutorMock = (CompensatingTransactionOperationExecutor) operationExecutorControl - .getMock(); - - operationFactoryControl = MockControl - .createControl(CompensatingTransactionOperationFactory.class); - operationFactoryMock = (CompensatingTransactionOperationFactory) operationFactoryControl - .getMock(); - - operationRecorderControl = MockControl - .createControl(CompensatingTransactionOperationRecorder.class); - operationRecorderMock = (CompensatingTransactionOperationRecorder) operationRecorderControl - .getMock(); + @Before + public void setUp() throws Exception { + operationExecutorMock = mock(CompensatingTransactionOperationExecutor.class); + operationFactoryMock = mock(CompensatingTransactionOperationFactory.class); + operationRecorderMock = mock(CompensatingTransactionOperationRecorder.class); } - protected void tearDown() throws Exception { - super.tearDown(); - operationExecutorControl = null; - operationExecutorMock = null; - - operationFactoryControl = null; - operationFactoryMock = null; - - operationRecorderControl = null; - operationRecorderMock = null; - } - - protected void replay() { - operationExecutorControl.replay(); - operationFactoryControl.replay(); - operationRecorderControl.replay(); - } - - protected void verify() { - operationExecutorControl.verify(); - operationFactoryControl.verify(); - operationRecorderControl.verify(); - } - + @Test public void testPerformOperation() { Object[] expectedArgs = new Object[0]; Object expectedResource = new Object(); - operationFactoryControl.expectAndReturn(operationFactoryMock - .createRecordingOperation(expectedResource, "some method"), - operationRecorderMock); - operationRecorderControl.expectAndReturn(operationRecorderMock - .recordOperation(expectedArgs), operationExecutorMock); - operationExecutorMock.performOperation(); + when(operationFactoryMock.createRecordingOperation(expectedResource, "some method")) + .thenReturn(operationRecorderMock); + when(operationRecorderMock.recordOperation(expectedArgs)).thenReturn(operationExecutorMock); DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( operationFactoryMock); - replay(); tested.performOperation(expectedResource, "some method", expectedArgs); - verify(); + verify(operationExecutorMock).performOperation(); Stack result = tested.getOperationExecutors(); assertFalse(result.isEmpty()); assertSame(operationExecutorMock, result.peek()); } + @Test public void testRollback() { DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( operationFactoryMock); tested.getOperationExecutors().push(operationExecutorMock); - operationExecutorMock.rollback(); - - replay(); tested.rollback(); - verify(); + verify(operationExecutorMock).rollback(); } + @Test(expected = TransactionSystemException.class) public void testRollback_Exception() { DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( operationFactoryMock); tested.getOperationExecutors().push(operationExecutorMock); - operationExecutorMock.rollback(); - operationExecutorControl.setThrowable(new RuntimeException()); + doThrow(new RuntimeException()).when(operationExecutorMock).rollback(); - replay(); - try { - tested.rollback(); - fail("TransactionSystemException expected"); - } catch (TransactionSystemException expected) { - assertTrue(true); - } - verify(); + tested.rollback(); } + @Test public void testCommit() { DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( operationFactoryMock); tested.getOperationExecutors().push(operationExecutorMock); - operationExecutorMock.commit(); - - replay(); tested.commit(); - verify(); + verify(operationExecutorMock).commit(); } + @Test(expected = TransactionSystemException.class) public void testCommit_Exception() { DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( operationFactoryMock); tested.getOperationExecutors().push(operationExecutorMock); - operationExecutorMock.commit(); - operationExecutorControl.setThrowable(new RuntimeException()); + doThrow(new RuntimeException()).when(operationExecutorMock).commit(); - replay(); - try { - tested.commit(); - fail("TransactionSystemException expected"); - } catch (TransactionSystemException expected) { - assertTrue(true); - } - verify(); + tested.commit(); } } diff --git a/gradle/java.gradle b/gradle/java.gradle index 24bc5951..91c6acbc 100644 --- a/gradle/java.gradle +++ b/gradle/java.gradle @@ -6,13 +6,14 @@ targetCompatibility = '1.5' ext.springVersion = '3.0.6.RELEASE' ext.springBatchVersion = '2.0.3.RELEASE' -ext.junitVersion = '4.8.2' +ext.junitVersion = '4.10' ext.commonsPoolVersion = '1.5.4' ext.commonsLangVersion = '2.4' ext.commonsLoggingVersion = '1.0.4' ext.easyMockVersion = '1.2_Java1.3' ext.gsbaseVersion = '2.0.1' ext.log4jVersion = '1.2.15' +ext.mockitoVersion = '1.9.5' repositories { mavenCentral()