Wednesday Jan 16, 2008

Injecting JNDI datasources for JUnit Tests outside of a container

I was working on some webservices that we're moving into libraries the other day, and needed to run a full set of tests using junit, but outside of a container. I didn't want to create and deploy an entire test harness, I just wanted to run the junit tests in the nb ide. But I couldn't get the test to inject the datasource resource so it was usable. I finally got it working, but I'll spare you all the pain I went through to get here. Here's how I did it in my test class:
    @BeforeClass
    public static void setUpClass() throws Exception {
        // rcarver - setup the jndi context and the datasource
        try {
            // 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:port:db");
            ds.setUser("MY_USER_NAME");
            ds.setPassword("MY_USER_PASSWORD");
            
            ic.bind("java:/comp/env/jdbc/nameofmyjdbcresource", ds);
        } catch (NamingException ex) {
            Logger.getLogger(MyDAOTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
As you can see, in this case I used the OracleConnectionPoolDataSource, you should use the datasource for your db connection. Don't forget to link in the appropriate db jar (in my case it was ojdbc14.jar) The code that is used to retrieve the datasource (which works for test and production) looks like this:
        Context initContext = new InitialContext();
        Context webContext = (Context)initContext.lookup("java:/comp/env");

        DataSource ds = (DataSource) webContext.lookup("jdbc/nameofmyjdbcresource");
viola!
About

Randy Carver

Search

Categories
Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today