Search code examples
javaunit-testingjakarta-eejmsjndi

How do I unit test my implementation of javax.naming.Referenceable?


I'm developing a JMS provider to spec, and it requires that certain objects implement Referenceable. I've implemented getReference() on my JMS ConnectionFactory, and I've created an object factory to convert the References to objects. I am trying to figure out an effective way to unit test.

Spring's SimpleNamingContext does not fit the bill:

Context ctx = new SimpleNamingContext();
ctx.bind("testFactory", connFactory);
ConnectionFactory testConnFactory = (ConnectionFactory)ctx.lookup("testFactory");
Assert.assertEquals(connFactor, testConnFactory);

It gives me a false positive because SimpleNamingContext is a mock object. The objects are identical and neither getReference nor my object factory gets called.

I've looked into possibly wiring up a Jetty server to test, but this might be a tad more than I need here.

Ideally, I'm looking for a simple Context class I can wire straight into like the example above that will actually execute my JNDI-specific methods behind the scenes. Short of that, I'll take other recommendations on how to unit test this.

I'm using the Java Referenceable Objects and References tutorials for defining how they should be implemented.

Thanks in advance.

UPDATE: I'm not sure this is relevant, but here is the object factory, and here is the Referenceable.getReference() implementation that I'm trying to test.

CONCLUSION: Per Nicholas' advice below I used RefFSContextFactory. Here was the code I used to generate the context in my JUnit test:

@Rule public TemporaryFolder folder = new TemporaryFolder();

private Context getContext() throws MalformedURLException, NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, 
        "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, folder.getRoot().toURI().toURL().toString());
    Context ctx = new InitialContext(env);
    Assert.assertNotNull(ctx);
    return ctx;
}

Full source code for now-working test class is here.


Solution

  • You can use the File System Context Provider. Here's one source for the jar. There's an example here.