Tuesday, August 05, 2014

Mocking the InitialContext

Unit testing with JNDI

One of the issue's with unit tests is that it is not always easy to control the java.naming.InitialContext provided to the object under test.
Mock frameworks cannot create mocks for JRE classes like InitialContext, so how can we solve this challenge?

One solution could be to create a simple implementation for the javax.naming.spi.InitialContextFactory that returns a mock implementation provided by mockito. Through configuration, our implementation is then used.

public class InitialContextFactoryMock implements InitialContextFactory {

  private static Context mockContext;

  /**
    * The mockContext is created here to be able to use the {@link Context}
    * mock object while defining the expectations.
    * Remember to call this method each time a new test case is run.
    * 
    * @return a fresh {@link Context} mock.
    */
  public static Context getMockContext() {
    mockContext = mock(Context.class);

    return mockContext;
  }

  /**
    * This factory returns the {@link Context} mock created earlier.
    */
  public Context getInitialContext(Hashtable environment) throws NamingException {
    return mockContext;
  }
}

To use the InitialContextFactoryMock you need to specify it in the jndi.properties:


java.naming.factory.initial=the.mocks.InitialContextFactoryMock