how to test jndi connection pooling

R

Rahul

Hi all,

In my web application (deployed in tomcat) I am using JNDI for fetching
database connections.
I did this by defining a context in META-INF/context.xml of my
application.

Here is what lies in my context.xml file:

<Context path="/myApp" docBase="myApp" debug="5" reloadable="true"
privileged="true" crossContext="true">
<Resource name="jdbc/myApp" auth="Container"
type="javax.sql.DataSource" maxActive="30" maxIdle="10"
maxWait="6000"
username="myApp_user" password="myApp_password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/myDatabase"
removeAbandoned="true"
autoReconnect="true"
/>
</Context>



And this is the code I use to get a connection :

Context ctx = (Context) new InitialContext().lookup("java:comp/env");
if (ctx == null)
throw new Exception("No context available");

Connection connection = ((DataSource) ctx.lookup("jdbc/myApp"))
.getConnection();



It is working fine for me.

But now I want to write some unit tests of my DatabaseService classes
which
uses the above code to get a database connection.
But I don't know how to load the above context parameter, in a junit
test
case.

because without doing this I wont be able to get a database connection.


Any Suggestions ?
 
H

Harry Bosch

Well, this is another reason JNDI can really blow.

Anway, I would say that the easiest solution is to use a getter/setter
on the class that is going to be using a datasource. You can then
manually set up an datasouce and pass it to your class that you wish to
test. Basically, just stub out a DataSource class by implementing the
DataSource interface. You really only need to implement on method
(getConnection).

......
your test case:

DataSource ds;

protected void setUp() {
this.ds = new MyNewDataSource();
}

protected void myTest() {
MyClassToTest myClass = new MyClassToTest();
myClass.setDataSource(ds);
//do something
}

So, this new class should not be doing any JNDI lookups. The datasouce
should be set at runtime. The class shouldn't really know anything
about "Context" or JNDI. This is the idea of the POJO (Plain Old Java
Object [but aren't all java objects POJO?]);

I would suggest that in the future, look into something like the Spring
framework. It helps aleviate all this context and JNDI pain.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top