Spring comes with some extremely useful convenience classes for test automation using JUnit. In order to use them, be sure to add the spring-mock.jar to your project. Here's a rundown of what's available in the org.springframework.test package:
- AbstractSpringContextTests: abstract subclass of JUnit's TestCase. This class isn't very useful on its own, but it maintains a Spring context using a static Map to optimize performance while running tests. Due to a "design decision" in JUnit 3, classes are destroyed/recreated between each test method invocation, so persisting state across method calls can't be done by placing code in the test case's constructor. Storing dependencies in a static variable - while considering something of a "hack" - is a welcome improvement.
- AbstractDependencyInjectionSpringContextTests: abstract subclass of AbstractSpringContextTests. This class will read Spring XML files from the classpath and autowire any dependencies into your test case. Simply override getConfigLocations() and ensure that a setter exists for each dependency and Spring will do autowiring by type.
- AbstractTransactionalSpringContextTests: abstract subclass of AbstractDependencyInjectionSpringContextTests. This class will wrap test method calls in a transaction and automatically rollback after execution, vastly increasing performance and eliminating the need for messy setUp() and tearDown() code to setup the database. You must provide a bean in the context that implements PlatformTransactionManager in order for the transactionality to work.
- AbstractTransactionalDataSourceSpringContextTests: abstract subclass of AbstractTransactionalSpringContextTests. This class will autowire a DataSource bean into your test case, making database connectivity relatively painless.
These classes have been a lifesaver and the performance increases help make running tests fast and easy. One important note: these test classes still use the JUnit 3.x API. If you've moved to JUnit 4, you may need to write an adapter class or wait for the Spring team to release some updated code.