0

I'm using a Resource tag in tomcat's context.xml file to store database connection info. I access it in my jersey servlet like this:

Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup(DB_SOURCE_CONTEXT);
return ds.getConnection();

For unit testing, I'm using jersey-test and grizzly2, rather than deploying to tomcat. I'm trying to set the connection properties to use a test DB (currently MySQL, but I will change it to DBUnit next) in the unit test class:

@BeforeClass
public static void initializeTest() throws NamingException
{
  Context initContext = new InitialContext();
  Context envContext  = (Context)initContext.lookup("java:/comp/env");
  BasicDataSource dataSource = new BasicDataSource();
  dataSource.setDriverClassName("com.mysql.jdbc.Driver");
  dataSource.setUsername("root");
  dataSource.setPassword("");
  dataSource.setUrl(TEST_DB_URL);
  dataSource.setMaxTotal(10);
  dataSource.setMaxIdle(5);
  dataSource.setInitialSize(5);
  dataSource.setValidationQuery("SELECT 1");
  envContext.bind(DB_SOURCE_CONTEXT, dataSource);
}

But I get the following exception, so it's clearly not the correct way to do it:

javax.naming.NoInitialContextException: Need to specify class name in environment or
system property, or as an applet parameter, or in an application resource file:
java.naming.factory.initial

How can I set these values so the Context reading code in the servlet reads the test values?

kwiqsilver
  • 1,017
  • 2
  • 11
  • 24

1 Answers1

0

I have had a similar issue when using glassfish and creating a context for testing.

You need to provide some properties for the InitialContext so that it can build itself correctly.

For example:

Hashtable<String, String> props = new Hashtable<>();
props.put("java.naming.factory.initial","com.sun.enterprise.naming.impl.SerialInitContextFactory");
props.put("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.put("java.naming.factory.state","com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
InitialContext ctx = new InitialContext(props);

Hope this helps.

Ed Mackenzie
  • 679
  • 6
  • 16