ovod
ovod

Reputation: 1178

test hibernate entities with spring

I try to tests how hibernate Entities are persisted to database. I have 5 tests for 3 Entitites. All my attempts are unsuccessful((( I tried to use @Transactional annotation to bind each test to one transaction. But I could not (tried all combinations). Now I try to test it manually creating sessions and transactions. But now problem is that I dont know how to create one session for all tests. I tried @BeforeClass, but here problem is that it is static and I use Spring beans for session creation. Any ideas how I can test hibernate Entities?

Upvotes: 0

Views: 1446

Answers (1)

André Blaszczyk
André Blaszczyk

Reputation: 760

You can use a dedicated database like HSQLDB for testing you entities via DAO test classes.

You will need a:

  • Maven test profile
  • Spring configuration file (test context)
  • Script SQL to insert some data
  • DAO class test.

Maven test profile :

<profile>
    <id>test</id>
    <properties>
        <jpa.dialect>org.springframework.orm.jpa.vendor.HibernateJpaDialect</jpa.dialect>
        <jpa.vendor.adapter>HibernateJpaVendorAdapter</jpa.vendor.adapter>
        <jdbc.dialect>org.hibernate.dialect.HSQLDialect</jdbc.dialect>
        <jdbc.url>jdbc:hsqldb:mem:testDatabase</jdbc.url>
        <jdbc.driver>org.hsqldb.jdbcDriver</jdbc.driver>
        <jdbc.username>sa</jdbc.username>
        <jdbc.password></jdbc.password>
        <jdbc.format_sql>true</jdbc.format_sql>
        <jdbc.show_sql>true</jdbc.show_sql>
        <!-- import.sql is read : it must have this name and be in classpath -->
        <jpa.generateDdl>true</jpa.generateDdl>
        <hibernate.format_sql>true</hibernate.format_sql>
        <hibernate.hbm2ddl.auto>create</hibernate.hbm2ddl.auto>
    </properties>
</profile>

Spring test-applicationContext.xml file :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>

    <!-- enables interpretation of the @PersistenceUnit/@PersistenceContext 
        annotations providing convenient access to EntityManagerFactory/EntityManager -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

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

    <context:component-scan base-package="foo.bar.dao">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Repository" />
    </context:component-scan>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitName" value="jpaLibrary" />
        <property name="jpaDialect">
            <bean class="${jpa.dialect}" />
        </property>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.${jpa.vendor.adapter}">
                <property name="showSql" value="${jdbc.show_sql}" />
                <property name="databasePlatform" value="${jdbc.dialect}" />
                <!-- On genere la BDD au demarrage -->
                <property name="generateDdl" value="${jpa.generateDdl}" />
            </bean>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!-- enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <context:spring-configured />
    <context:annotation-config />

</beans>

import.sql (authors for instance):

INSERT INTO `testDatabase`.`authors`(author_id, name) VALUES
(1, "JRR Tolkien"),
(2, "Albert Camus"),
(3, "Victor Hugo");
...

Finally, the class to test your DAO (then entities) :

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

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.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import foo.bar.dao.BookDao;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/test-applicationContext.xml" })
public class BookDaoTest extends AbstractTransactionalJUnit4SpringContextTests {

    @Autowired
    private BookDao bookDao;

    private int initialSize = 0;

    @Before
    public void init() {
        initialSize = bookDao.findAll().size();
    }

    @Test
    public void getAllBooks() {
        assertEquals(12, initialSize);
    }

    ...
}

Upvotes: 1

Related Questions