I have an application in spring with database oracle running on JBOSS 7.1.
I want to test my service layer beans simply running a junit test.
In my spring context I use a jndi datasource like this:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jboss/datasources/myDatasource" />
<property name="resourceRef" value="true"/>
</bean>
When I run my junit test that loads the spring context test I receive an exception like:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [context.xml]: Invocation of init method failed; nested exception is 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
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
How can I inject the JNDI datasource in my tests without change my context in jboss?
Best Answer
According with this post, or this great blog post I found three ways to solve my issue, just create BeforeClass method in your JUnitTest Class.
I post it for the community:
- Solution 1
This solution, requires the catalina.jar and the oracledriver in your classpath:
if you use maven you can put in your pom:
- Solution 2
This solution, requires commons-dbcp in your classpath:
in your pom:
- Solution 3
This solution uses the OracleConnectionPoolDataSource included in Oracle Driver: