JUnit Testing JNDI Datasources: Thinking outside of the Container

When it comes to JNDI Datasources, you really need a fast way to test outside of the container without changing all of your configuration just because your testing.

java programming tipsOne of the problems with using a JNDI Datasource is Unit Testing outside of the container. Testing in the container is a pain and it’s slow if you are fixing bugs or just testing to make sure what you have works after a few changes. It’s OK for system tests.

Another option might be to have one set of configuration for the container and one for Unit Testing. An example might be to have two files controlled by your classpath or even worse, one file which you comment/uncomment to get the datasource you need. Then hope you package up the right configuration for the release.

What you really need a fast way to test outside of the container without changing all of your configuration just because your testing. Thankfully, spring provides a nice way to test your application outside of the container. Just bind your resource to a SimpleNamingContext mock and voila!

You may have found Rod Johnson’s simple forum post saying just that: Problem running JUNIT test with JNDI datasource.

If you found yourself looking for a little bit more explanation, here it is.

This example uses Spring 1.2.7 and JDK 1.4. You’ll have to write your own JDBC datasource bean definition for whatever database you are using. But, here is an example snippet from a unit test which binds a local JDBC datasource to a JNDI mock for testing.

 

import javax.sql.DataSource;

import junit.framework.TestCase;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.mock.jndi.SimpleNamingContextBuilder;
public class JndiTest extends TestCase {

	private static String[] springFiles = { "beans/my-beans-config.xml" };

	private ClassPathXmlApplicationContext context;

	public void testJndi( ) throws Exception {

		context = new ClassPathXmlApplicationContext(springFiles);

		SimpleNamingContextBuilder builder =

			SimpleNamingContextBuilder.emptyActivatedContextBuilder();

		DataSource ds = (DataSource) context.getBean("dataSource");

		builder.bind("jndi:jdbc/DataSource", ds);

		// your dataSource bean is available as "jndi:jdbc/DataSource", now

	}

}

You’ll need a few jars to make that work. In my case, I needed:

  • junit
  • spring
  • spring-mock
  • commons-logging
  • log4j
  • commons-pool
  • commons-dbcp
  • your favorite database jar

I hope that helps!

Author: eric

Eric Holsinger is a software professional and photography enthusiast in Southern Maine.

One thought on “JUnit Testing JNDI Datasources: Thinking outside of the Container”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.