使用spring

时间:2015-09-28 16:59:02

标签: spring hibernate junit entity

我尝试测试hibernate实体如何持久化到数据库。我有3个实验的5个测试。我的所有尝试都不成功(((我尝试使用@Transactional注释将每个测试绑定到一个事务。但我不能(尝试所有组合)。现在我尝试手动测试它创建会话和事务。但现在问题是我不知道如何为所有测试创建一个会话。我尝试了 @BeforeClass ,但问题是它是静态的,我使用Spring bean进行会话创建。任何想法我如何测试hibernate实体?

1 个答案:

答案 0 :(得分:1)

您可以使用HSQLDB等专用数据库通过DAO测试类测试实体。

您需要:

  • Maven测试资料
  • Spring配置文件(测试上下文)
  • 脚本SQL插入一些数据
  • DAO班级考试。

Maven测试档案:

<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文件:

<?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(例如作者):

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

最后,测试你的DAO(然后是实体)的类:

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);
    }

    ...
}