【问题标题】:javax.naming.NoInitialContextException: while running JUNIT test cases in webservicesjavax.naming.NoInitialContextException:在 web 服务中运行 JUNIT 测试用例时
【发布时间】:2015-07-02 15:38:55
【问题描述】:

我的应用程序中所有可能的数据库连接都有 JNDI 配置。同时我正在使用 JUNIT 来测试我的应用程序。我发现我的 webservices 类调用成功连接,但通过 junit 测试类调用它时抛出错误。

我的 JNDI 设置是

public static Connection getConnectionPool() {
    Connection conn = null;
System.out.println("Creating connection pool.");
    try {
        Context initContext = new InitialContext();
        Context envContext  = (Context)initContext.lookup("java:/comp/env");
        DataSource ds = (DataSource)envContext.lookup(getJNDIName());
        conn = ds.getConnection();
    } catch (SQLException e1) {
        e1.printStackTrace();
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return conn;

}

private static String getJNDIName()
{
    if(!readJNDI)
    {
        try{
            Properties prop = new Properties();
            prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
            JNDIName = prop.getProperty("jndi.name");
            System.out.println("JNDIName : "+JNDIName);
            readJNDI = true;
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    return JNDIName;
}

下面提到的是错误。

javax.naming.NoInitialContextException: 需要指定类名 环境或系统属性,或作为小程序参数,或在 应用资源文件:java.naming.factory.initial

我该如何解决?

提前致谢。

【问题讨论】:

标签: java web-services soap junit jndi


【解决方案1】:

您应该使用本地数据源。

只需将 DataSource/TransactionManager 定义提取到一个单独的 XML 文件中,并在测试期间使用它而不是 JNDI 文件。

您仍然可以使用所有其余配置。

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多