title: Integration tests with spring-security and ldap
body: <p><a href="https://stackoverflow.com/questions/544550/spring-embedded-ldap-server-in-unit-tests">Spring embedded ldap server in unit tests</a> is similar, however no answer was given that suites me.</p>
  
  <p>I can run my integration tests with spring and the embedded ldap server of spring-security without any problems.
  However, I haven't find a way yet to clear the embedded ldap server and load the ldif again to provide a common test environment.</p>
  
  <p>LdapTestUtils of spring-ldap provides a cleanAndSetup() method. However, this does not work with the suggested version (1.5.5) of apache-ds, as LdifFileLoader now requires a <em>CoreSession</em> instead of the <em>DirContext</em> provided by LdapTestUtils. This causes a </p>
  
  <pre><code>java.lang.NoSuchMethodError:
  org.apache.directory.server.protocol.shared.store.LdifFileLoader.&lt;init&gt;(Ljavax/naming/directory/DirContext;Ljava/lang/String;)
  </code></pre>
  
  <p>I only want a method that clear the embedded ldap server and fills it with the ldif file again (as done on startup).
  Does anybody have an idea regarding this?</p>
  
  <p>Version: spring 3.1, spring-ldap 1.3, spring-security 3.1, apache-ds 1.5.5</p>
  
  <p><strong>Solution (Thanks to Luke Taylor):</strong></p>
  
  <pre><code>@Inject
  private ApplicationContext applicationContext;
  
  @Before
  public void reloadLdapDirectory() throws NamingException, IOException{
      ApacheDSContainer apacheDSContainer = (ApacheDSContainer) applicationContext.getBean(BeanIds.EMBEDDED_APACHE_DS);
      LdapTestUtils.clearSubContexts(contextSource, DistinguishedName.EMPTY_PATH);
  
      ClassPathResource classPathResource = new ClassPathResource("ldap.ldif");
  
      File tempFile = File.createTempFile("spring_ldap_test", ".ldif");
      try {
          InputStream inputStream = classPathResource.getInputStream();
          IOUtils.copy(inputStream, new FileOutputStream(tempFile));
          LdifFileLoader fileLoader = new LdifFileLoader(apacheDSContainer.getService().getAdminSession(), tempFile.getAbsolutePath());
          fileLoader.execute();
      }
      finally {
          try {
              tempFile.delete();
          }
          catch (Exception e) {
              // Ignore this
          }
      }
  }
  </code></pre>