f-angi
8/23/2016 - 8:37 AM

Programmatic creation of a JNDI datasource inside a Junit test. Assuming that inside the Catalina context is defined a data source named Dat

Programmatic creation of a JNDI datasource inside a Junit test. Assuming that inside the Catalina context is defined a data source named DataSourceName.

<Resource auth="Container" driverClassName="oracle.jdbc.OracleDriver" maxActive="20" maxIdle="10" maxWait="-1" name="jdbc/DataSourceName" password="password" type="javax.sql.DataSource" url="jdbc:oracle:thin:@host" username="username"/>

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class Test {
    @BeforeClass
    public static void setUpDataSource() throws NamingException, SQLException {

        // Create initial context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
        InitialContext ic = new InitialContext();

        ic.createSubcontext("java:");
        ic.createSubcontext("java:/comp");
        ic.createSubcontext("java:/comp/env");
        ic.createSubcontext("java:/comp/env/jdbc");

        // Construct DataSource
        OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
        ds.setURL("jdbc:oracle:thin:@host");
        ds.setUser("username");
        ds.setPassword("password");

        ic.bind("java:/comp/env/jdbc/DataSourceName", ds);
    }
}