Monday 12 March 2007

Unit Testing in Java

I'm sold on JUnit testing. I've been using it for 3 or 4 years now and it has proved invaluable in that time.

New techniques (at least to me) keep popping up all the time. Originally I setup a unit test database with lots of static tables. I had a fixed dataset that didn't need to change.

And then other developers joined the project...

And they started writing to those tables as part of their tests...

And changing schemas....

Suddenly we couldn't run tests simultaneously (no transactions were used - doh). We couldn't test branches of old code (because schemas had changed).

The solution: twofold.

The first one was to use HSQLDB together with inmemory tables. This works really well but you end up having code to create SQL tables duplicated in the actual database, a DDL file and in the unit test code. Not an enormous problem because if the tables change - the tests fail!

The second one was to use interfaces more, if the table was being used to provide static we just create an interface on the cache and implement that interface in the unit test. This works very well indeed.

Another solution, suggested by a new team member, is to use Spring. This has some nifty little classes to help with testing. More soon....

No comments: