This is probably fairly well known, but I couldn’t find any doc on it when I searched so I’ll put it up here.
First off: Don’t load your Spring Context in your tests unless you absolutely have to. Some integration tests should load it, but keep it to a minimum. Loading the context is expensive, especially if you load up Hibernate and maybe H2 in that context.
Avoid loading the context is important both for speed and design. I have seen way too many tests where the context is loaded just because someone don’t want to do mocking. Besides, if you have to do a lot of mocking your design is usually too coupled, and should be changed.
So how can you speed up your tests in Maven?
- Put them in a suite
- And make sure they load the same context. Not the actual context object, but an array of strings of the context files in the same order and file names. See http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/test/AbstractSingleSpringContextTests.html#getConfigLocations().
Spring will cache the context and make sure it is only loaded once. But due to details I have not studied; in Maven, this only works for the tests that are in the same suite. It should work with fork=once on the surefire-plugin, but for some reason we need the suites too. Test which one works for you.
Drawbacks? If there is state in your context (database, stateful services) you will have created a dependency between your tests. That’s why, when it comes to database-testing you should use the AbstractTransactionalSpringContextTests which will automatically roll back your changes at the end of your tests. If state is modified in a way that has nothing to do with your database use setDirty() to signal to Spring that the context should be recreated for the next test. Of course then you get the time penalty of recreation.