Lets take a simple DAO class that save a User object to the database:
Now in order to test this you would write a test class as below extending from AbstractTransactionalDataSourceSpringContextTests class.
The test class has to implement the protected String getConfigLocations() method from the base class and return a String array of Spring config files which will be used to initialize the Spring context.
UserDao and SessionFactory properties are defined with the setter methods and the base class will take care of injecting them automatically from the Spring context. Auto wiring will not work if there are multiple objects implementing the same interface. In such a case you can remove the setter method and retrieve the object using the exposed applicationContext as below.
The base class also exposes a JDBC template object (jdbcTemplate) that can be used to query data or setup test data in the database. Note that you need to have a data source and a transaction manager defined in your Spring config in order to use the AbstractTransactionalDataSourceSpringContextTests base class. The data source defined in the config file will be bound to the exposed JDBC template.
In the testSave method first we verify there is no record in the User table where first name equals to 'Firstname' using the jdbc template object. Then we call the save method on the UserDao passing it a User object.
Now we simple verify there is a record in the table where first name equals to 'Firstname'. Before running the query we flush the current Hibernate session to make sure jdbcTemplate can see the newly added record.
Thats it and when the testSave method exits the current transaction will be rolled back and the record inserted to the User table will not be saved. This is great as your test database will always be at a know state at the start and end of a test method.
The spring config file will like below (test-spring-config.xml) :
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">