JUnit JNDI DataSource helper package

“jrunittesthelper” is a library offered by JavaRanch Codebarn which can be used to simulate a JNDI lookup for database connections. It comes really handy for Junit test cases written to test production code which would typically require a JNDI lookup in order to instantiate the JDBC datasource.

Installation and Configuration

Download the zip file from JavaRanch Codebarn

Include the jrunittesthelper.jar in the classpath (ant or maven) of your test packages

Create a jndi_unit_test_helper.properties

Configure the jndi_unit_test_helper.properties as below:

PostgreSQL example


Oracle example



Import the package in your test source code:

  import com.javaranch.unittest.helper.sql.pool.JNDIUnitTestHelper;

Before each test initialise the helper package:

@Before public void beforeEachTest() throws Exception {

  // use system property to set full path to jndi_unit_test_helper.properties
  Properties props = new Properties(System.getProperties());
  String jndiUnitTestHelper = props.getProperty("jndi_unit_test_helper");
  if(JNDIUnitTestHelper.notInitialized()) {
    System.out.println("JNDIUnitTestHelper notInitialized");
  System.out.println("Jndi Context name is " + JNDIUnitTestHelper.getJndiName());

Then just use your production code:

@Test public void testRunSql() throws Exception {
   ProductionCode pc.executeSQL("update table set col1 = 100");

where for example ProductionCode can be something like that:

public ProductionCode {
 public static void executeSQL (String sql) {
  DataSource datasource = (DataSource)new InitialContext().lookup("myds");
  // execute sql
  // .....

Final notes

The helper package needs to be initialised with the full path (e.g. C:\data\prop\jndi_unit_test_helper.properties) to jndi_unit_test_helper.properties. I prefer doing this outside the source, like for instance (see Java code above) in a system property which I can set in my Ant build or Maven pom.

Also consider shutting down manually the helper:

@After public void afterEachTest() throws Exception {

I have used the library for some time before realising I could/should shut down the pool… however I never had any problem anyway. I guess it is always better to control the lifecycle of all resources involved and terminate them when no longer necessary.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: