【发布时间】:2011-03-28 12:58:09
【问题描述】:
我正在尝试在数据库“worker”类上运行 JUnit 测试,这些类在 InitialContext 上执行 jndi 查找以获得 DataSource。工作程序类通常在 Glassfish v3 App Server 上运行,该服务器已定义适当的 jdbc 资源。
代码在应用服务器上部署时运行良好,但不在 JUnit 测试环境中运行,因为显然它找不到 jndi 资源。所以我尝试在测试类中设置一个 InitialContext,将数据源绑定到适当的上下文,但它不起作用。
这是我在测试中的代码
@BeforeClass
public static void setUpClass() throws Exception {
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
SQLServerConnectionPoolDataSource testDS = new SQLServerConnectionPoolDataSource();
testDS.setServerName("sqlserveraddress");
testDS.setPortNumber(1433);
testDS.setDatabaseName("dbname");
testDS.setUser("username");
testDS.setPassword("password");
ic.bind("java:/comp/env/jdbc/TestDS", testDS);
DataWorker dw = DataWorker.getInstance();
} catch (NamingException ex) {
Logger.getLogger(TitleTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
那么DataWorker类有一个方法,代码如下,或多或少
InitialContext ic = null;
DataSource ds = null;
Connection c = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "SELECT column FROM table";
try{
ic = new InitialContext();
ds = (DataSource) ic.lookup("jdbc/TestDS");
c = ds.getConnection();
ps = c.prepareStatement(sql);
// Setup the Prepared Statement
rs = ps.executeQuery();
if(rs.next){
//Process Results
}
}catch(NamingException e){
throw new RuntimeException(e);
}finally{
//Close the ResultSet, PreparedStatement, Connection, InitialContext
}
如果我更改ic.createSubContext("java:/comp/env/jdbc");ic.bind("java:/comp/env/jdbc/TestDS",testDS);
行至ic.createSubContext("jdbc");ic.bind("jdbc/TestDS",testDS);
worker 类能够找到 DataSource,但未能给出错误提示“用户名无法登录服务器”。
如果我将在 JUnit 方法中创建的 DataSource 直接传递给 worker,它可以连接并运行查询。
所以,我想知道如何绑定一个不需要在 Web Container 中的工作类可以查找的 DataSource。
【问题讨论】:
标签: java jdbc junit glassfish datasource