简体   繁体   中英

JUnit Servlets testing with jndi lookup for the datasource

如何对使用jndi查找数据源(JDBC)的servlet进行单元测试?

I run the following code in the before class method.

    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(""); // <--insert url to database here
        ds.setUser("username"); //<-- self explanatory
        ds.setPassword("password"); //<-- self explanatory

        ic.bind("java:/comp/env/jdbc/examplename", ds); //<--insert name of binding here
    } catch (NamingException ex) {
        ex.printStackTrace();
    } catch (SQLException ex){
        ex.printStackTrace();
    }

I am using Tomcat as my server so I also had to reference the following jar files located in the tomcat\\bin directory:

  1. tomcat-juli.jar
  2. bootstrap.jar
  3. commons-daemon.jar

I hope this helps you

Setup the JNDI context in your @Before (or @BeforeClass ) methods, by manually creating the datasource.

(The answer is only guiding, but I can't provide anything concrete, since you haven't provided anything concrete)

如果问题是您需要JNDI,那么有一个简单的独立实现,可以在应用程序和单元测试场景中使用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM