Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Last active June 7, 2020 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterkeller/6d9993b440c4f0bf0cffc71b595df1bb to your computer and use it in GitHub Desktop.
Save peterkeller/6d9993b440c4f0bf0cffc71b595df1bb to your computer and use it in GitHub Desktop.
Starting in memory ldap server for JUnit 5 tests
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
dependencies {
compile 'com.unboundid:unboundid-ldapsdk:5.1.0'
compile 'org.junit.jupiter:junit-jupiter:5.6.2'
compile 'org.springframework.boot:spring-boot-starter-parent:2.3.0'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
package ch.keller.test.extension;
import com.unboundid.ldap.listener.InMemoryDirectoryServer;
import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
import com.unboundid.ldap.listener.InMemoryListenerConfig;
import com.unboundid.ldif.LDIFReader;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.SocketUtils;
public class LdapExtension implements BeforeAllCallback, AfterAllCallback {
public final int port;
private static final Logger LOG = LoggerFactory.getLogger(LdapExtension.class);
private InMemoryDirectoryServer server;
public LdapExtension() {
this.port = SocketUtils.findAvailableTcpPort();
public LdapExtension(int port) {
this.port = port;
public void beforeAll(final ExtensionContext context) throws Exception {
try (final InputStream inputStream = getClass().getResourceAsStream("/my.ldif")) {"LDAP server starting...");
final InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("o=myorganization,c=com");
config.setSchema(null); // must be set or initialization fails with LDAPException
config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", port));
final LDIFReader reader = new LDIFReader(inputStream);
server = new InMemoryDirectoryServer(config);
server.importFromLDIF(true, reader);
server.startListening();"LDAP server started. Listen on port " + server.getListenPort());
public void afterAll(final ExtensionContext context) {
public int getPort() {
return port;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.ldap.core.LdapTemplate;
public class MyTest {
static LdapExtension ldapExtension = new LdapExtension();
static void ldapProperties(DynamicPropertyRegistry registry) {
registry.add("ldap.url", () -> "ldap://localhost:" + ldapExtension.getPort());
private LdapTemplate ldapTemplate;
public doTest() {
// Use ldapTemplate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment