Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > how to test jndi connection pooling

Thread Tools

how to test jndi connection pooling

Posts: n/a
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

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"
username="myApp_user" password="myApp_password"

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"))

It is working fine for me.

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

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

Any Suggestions ?

Reply With Quote
Harry Bosch
Posts: n/a
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

your test case:

DataSource ds;

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

protected void myTest() {
MyClassToTest myClass = new MyClassToTest();
//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.

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
why use ENC JNDI (java:comp/env) instead of JNDI name ? Mick Java 2 02-23-2005 12:50 PM
Need Help with Hibernate - "Not binding factory to JNDI, no JNDI name configured" Mike S Java 0 09-16-2004 09:58 PM
connection pooling error Chris Szabo ASP .Net 6 08-19-2003 07:19 PM
connection pooling Trevor Hartman ASP .Net 2 07-28-2003 07:58 PM
test test test test test test test Computer Support 2 07-02-2003 06:02 PM