我编写了一些单元测试,这些测试引用了引用其他类的类,这些类依赖于WebSphere中定义的JDBC资源。有问题的单元测试实际上并不会触发任何数据库读取或写入,但它们引用的类是由Spring创建的,而Spring配置文件会尝试将JDBC资源注入其中。 Spring失败,出现此错误消息:
2013-07-31 13:46:17,008:could not load the application context org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [myApplication.xml]: Invocation of init method failed; nested exception is javax.naming.ServiceUnavailableException: Could not obtain an initial context due to a communication failure. Since no provider URL was specified, the default provider URL of "corbaloc:iiop:1.0@myMachineName.myCompany.com:2809/NameService" was used. Make sure that any bootstrap address information in the URL is correct and that the target name server is running. Possible causes other than an incorrect bootstrap address or unavailable name server include the network environment and workstation network configuration. [Root exception is org.omg.CORBA.TRANSIENT: java.net.ConnectException: Connection refused: connect:host=myMachineName.myCompany.com,port=2809 vmcid: IBM minor code: E02 completed: No] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(AccessController.java:224) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
dataSource
bean的定义很简单:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/dataSource" />
</bean>
即使在应用程序容器外部运行单元测试,如何让Spring正确连接到WebSphere JNDI?
答案 0 :(得分:1)
虽然没有连接到WebSphere实例,但在查看JNDI资源时,您始终可以使用SimpleNamingContextBuilder
包中的org.springframework.mock.jndi
。这允许您构建一个对象(比如一个DataSource,您自己直接绑定到远程JNDI服务),然后将其绑定到“模拟”JNDI服务,以便在测试时注入Spring Application Context。
要执行此操作,您需要在JUnit测试的@BeforeClass(静态)中执行此操作,以确保在应用程序上下文启动之前,可以使用JNDI绑定。 (因此App上下文可以在查找jdbc / dataSource时找到一些内容)
如果你打算在持续集成环境中使用它,我不建议连接另一台服务器,但是如果你正在做一次“一次性,手动测试”,你可以试试类似下面的内容;
@BeforeClass
public static void beforeClass() throws Exception {
Properties properties = new Properties();
//build your properties to the remove class
Context context = new InitialContext(properties);
//look up your dataSource
DataSource ds = (DataSource) context.lookup("");
//now build the simple
SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
builder.bind("jdbc/dataSource", ds);
}