However, inspired by a Matt Raible blog post, I've recently started to use the AbstractTransactionalDataSourceSpringContextTests Spring class.
It's a long time since I want to post about this very interesting piece of thing.
This class provides an easy way to do unit, but I'd better say integration, tests over your Spring managed business objects and services, importing your Spring configuration, loading an appropriate Spring application context based on it, and wrapping your test methods each in a separated transaction which will be rolled back at the end of the method, avoiding so to insert test data into your database tables.
This sounds very good, because you don't have to manually configure Hibernate (it will be configured in your Spring application context), nor to manually manage transactions, nor to worry about unwanted test data!!!
So, you will simply have to:
- Subclass AbstractTransactionalDataSourceSpringContextTests.
- Overwrite the getConfigLocations() method, which must return an array of String objects, containing the location of your Spring configuration files.
You will be able to access your application context through the applicationContext instance variable.
- Write your test methods!!!!!
In your test methods, you can use all normal JUnit assert methods.
Moreover, you will be able to do a lot of other cool things, like accessing a jdbcTemplate variable for making SQL queries, committing transactions instead of rolling them back, or making special setup operations before every test method in the same context of its transaction or in another one.
Take a look at its javadoc.