The Artima Developer Community
Sponsored Link

Java Buzz Forum
Using mock naming contexts for testing

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Simon Brown

Posts: 636
Nickname: simonbrown
Registered: Jun, 2003

Simon Brown is a Java developer, architect and author.
Using mock naming contexts for testing Posted: Nov 21, 2003 7:30 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Simon Brown.
Original Post: Using mock naming contexts for testing
Feed Title: Simon Brown's weblog
Feed URL: http://www.simongbrown.com/blog/feed.xml?flavor=rss20&category=java
Feed Description: My thoughts on Java, software development and technology.
Latest Java Buzz Posts
Latest Java Buzz Posts by Simon Brown
Latest Posts From Simon Brown's weblog

Advertisement

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 jndi.properties file on your classpath like this.


java.naming.factory.initial=some.package.mock.MockInitialContextFactory

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!

Read: Using mock naming contexts for testing

Topic: First Day in the New Pad Previous Topic   Next Topic Topic: Streaming API for XML (StAX)

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use