简体   繁体   English

在jUnit中设置JNDI数据源

[英]Setting up JNDI Datasource in jUnit

I am trying to set up some jUnit testing. 我正在尝试设置一些jUnit测试。 Our database is connected by the server using JNDI. 我们的数据库由服务器使用JNDI连接。 We have an xml describing the setup in root.xml. 我们有一个xml描述了root.xml中的设置。 How do I set up jUnit to hook up to the database? 如何设置jUnit以连接数据库? I'd prefer to have it just read the the stuff off of root.xml, but I'm open to setting it up anyway that works. 我宁愿让它只读取root.xml中的内容,但我仍然愿意设置它,无论如何都有效。

I've found this Blog: https://blogs.oracle.com/randystuph/entry/injecting_jndi_datasources_for_junit 我找到了这个博客: https//blogs.oracle.com/randystuph/entry/injecting_jndi_datasources_for_junit

About H2 Datasource: http://www.h2database.com/javadoc/org/h2/jdbcx/JdbcConnectionPool.html 关于H2数据源: http//www.h2database.com/javadoc/org/h2/jdbcx/JdbcConnectionPool.html

So for my Code: 所以我的代码:

package com.example.test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.h2.jdbcx.JdbcConnectionPool;

import junit.framework.TestCase;

public class JunitDataSource extends TestCase {

    public void setUp() 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");

            JdbcConnectionPool ds = JdbcConnectionPool.create(
                    "jdbc:h2:file:src/main/resources/test.db;FILE_LOCK=NO;MVCC=TRUE;DB_CLOSE_ON_EXIT=TRUE", "sa", "sasasa");
            // 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:/mydatasourcename", ds);
        } catch (NamingException ex) {
            Logger.getLogger(JunitDataSource.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void testSimple() throws Exception {

        // Obtain our environment naming context
        Context initCtx = new InitialContext();

        // Look up our datasource
        DataSource ds = (DataSource) initCtx.lookup("java:/mydatasourcename");

        Connection conn = ds.getConnection();
        Statement stmt = conn.createStatement();

        ResultSet rset = stmt.executeQuery("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES");


        while (rset.next()) {
          System.out.println("<<<\t"+rset.getString("TABLE_NAME"));
        }


    }

}

Note : I had to add Tomcat Library and the jars inside the Tomcat's bin directory to get it working 注意 :我必须在Tomcat的bin目录中添加Tomcat Library和jar才能使其正常工作

I found that the best way to do it is to use something called Simple-Jndi . 我发现最好的方法是使用名为Simple-Jndi的东西。

I added this to the maven file: 我把它添加到maven文件中:

    <dependency>
        <groupId>simple-jndi</groupId>
        <artifactId>simple-jndi</artifactId>
        <version>0.11.4.1</version>
        <scope>test</scope>
    </dependency>

You can download the the package here, the download contains an instruction manual. 您可以在此下载该软件包,下载包含说明手册。 http://code.google.com/p/osjava/downloads/detail?name=simple-jndi-0.11.4.1.zip&can=2&q= http://code.google.com/p/osjava/downloads/detail?name=simple-jndi-0.11.4.1.zip&can=2&q=

After adding to to your project you just have to add a couple of properties files, per the instructions. 添加到项目后,您只需按照说明添加几个属性文件。

However, after you add the dependency, I believe you can add your jndi resources programmatically instead of using properties files. 但是,在添加依赖项之后,我相信您可以以编程方式添加jndi资源,而不是使用属性文件。 You do something like this: (new InitialContext()).rebind("datasource",myDatasource); 你做这样的事情:( new InitialContext())。rebind(“datasource”,myDatasource);

I have used Simple-JNDI for this purpose for years now. 我已经将Simple-JNDI用于此目的多年了。 It gives you an in-memory implementation of a JNDI Service and allows you to populate the JNDI environment with objects defined in property files. 它为您提供了JNDI服务的内存实现,并允许您使用属性文件中定义的对象填充JNDI环境。 There is also support for loading datasources or connection pools configured in a file. 还支持加载文件中配置的数据源或连接池。

To get a connection pool you have to create a file like this: 要获得连接池,您必须创建如下文件:

type=javax.sql.DataSource
driver=com.sybase.jdbc3.jdbc.SybDriver
pool=myDataSource
url=jdbc:sybase:Tds:servername:5000
user=user
password=password 

In your application you can access the pool via 在您的应用程序中,您可以通过访问池

Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("path/to/your/connectionPool");

You can find more about it at https://github.com/h-thurow/Simple-JNDI . 您可以在https://github.com/h-thurow/Simple-JNDI找到更多相关信息。

TomcatJNDI helps with that situation too. TomcatJNDI也可以帮助解决这个问题。 It can process Tomcat's configuration files and creates the same JNDI environment as Tomcat does, but without starting a server. 它可以处理Tomcat的配置文件并创建与Tomcat相同的JNDI环境,但无需启动服务器。 So you can run classes with dependencies on Tomcat's JNDI environment in eg JUnit tests. 因此,您可以在例如JUnit测试中运行具有Tomcat JNDI环境依赖性的类。

TomcatJNDI tomcatJNDI = new TomcatJNDI();
tomcatJNDI.processContextXml(new File(“tomcat-root-dir/conf/context.xml”);
tomcatJNDI.start();

Then your classes can lookup the DataSource as when they would run in Tomcat. 然后,您的类可以查找DataSource,就像它们在Tomcat中运行一样。

More about TomcatJNDI can be found here: https://github.com/h-thurow/TomcatJNDI 有关TomcatJNDI的更多信息,请访问: https//github.com/h-thurow/TomcatJNDI

Would you like to create datasource programmatically on Application Server? 您想在Application Server上以编程方式创建数据源吗? Referene : 参考:

  1. Create Datasource JBoss 7 from program 从程序创建数据源JBoss 7
  2. Create Datasource Weblogic from program 从程序创建Datasource Weblogic

If you already created on Sever, 如果您已在Sever上创建,

public class YourTestCase {
    private java.sql.Connection conn;

    @BeforeClass
    public static void init() {
        /* Weblogic */
        try {
            Context ctx = null;
            Hashtable ht = new Hashtable();
            ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
            ht.put(Context.PROVIDER_URL, "t3://<your-host>:<your:post>");
            ctx = new InitialContext(ht);
            javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup ("<your-datasource-jndi-name>");
            conn = ds.getConnection();
        } catch(Exception e) {

        }
        /* JBoss 5*/
        Context.INITIAL_CONTEXT_FACTORY ---> org.jnp.interfaces.NamingContextFactory
        Context.PROVIDER_URL ---->http://localhost:1099
    }
    @AfterClass
    public static void finished() {
    }


    @Test
    public void testMethod() {
        try {
            Statement stmt = conn.createStatement();
            stmt.execute("select * from someTable");
            ResultSet rs = stmt.getResultSet();  
                // do operation
            stmt.close();
            conn.close();
            } catch (Exception e) {
                // a failure occurred
            } finally {
                try {ctx.close();
                } catch (Exception e) {
                }
            }
        }
    }
}

You can add Tomcat lib via maven dependency using below, to get it working. 您可以使用下面的maven依赖添加Tomcat lib,以使其正常工作。

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>catalina</artifactId>
    <version>6.0.18</version>
    <scope>test</scope>
</dependency>

I think you should try to mock out the database. 我想你应该试着模拟数据库。 Use appropriate framework, for example Mockito, it creates mocks and have DI abilities. 使用适当的框架,例如Mockito,它会创建模拟并具有DI功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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