Testing Your App Using Spring's AbstractTransactionalJUnit4SpringContextTests
AbstractTransactionalJUnit4SpringContextTests is a pretty long class name but it makes easy work of testing a Spring application which uses a database. This post will walk through a quick example of how to use the class while demonstrating it's usefulness. Let's get to the code.
The AbstractTrkrCoreTests class below extends AbstractTransactionalJUnit4SpringContextTests and sets up a few things needed by this application including the datasource and the Spring context configuration.
- @ContextConfiguration - accepts multiple locations of other Spring context files required for tests.
- TransactionConfiguration - is optional if you only have one transaction manager Spring bean definition. In this application there are several defined so this annotation is added here to define which transaction manager to use.
- @Autowired - sets up various DAOs commonly needed by tests which extend this class.
- @Qualifier - is used in the setDataSource method to choose a specific data source where there are more than one available from the Spring configuration. This annotation can be used for a class property or a method parameter to qualify which bean should be injected.
Next is an actual test class:
- @Before - a JUnit annotation which will be called prior to each @Test. The doSetup property here just ensures that the database setup is done just once for the tests in this class.
- deleteFromTables - helper method from AbstractTransactionalJUnit4SpringContextTests which will delete all the records in the tables passed to it. This all happens in the same transaction in which the tests are run. What this means is that the tables in question will be in the same state that they were before the test was run. This is especially helpful if you don't have a database sandbox and instead the database is shared among one or more developers.
- executeSqlScript - is another helper method which allows you to execute arbitrary SQL needed by the tests. In this case, two scripts are called to populate some test data.
- @Test - a JUnit annotation used to indicate a method as a test.
- The ordering of the parameters for deleteFromTables are important if foreign keys and/or other constraints are in place.
- If you're testing against a database which has a lot of data the deleteFromTables method may take a long time to execute. If the data volume is large enough, you may want to think about either reducing the number of records in the tables or simply using the data that's already there instead of deleting and inserting your own test data.