write Junit for JNDI



我在我的应用程序中使用了JNDI连接,它正在工作。但是我需要编写 Junits 来测试连接。我们不使用任何弹簧框架。这是我为获取 JNDI 连接而编写的方法。

public Connection getConnection() throws SQLException {
        DataSource ds = null;
        InitialContext ic = null;
        Connection con = null;
        try {
            ic = new InitialContext();
            ds = (DataSource) ic.lookup("java:/DBs");
            con = ds.getConnection();
            return con;
        } catch (Exception e) {
            throw new SQLException(e);
        }
}

您可以使用 spring-test 库附带的 SimpleNameContextBuilder。 即使您不使用 Spring,您也可以使用它,因为它不是特定于 Spring 的。

下面是在 JUnit 测试@Before中设置 JNDI 连接的示例。

package com.example;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;

public class SomeTest
{
   @Before
   public void contextSetup () throws Exception
   {
       SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
       DriverManagerDataSource dataSource = new DriverManagerDataSource("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:testdb", "sa", "");
       builder.bind("java:comp/env/jdbc/ds1", dataSource);
       builder.bind("java:comp/env/jdbc/ds2", dataSource);
   }
   @Test
   public void testSomething () throws Exception
   {
        /// test with JNDI
   }
}

更新:此解决方案还使用Spring的DriverManagerDataSource。 如果你想使用它,你还需要spring-jdbc库。 但是您不必使用它,您可以创建任何您喜欢的对象并将其放入SimpleNamingContextBuilder中。 例如,DBCP 连接池、JavaMail 会话等。

OK. After lot of searching i found a solution.And it is working for me. I want to share this to everybody. Hope this thing might help people who are having the same issue. Please add the below code.Add ojdb6.jar and naming-common-4.1.31.jar in your test libraries                                               
 @BeforeClass
    public static void setUpClass() throws Exception {
        try {
            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");
            OracleConnectionPoolDataSource ocpds = new OracleConnectionPoolDataSource();
            ocpds.setURL("your URL");
            ocpds.setUser("your username");
            ocpds.setPassword("your password");
            ic.bind("java:/yourJNDIName", ocpds);
        } catch (NamingException ex) {
            Logger.getLogger(yourTesTClass.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

如果这是在应用服务器外部运行的,则可能需要为对 InitialContext 的调用提供参数。 但也要意识到,许多数据源实现是不可序列化的,因此它们不会在容器之外工作。

您正在编写的是集成测试,它应该在容器中运行。

最新更新