开发者

JUnit Servlets testing with jndi lookup for the datasource

开发者 https://www.devze.com 2022-12-15 19:01 出处:网络
How to make unit test of开发者_高级运维 servlets which uses jndi for lookup of datasource (JDBC) ?I run the following code in the before class method.

How to make unit test of开发者_高级运维 servlets which uses jndi for lookup of datasource (JDBC) ?


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)


If the problem is that you need JNDI then there is a simple standalone implementation which Can be used in applications and Unit tests scenarios.

0

精彩评论

暂无评论...
验证码 换一张
取 消