Running JUnit from ant - beware the fork attribute
Recently I was looking at some of our JUnit tests to work out why they were taking quite so long to run. After going down a few dead ends, I found one big reason. The <junit> task in ant had its fork attribute set to “true”. I had naively assumed that this would fork a new JVM in which to run the tests. In fact, the documentation says:
fork: Run the tests in a separate VM.
but you need to look at the next line which tells you that the forkmode attribute controls how this forking occurs. The default is per test! So each test incurs a JVM startup overhead. No wonder the tests were taking a long time!
Having the tests run each in its own JVM also covers up problems. You can create whatever sort of mess you like and it’ll all be swept away before the next test runs. While going through a setting the forkmode to “once” I found a database connection leak in some test code. This sort of problem would be much more visible if all the test code was running in a single JVM and reminded me of Martin Fowler’s advice on testing resource pools.


July 9th, 2007 at 3:40 pm
Chris,
The documentation says
“perTest” creates a new VM for each TestCase class.
So its not quite as bad as each test method, but still pretty bad.
I’ve updated my ant scripts to include “once”.
Every little bit helps!
July 9th, 2007 at 3:43 pm
True enough, I was being a little sloppy with my terminology.