When unit testing a class that queries an LDAP server using Java’s JNDI API I needed to replace the actual remote LDAP server with a mock LDAP access layer so that the unit test (remember, this is not an integration test) doesn’t depend on any external SW/HW. Few hours of googling haven’t yielded any suitable mock implementation and so I had to create my own one. It turned out to be an easy task after all. I hope it could be useful for you too.
To create a test implementation of LDAP/JNDI you need to:
- Hook you mock JNDI implementation into the JVM and make sure that you use it
- Actually implement the JNDI layer by implementing/mocking few (3) JNDI classes, mostly from the javax.naming.directory package
- Configure your mock implementation to return the data expected

