JRoller is down, and has been down for an hour or so - so I've decided to post this Spring Live entry here.
I discovered an interesting thing today about Spring and my JUnit tests. I noticed that the VelocityEngine I was setting on my
PositionManager was getting initialized once for each test* method in my Test. This means that
since my PositionManagerTest has 10 test methods - it would load the context 10 times.
Loading the context so many times was because the following code was in my Test's parent's
constructor:
ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
I suppose I expected any constructor-iniatialized variables to be initialized once and only
once. So I figured out a solution to make my JUnit tests run faster. By making the ctx
variable static, and loading the file in the member variables definition, I
greatly reduced the amount of time needed to run tests. Below is the new code I'm using:
protected static ApplicationContext ctx =
new ClassPathXmlApplicationContext("/applicationContext.xml");
By doing this, the ApplicationContext is only set once, and my tests run much faster. Here's
some performance comparisons from Struts Resume:
Average time to run "ant test-dao": 36 seconds
Average time to run "ant test-dao" after this change: 26 seconds
A 10 second improvement - that's crazy talk dontcha think?! I've tried it on single tests, as well as suites - and it seems to improve performance by approximately 30% across the board.
Because of this experience, I have to recommend that when you write JUnit tests that use Spring - you should initialize your ApplicationContext in a static member variable. It seems to be the best performing and logical choice. Of course, if I'm off my rocker - please let me know.
On a sidenote, it would be cool if Roller allowed me to turn off comments for a single post. I like how Simon posts stuff on java.net and then aggregates it to his personal weblog.