Sunday, June 21, 2009

Unit Test Helper

Working on JUnit is fun and great but always remember a golden rule "Never change a good design just to make it accessable/runnable by JUnit". Let me elaborate on this statement to tell you what exactly I meant. In our code we write data access layer, which creates connections and execute sql.

Specially in Web Application, connections are often managed inside container and are accessed by our code using JNDI. This is one of the industry best practices. Problem is how to test that code outside the Container. How to make that code JUnit accessible.

Normally we might make some changes in our code in order to make JUnit run outside container, DON'T. With the above statement I meant these kind of changes specially. But the question is what is the solution for this situation. Should you leave that code untested? No, you can still test that code. And I am not going to talk about any new testing methodology either. You can test the same code with simple JUnit.

This is made possible a small helper jar called JRUnitTestHelper from Java Ranch. This junit utility helps create JNDI based datasources and connections at the run time to assist junit test the code efficiently.

Using this jar is very very simple, put this jar in your classpath while running your junit test and call these two lines

if(JNDIUnitTestHelper.notInitialized()){
JNDIUnitTestHelper.init("jndi_unit_test_helper.properties");
}

And of course please mention your connection details like IP, port, username etc in this "jndi_unit_test_helper.properties" properties file. Please feel free to shoot me emails if you have any questions.

0 comments:

 

Site Info

Text

Java 2 Enterprise Edition Copyright © 2009 Community is Designed by Bie