For unit testing purposes, I'm trying to set up JNDI to connect to a HSQLDB without using Tomcat. To do this I am using Simple-JNDI and following this website.
So first I created a class that will initialize the a JNDI Data Source:
import org.hsqldb.jdbc.JDBCDataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class JndiDataSource {
public void Initialize() throws NamingException {
// Create initial context
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.MemoryContextFactory");
System.setProperty("org.osjava.sj.jndi.shared", "true");
InitialContext ic = new InitialContext();
ic.createSubcontext("java:/comp/env/jdbc");
// Construct DataSource
JDBCDataSource ds = new JDBCDataSource();
ds.setDatabase("jdbc:hsqldb:hsql://localhost/xdb");
ds.setUser("SA");
ds.setPassword("");
// Put datasource in JNDI context
ic.bind("java:/comp/env/jdbc/myDS", ds);
}
}
Then in a unit test I'm calling Initialize()
and just attempting to lookup the Data Source.
import org.junit.jupiter.api.Test;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class JndiDataSourceTest {
@Test
public void testInitialize() throws NamingException {
JndiDataSource jds = new JndiDataSource();
jds.Initialize();
InitialContext ic = new InitialContext();
DataSource ds = (DataSource)ic.lookup("java:/comp/env/jdbc/myDS");
}
}
Unfortunately, when I try to debug this unit test it fails on the lookup, (DataSource)ic.lookup("java:/comp/env/jdbc/myDS");
The debugger says,
javax.naming.NameNotFoundException: java:/comp/env/jdbc/myDS
So the question is, what am I doing wrong?
May be it's a simple typo - IMHO it should be org.osjava.sj.memory.MemoryContextFactory