Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring/Hibernate/Junit example of testing DAO against HSQLDB

Tags:

I'm working on trying to implement a JUnit test to check the functionality of a DAO. (The DAO will create/read a basic object/table relationship).

The trouble I'm having is the persistence of the DAO (for the non-test code) is being completed through an in-house solution using Spring/Hibernate, which eliminates the usual *.hbm.xmltemplates that most examples I have found contain.

Because of this, I'm having some trouble understanding how to setup a JUnit test to implement the DAO to create/read (just very basic functionality) to an in-memory HSQLDB. I have found a few examples, but the usage of the in-house persistence means I can't extend some of the classes the examples show (I can't seem to get the application-context.xml setup properly).

Can anyone suggest any projects/examples I could take a look at (or any documentation) to further my understanding of the best way to implement this test functionality? I feel like this should be really simple, but I keep running into problems implementing the examples I have found.

edit:

Here's my solution for better readability, for anyone who needs a hand getting things going:

  • My TestClass:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:applicationContextTest-Example.xml")
    @Transactional
    public class ExampleDaoTest extends AbstractTransactionalJUnit4SpringContextTests {
        @Resource(name = "sessionFactory")
        private SessionFactory exampleSessionFactory;
    
        @Resource(name = "exampleDao")
        private ExampleDao exampleDao;
    
  • My applicationContext.xml file:

    <!-- List of Daos to be tested -->
    <bean id="exampleDao" class="org.myExample.ExampleDao"/>
    
    <!-- Datasource -->
    <bean id="example_dataSource"
          class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem:ExampleTest"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>
    
    <!-- Session Factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="example_dataSource"/>
        <property name="annotatedClasses">
            <list>
                <value>org.myExample.ExampleClass</value>
            </list>
        </property>
        <property name="hibernateProperties">
            .... left to user to choose properties
        </property>
    </bean>