Digital Sanctum

Personal blog of Shane Witbeck Tags · Archive · About

Testing Your App Using Spring's AbstractTransactionalJUnit4SpringContextTests

Published: 02 Oct 2009

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.

Extending AbstractTransactionalJUnit4SpringContextTests

The AbstractTrkrCoreTests class below extends AbstractTransactionalJUnit4SpringContextTests and sets up a few things needed by this application including the datasource and the Spring context configuration.

  1. @ContextConfiguration - accepts multiple locations of other Spring context files required for tests.
  2. 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.
  3. @Autowired - sets up various DAOs commonly needed by tests which extend this class.
  4. @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.

Test Implementation

Next is an actual test class:

  1. @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.
  2. 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.
  3. 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.
  4. @Test - a JUnit annotation used to indicate a method as a test.


  1. The ordering of the parameters for deleteFromTables are important if foreign keys and/or other constraints are in place.
  2. 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.
Tags: #testing#spring#junit#integration-testing