Another alternative is to look at how the integration tests in Spring LDAP are managed. It's a bit verbose, but if you browse the following files in src/itest/java, you'll see how it's done:
conf/ldapTemplateTestContext.xml
conf/apacheDsContext.xml
org/springframework/ldap/ConfigEnvHelper
org/springframework/ldap/LdapServerManager
setup_data.ldif
ldap.properties
Basically we start a new in-memory server instance for each test, create a partition in it, and load an LDIF file with test data.
The handling of the server is perhaps slightly non-intuitive. First, you plug in ApacheDS by setting the initialcontext factory to be the ApacheDS ServerContextFactory. You start a server instance by creating an InitialContext. You shut down the server instance by adding a ShutdownConfiguration to the environment and then creating an InitialContext again.
Here is an example of shutting down the server:
Code:
public class LdapServerManager implements InitializingBean {
...
public void shutdown() throws NamingException {
Properties env = new Properties();
env.setProperty(Context.INITIAL_CONTEXT_FACTORY,
ServerContextFactory.class.getName());
...
ShutdownConfiguration configuration = new ShutdownConfiguration();
env.putAll(configuration.toJndiEnvironment());
new InitialContext(env);
}
}
We start the server simply by configuring it as a Spring bean:
Code:
<bean name="serverContext" class="javax.naming.InitialContext">
<constructor-arg>
<bean class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetObject" ref="configEnvHelper" />
<property name="propertyPath" value="env" />
</bean>
</constructor-arg>
</bean>
<bean id="configEnvHelper" class="org.springframework.ldap.ConfigEnvHelper">
...
</bean>
The configEnvHelper bean sets the initialcontext factory, the server working directory, and other configuration properties in afterPropertiesSet:
Code:
public class ConfigEnvHelper implements InitializingBean {
...
public void afterPropertiesSet() throws Exception {
initialEnv.put(Context.INITIAL_CONTEXT_FACTORY, ServerContextFactory.class.getName());
...
}
Admittedly, it's convoluted, but it enables repeatable integration tests towards a real LDAP server without the hassles of installing and maintaining a server. Anyone that checks out the source code get this benefit. Just point to the src/itest/java source folder and run it as a JUnit test.