How to unit test a DAO class in Java


When you test a DAO class. It is possible you insert or update test data in your database. Of course, we don’t want that. There is a possibility to rollback the transaction when your test is completed.
We use EasyMock to do so.



In your spring xml, add the following code:

<bean id="yourTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="yourSessionFactory" />

<bean id="yourSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="yourDatasource" />
    <property name="hibernateProperties">
            <prop key="hibernate.dialect">${dialect}</prop>
            <prop key="hibernate.show_sql">${show_sql}</prop>
            <prop key="">${hbm2ddl}</prop>

<bean id="yourDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${driver}" />
    <property name="url" value="${url}" />
    <property name="username" value="${username}" />
    <property name="password" value="${password}" />

On top of your test class, you need to add the following code:

@ContextConfiguration(locations = { "classpath:spring.xml" })
public class TestDaoClass extends AbstractTransactionalJUnit4SpringContextTests {

then you need to add the following code to your test class

private YourClassDao dao;

public void setDataSource(DataSource dataSource) {
    // remain it empty

Now you can add your test code to roll back

public void testInsert() {
    <YourObject> classList1 = dao.getData();
    dao.insert(new YourObject());
    List<YourObject> classList2 = dao.getData();

    assertTrue(classList1.size() < classList2.size());

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Tag Cloud