JUnit 4 Testing with DBUnit in Spring Hibernate Application

21-07-2016

HsqlDb Connection

1. Download hsqldb.zip file from here

2. Extract zip file

3. Open bin folder in the hsqldb folder

4. Edit runServer.bat file as follows:

cd ..\data
@java -classpath ../lib/hsqldb.jar org.hsqldb.server.Server -database.0 mem:sample -dbname.0 sample

5. Save and run runServer.bat file

6. After running this file you should see the command prompt as follows:

Spring applicationContext-test.xml File

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.codesenior.telif.service.mail">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <bean id="dataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="org.hsqldb.jdbcDriver"/>
        <property name="jdbcUrl" value="jdbc:hsqldb:hsql://localhost/sample"/>
        <property name="user" value="sa"/>
        <property name="password" value=""/>
        <property name="initialPoolSize" value="1"/>
        <property name="maxPoolSize" value="1"/>
        <property name="minPoolSize" value="1"/>
    </bean>
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.codesenior.telif.service.mail.model"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="hibernate.hbm2ddl.import_files">import.sql</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.connection.CharSet">utf8</prop>
                <prop key="hibernate.connection.characterEncoding">utf8</prop>
                <prop key="hibernate.connection.useUnicode">true</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <!--with hibernate 5, new_generator_mappings should be false-->
                <prop key="hibernate.id.new_generator_mappings">false</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
                <prop key="hibernate.generate_statistics">false</prop>
                <prop key="javax.persistence.validation.mode">none</prop>
                <prop key="hibernate.cache.region.factory_class">
                    org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
                </prop>
            </props>
        </property>
    </bean>
</beans>

Spring JUnit4 Example

import org.dbunit.database.DatabaseDataSourceConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.io.InputStream;

/**
 * DBUnitExample
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext-test.xml"})
public class DBUnitExampleTest {
    @Autowired
    private DataSource dataSource;

    @Before
    public void init() throws Exception{
        IDatabaseConnection connection=getConnection();
        try{
            DatabaseOperation.CLEAN_INSERT.execute(getConnection(), getDataSet());
        }finally {
            connection.close();
        }
    }

    @After
    public void after() throws Exception{
        IDatabaseConnection connection=getConnection();
        try{
            DatabaseOperation.DELETE_ALL.execute(getConnection(), getDataSet());
        }finally {
            connection.close();
        }
    }
    private IDatabaseConnection getConnection() throws Exception{

        return new DatabaseDataSourceConnection(dataSource);
    }

    private IDataSet getDataSet() throws Exception {
        InputStream in = getClass().getResourceAsStream("/data/full.xml");
        return new FlatXmlDataSetBuilder().build(in);
    }
    @Test
    public void testHello() throws Exception{
        System.out.println("hello");
    }
    @Test
    public void testHello1() throws Exception{
        System.out.println("hello1");
    }
}

© 2019 All rights reserved. Codesenior.COM