Java 以编程方式设置单元测试的InitialContext

Java 以编程方式设置单元测试的InitialContext,java,jersey,jndi,junit4,Java,Jersey,Jndi,Junit4,我正在使用tomcat的context.xml文件中的资源标记来存储数据库连接信息。我在jersey servlet中访问它,如下所示: Context initContext = new InitialContext(); Context envContext = (Context)initContext.lookup("java:/comp/env"); DataSource ds = (DataSource)envContext.lookup(DB_SOURCE_CONTEXT); re

我正在使用tomcat的context.xml文件中的资源标记来存储数据库连接信息。我在jersey servlet中访问它,如下所示:

Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup(DB_SOURCE_CONTEXT);
return ds.getConnection();
对于单元测试,我使用jersey测试和grizzly2,而不是部署到tomcat。我试图将连接属性设置为使用当前MySQL的测试DB,但我将在unit test类中将其更改为DBUnit:

@BeforeClass
public static void initializeTest() throws NamingException
{
  Context initContext = new InitialContext();
  Context envContext  = (Context)initContext.lookup("java:/comp/env");
  BasicDataSource dataSource = new BasicDataSource();
  dataSource.setDriverClassName("com.mysql.jdbc.Driver");
  dataSource.setUsername("root");
  dataSource.setPassword("");
  dataSource.setUrl(TEST_DB_URL);
  dataSource.setMaxTotal(10);
  dataSource.setMaxIdle(5);
  dataSource.setInitialSize(5);
  dataSource.setValidationQuery("SELECT 1");
  envContext.bind(DB_SOURCE_CONTEXT, dataSource);
}
但我有以下例外,所以这显然不是正确的方法:

javax.naming.NoInitialContextException: Need to specify class name in environment or
system property, or as an applet parameter, or in an application resource file:
java.naming.factory.initial

如何设置这些值,以便servlet中的上下文读取代码读取测试值?

在使用glassfish并创建测试上下文时,我遇到了类似的问题

您需要为InitialContext提供一些属性,以便它能够正确地构建自身

例如:

Hashtable<String, String> props = new Hashtable<>();
props.put("java.naming.factory.initial","com.sun.enterprise.naming.impl.SerialInitContextFactory");
props.put("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.put("java.naming.factory.state","com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
InitialContext ctx = new InitialContext(props);
希望这有帮助。

请参阅