hibernateunit-testingjpa-2.0data-generationstub-data-generation

Test data generator for JPA or Hibernate


Are there any tools or libraries that can be used to generate test data using JPA or entity beans? I believe this will be very helpful for unit testing where we can have an in memory database with data dynamically generated just when we start our testing. So, there will be no communication with actual DB servers and not any waste of time.

I was only able to find JPAMock. But it is still under development. It would be nice if someone could provide a good pointer.

Thanks a lot.


Solution

  • I use DBUnit in conjunction with H2 database and untils & Spring. Works nicely:

    @SpringApplicationContext({ "classpath:test-context-dbunit.xml" })
    @Transactional(TransactionMode.ROLLBACK)
    @DataSet
    public class ApplicationDaoTest extends UnitilsTestNG {
    
        @SpringBeanByType
        private ApplicationDao applicationDao;
    
        @Test
        public void findAll() throws Exception {
            List<Application> actual = applicationDao.findAll();
            assertNotNull(actual);
            assertEquals(actual.size(), 3);
        }
    }
    

    The data is set in an XML file:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <dataset>
        <APPLICATION APPLICATION_ID="1" name="APP3" enabled="1" application_type="TRADE" api_key="AK1" auto_create_topics="1" />
        <APPLICATION APPLICATION_ID="2" name="APP1" enabled="1" application_type="TRADE" api_key="AK2" auto_create_topics="1" />
        <APPLICATION APPLICATION_ID="3" name="APP2" enabled="0" application_type="TRADE" api_key="AK3" auto_create_topics="1" />
    </dataset> 
    

    In Spring test context you define your datasource as such:

    <bean id="dataSource" class="org.unitils.database.UnitilsDataSourceFactoryBean"/>
    

    As dialect you use: org.hibernate.dialect.H2Dialect

    Finally a unitils.properties in your classpath like:

    database.driverClassName=org.h2.Driver
    database.url=jdbc:h2:mem:test
    database.user=sa
    database.password=
    database.schemaNames=public
    database.dialect=hsqldb
    

    UPDATE

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="..."/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            </props>
        </property>
    </bean>