Skip to main content

Using mock naming contexts for testing

Posted by simongbrown on November 21, 2003 at 6:48 AM PST

Say for example that you want to unit test a Service Locator - a class that looks up data sources, topics, queues, etc from JNDI. How would you go about doing this?

One option would be to simply setup a JNDI environment inside a J2EE application server and write some JUnit tests to run inside the container. While this works, ideally you may want your unit tests to run independently and quickly.

The option we've just taken is to use a Mock Objects approach, therefore enabling us to run the tests during our normal unit test cycle. The one tiny problem that we ran into was that the service locator itself is responsible for creating a naming context by creating a new InitialContext instance, meaning that it's harder to get a mock context in there. The solution? Just write a mock InitialContextFactory as follows.

import javax.naming.Context;
import javax.naming.spi.InitialContextFactory;

* Provides a JNDI initial context factory for the MockContext.
public class MockInitialContextFactory implements InitialContextFactory {

    public Context getInitialContext(Hashtable env) {
        return new MockContext();


Then, when you want to run your tests, just stick a file on your classpath like this.


At runtime, the call to new InitialContext() uses the mock factory and results in the creation of a mock context. Just remember not to deploy the properties file in production!

Related Topics >>