Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

Spring provides the SimpleNamingContextBuilder to handle cases where the code that is tested needs a JNDI environment entry.

Steps to using a Spring SimpleNamingContextBuilder

Using the Spring SimpleNamingContextBuilder is fairly easy. There are basically three steps:

  1. Instantiate the variable
  2. Bind objects to their JNDI keys in the context builder (repeat as necessary)
  3. Activate the context builder

Full Example Utility

In my case, I only had to bind one thing, the full path to a file.

Here is the utility class that I built to hold the code.


import org.springframework.mock.jndi.SimpleNamingContextBuilder;

import javax.naming.NamingException;
import java.nio.file.Path;
import java.nio.file.Paths;

import static;

 * @author norris.shelton
public class JunitTestUtility {

     * Performs environmental setup for Cam tests.
     * @throws NamingException if unable to activate the builder
     * @throws URISyntaxException if unable to find the properties file by a classloader
    public static void setup() throws NamingException, URISyntaxException {
            String camPropertiesFile = "";
        URL url = JunitTestUtility.class.getClassLoader().getResource(camPropertiesFile);
        if (url != null) {
            Path path = Paths.get(url.toURI());
            if (path != null) {
                SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
                builder.bind("cam.config.path", path.toString());
        } else {
            fail("Unable to find in src/test/resources");

How to reuse in a Junit test class

Once that is done, it is quite easy to reuse it. In my case, all of the test classes for a project needed that.

    public static void setup() throws Exception {

May 24th, 2016

Posted In: Java, java ninja, Javaninja, JUnit, Spring, TDD

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By :