|
|
||
Simon Brown's BlogPatterns ArchivesUsing mock naming contexts for testingPosted by simongbrown on November 21, 2003 at 06:48 AM | Permalink | Comments (7)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
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 java.naming.factory.initial=some.package.mock.MockInitialContextFactory
At runtime, the call to | ||
|
|