LDAP-257: Upgraded all core unit tests to JUnit 4 style, and migrated to Mockito.

This commit is contained in:
Mattias Hellborg Arthursson
2013-08-27 13:15:41 +02:00
parent 0dfbfb210f
commit 469549d04e
72 changed files with 1970 additions and 3313 deletions

View File

@@ -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"
}

View File

@@ -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(

View File

@@ -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 {

View File

@@ -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");

View File

@@ -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 };

View File

@@ -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;

View File

@@ -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);
}
}

View File

@@ -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);

View File

@@ -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();

View File

@@ -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);
}
}

View File

@@ -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());

View File

@@ -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());

View File

@@ -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();

View File

@@ -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"),

View File

@@ -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("\\");
}
}

View File

@@ -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");

View File

@@ -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");

View File

@@ -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 <code>list</code> 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());

View File

@@ -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);
}

View File

@@ -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();
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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);

View File

@@ -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/");

View File

@@ -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) {

View File

@@ -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");

View File

@@ -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");

View File

@@ -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());
}
}

View File

@@ -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() {

View File

@@ -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);

View File

@@ -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");

View File

@@ -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";

View File

@@ -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);

View File

@@ -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";

View File

@@ -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";

View File

@@ -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);

View File

@@ -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);

View File

@@ -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"));

View File

@@ -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);

View File

@@ -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("", "(*)")

View File

@@ -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);
}
}

View File

@@ -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 <a
@@ -28,10 +38,8 @@ import org.easymock.MockControl;
*/
public class DelegatingContextTest extends AbstractPoolTestCase {
@Test
public void testConstructorAssertions() {
replay();
try {
new DelegatingContext(null, contextMock, DirContextType.READ_ONLY);
fail("IllegalArgumentException expected");
@@ -53,16 +61,10 @@ public class DelegatingContextTest extends AbstractPoolTestCase {
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
verify();
}
@Test
public void testHelperMethods() throws Exception {
keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, contextMock);
keyedObjectPoolControl.setVoidCallable(1);
replay();
// Wrap the Context once
final DelegatingContext delegatingContext = new DelegatingContext(
keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY);
@@ -77,14 +79,7 @@ public class DelegatingContextTest extends AbstractPoolTestCase {
delegatingContext.assertOpen();
// Wrap the wrapper
MockControl secondKeyedObjectPoolControl = MockControl
.createControl(KeyedObjectPool.class);
KeyedObjectPool secondKeyedObjectPoolMock = (KeyedObjectPool) secondKeyedObjectPoolControl
.getMock();
secondKeyedObjectPoolMock.returnObject(DirContextType.READ_ONLY,
delegatingContext);
secondKeyedObjectPoolControl.setVoidCallable(1);
secondKeyedObjectPoolControl.replay();
KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class);
final DelegatingContext delegatingContext2 = new DelegatingContext(
secondKeyedObjectPoolMock, delegatingContext,
@@ -135,22 +130,18 @@ public class DelegatingContextTest extends AbstractPoolTestCase {
} catch (NamingException ne) {
// Expected
}
verify();
secondKeyedObjectPoolControl.verify();
verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock);
verify(secondKeyedObjectPoolMock)
.returnObject(DirContextType.READ_ONLY, contextMock);
}
@Test
public void testObjectMethods() throws Exception {
keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, contextMock);
keyedObjectPoolControl.setVoidCallable(1);
replay();
// Wrap the Context once
final DelegatingContext delegatingContext = new DelegatingContext(
keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY);
assertEquals("EasyMock for interface javax.naming.Context",
delegatingContext.toString());
assertEquals(contextMock.toString(), delegatingContext.toString());
delegatingContext.hashCode(); // Run it to make sure it doesn't fail
assertTrue(delegatingContext.equals(delegatingContext));
@@ -175,14 +166,12 @@ public class DelegatingContextTest extends AbstractPoolTestCase {
assertFalse(delegatingContext.equals(delegatingContext2));
assertFalse(delegatingContext2.equals(delegatingContext));
assertFalse(delegatingContext.equals(contextMock));
verify();
verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock);
}
@Test
public void testUnsupportedMethods() throws Exception {
replay();
final DelegatingContext delegatingContext = new DelegatingContext(
keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY);
@@ -222,15 +211,10 @@ public class DelegatingContextTest extends AbstractPoolTestCase {
} catch (UnsupportedOperationException uoe) {
// Expected
}
verify();
}
@Test
public void testAllMethodsOpened() throws Exception {
contextControl = MockControl.createNiceControl(Context.class);
contextMock = (Context) contextControl.getMock();
replay();
final DelegatingContext delegatingContext = new DelegatingContext(
keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY);
@@ -256,16 +240,10 @@ public class DelegatingContextTest extends AbstractPoolTestCase {
delegatingContext.rename((String) null, (String) null);
delegatingContext.unbind((Name) null);
delegatingContext.unbind((String) null);
verify();
}
@Test
public void testAllMethodsClosed() throws Exception {
keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, contextMock);
keyedObjectPoolControl.setVoidCallable(1);
replay();
final DelegatingContext delegatingContext = new DelegatingContext(
keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY);
@@ -403,16 +381,12 @@ public class DelegatingContextTest extends AbstractPoolTestCase {
} catch (NamingException ne) {
// Expected
}
verify();
verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock);
}
@Test
public void testDoubleClose() throws Exception {
keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, contextMock);
keyedObjectPoolControl.setVoidCallable(1);
replay();
final DelegatingContext delegatingContext = new DelegatingContext(
keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY);
@@ -420,16 +394,14 @@ public class DelegatingContextTest extends AbstractPoolTestCase {
// noop close
delegatingContext.close();
verify();
verify(keyedObjectPoolMock, times(1)).returnObject(DirContextType.READ_ONLY, contextMock);
}
@Test
public void testPoolExceptionOnClose() throws Exception {
keyedObjectPoolMock.returnObject(DirContextType.READ_ONLY, contextMock);
keyedObjectPoolControl.setThrowable(new Exception(
"Fake Pool returnObject Exception"));
replay();
doThrow(new Exception("Fake Pool returnObject Exception"))
.when(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock);
final DelegatingContext delegatingContext = new DelegatingContext(
keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY);
@@ -440,7 +412,5 @@ public class DelegatingContextTest extends AbstractPoolTestCase {
} catch (NamingException ne) {
// Expected
}
verify();
}
}

View File

@@ -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,31 @@
*/
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 javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
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 <a
* href="mailto:eric.dalquist@doit.wisc.edu">eric.dalquist@doit.wisc.edu</a>
*/
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);
}
}

View File

@@ -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 <a
* href="mailto:eric.dalquist@doit.wisc.edu">eric.dalquist@doit.wisc.edu</a>
*/
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);
}
}

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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());
}
}

View File

@@ -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();
}
}

View File

@@ -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 <a
* href="mailto:eric.dalquist@doit.wisc.edu">eric.dalquist@doit.wisc.edu</a>
*/
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);
}
}

View File

@@ -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,

View File

@@ -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);
}
}

View File

@@ -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});
}
}

View File

@@ -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");

View File

@@ -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"));

View File

@@ -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);
}
}

View File

@@ -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");

View File

@@ -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);
}
}

View File

@@ -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());

View File

@@ -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);
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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);

View File

@@ -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();
}
}

View File

@@ -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);

View File

@@ -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();
}
}

View File

@@ -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");

View File

@@ -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");

View File

@@ -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 {

View File

@@ -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();
}
}

View File

@@ -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()