How to unit test a DAO class in Java

H

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.

Maven:

<dependency>
    <groupId>org.easymock</groupId>
    <artifactId>easymock</artifactId>
    <version>3.1</version>
    <scope>test</scope>
</dependency>

In your spring xml, add the following code:

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

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

<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}" />
</bean>

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

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

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

@Autowired
private YourClassDao dao;

@Override
@Qualifier("yourDatasource")
public void setDataSource(DataSource dataSource) {
    // remain it empty
}

Now you can add your test code to roll back

@Test
@Rollback(true)
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

Categories