一个很好的DBunit test的架构,和Hibernate结合

最基本的创建数据库和打开关闭数据库使用父类
public abstract class HibernateBaseTest {

    protected ApplicationContext applicationContext;

    protected HibernateTransactionManager hibernateTransactionManager;

    protected IDatabaseTester databaseTester;

    @Before
    public void setUpHibernate() throws Exception {
        // BasicConfigurator.configure(); /* for debugging */
        applicationContext = new ClassPathXmlApplicationContext("hibernate-hsql-context.xml");
        hibernateTransactionManager = (HibernateTransactionManager) applicationContext
                .getBean("hibernateTransactionManager");
        databaseTester = (IDatabaseTester) applicationContext.getBean("dbUnitJdbcDatabaseTester");

    }

    protected QueryDataSet createQueryDataSet() throws SQLException, Exception {
        QueryDataSet qds = new QueryDataSet(databaseTester.getConnection());
        qds.addTable("account");
        return qds;
    }

    @After
    public void tearDown() throws Exception {
        if (databaseTester != null) {
            databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
            databaseTester.onTearDown();
        }
    }
}

配置文件为:
<?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:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetClass" value="nl.enovation.ems.message.repository.DataSourceUserType"/>
           <property name="targetMethod" value="setDefaultDataSourceRepository"/>
           <property name="arguments">
             <list>
                   <ref bean="dataSourceRepository"/>
             </list>
           </property>
    </bean>
   
    <bean id="dataSourceRepository" class="nl.enovation.ems.message.repository.FileSectionDataSourceRepository">
        <property name="baseDir" value="/var/lib/ems/messages"/>
    </bean>
   
    <bean id="jdbcDataSourceRepository" class="nl.enovation.ems.message.repository.JdbcDataSourceRepository">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
        <property name="lobHandler" ref="lobHandler"/>
    </bean>
   
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory">
            <ref local="hibernateSessionFactory" />
        </property>
    </bean>

    <bean id="hibernateSessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="mappingResources">
            <list>
                <value>META-INF/Message.hbm.xml</value>
                <value>META-INF/Account.hbm.xml</value>
                <value>META-INF/Rule.hbm.xml</value>
                <value>META-INF/Destination.hbm.xml</value>
                <value>META-INF/MessageSearchCriteria.hbm.xml</value>               
                <value>META-INF/ReportRule.hbm.xml</value>
                <value>META-INF/NotificationRule.hbm.xml</value>
                <value>META-INF/InboxEntry.hbm.xml</value>           
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
                <prop key="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</prop>
                <prop key="hibernate.connection.url">jdbc:hsqldb:mem:ems</prop>
                <prop key="hibernate.connection.username">sa</prop>
                <prop key="hibernate.connection.password"></prop>
                <prop key="hibernate.connection.pool_size">1</prop>
                <prop key="hibernate.connection.autocommit">true</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
                <prop key="org.hibernate.SQL">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTransactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref bean="hibernateSessionFactory" />
        </property>
    </bean>
   
    <bean name="dbUnitJdbcDatabaseTester" class="nl.enovation.ems.domain.BooleanSupportingJdbcDatabaseTester">
        <constructor-arg value="org.hibernate.dialect.HSQLDialect"/>
        <constructor-arg value="jdbc:hsqldb:mem:ems"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>   
   
    <bean id="accountRepository" class="nl.enovation.ems.domain.HibernateAccountRepository">
        <property name="hibernateTemplate">
            <ref bean="hibernateTemplate"/>
        </property>
    </bean>
   
    <bean id="messageRepository" class="nl.enovation.ems.domain.HibernateMessageRepository">
        <property name="hibernateTemplate">
            <ref bean="hibernateTemplate"/>
        </property>
        <property name="hibernateQueryManager">
            <ref local="hibernateQueryManager" />
        </property>       
    </bean>
   
    <bean id="hibernateQueryManager" class="nl.enovation.commons.query.hibernate.HibernateQueryManager">
        <property name="idGenerator">
            <bean class="nl.enovation.commons.SimpleIdGenerator"/>           
        </property>
        <property name="sessionFactory">
            <ref local="hibernateSessionFactory"/>
        </property>
        <property name="maxIdleTime" value="30000"/>
        <property name="maxResults" value="1501"/>
    </bean>
   
    <bean id="jdbcMessageRepository"
        class="nl.enovation.ems.domain.JdbcMessageRepository">
        <property name="jdbcTemplate">
            <ref local="jdbcTemplate" />
        </property>
        <property name="contentPersister">
            <bean class="nl.enovation.ems.message.repository.test.DataSourcePersisterMock"/>
        </property>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>
   
    <bean id="jdbcTransactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem:ems"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>

    <bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler">
        <property name="nativeJdbcExtractor">
            <bean class="org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor" />
        </property>
    </bean>

    <bean class="nl.enovation.ems.message.repository.DataSourceUserType" scope="prototype">
        <property name="dataSourceRepository">
            <bean class="nl.enovation.ems.message.repository.JdbcDataSourceRepository">
                <property name="jdbcTemplate" ref="jdbcTemplate" />
                <property name="lobHandler" ref="lobHandler" />
            </bean>
        </property>
    </bean>   
</beans>


一个测试类为:
package nl.enovation.ems.domain;

import java.sql.SQLException;
import java.util.Set;

import javax.activation.DataSource;

import nl.enovation.commons.datasource.FileSectionDataSource;

import org.dbunit.Assertion;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.filter.DefaultColumnFilter;
import org.dbunit.dataset.xml.XmlDataSet;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.core.io.Resource;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.*;

public class HibernateInboxPersistenceTest extends HibernateBaseTest {

    private AccountRepository accountRepository;

    private MessageRepository messageRepository;

    private IDataSet addExpectedDataSet;

    private CompositeDataSet deleteExpectedDataSet;

    @Before
    public void setUp() throws Exception {
        messageRepository = (MessageRepository) applicationContext.getBean("messageRepository");
        accountRepository = (AccountRepository) applicationContext.getBean("accountRepository");
        Resource inboxDataSetResource = applicationContext.getResource("store-inbox-dataset.xml");
        Resource messageDataSetResource = applicationContext.getResource("store-message-dataset.xml");
        Resource accountDataSetResource = applicationContext.getResource("shared-account-dataset.xml");

        CompositeDataSet ds = new CompositeDataSet(new IDataSet[] {
                new XmlDataSet(accountDataSetResource.getInputStream()),
                //new XmlDataSet(messageDataSetResource.getInputStream()),
                new XmlDataSet(inboxDataSetResource.getInputStream()) });
        databaseTester.setDataSet(ds);
       
        Resource inboxAddDataSetResource = applicationContext.getResource("store-inbox-add-assert-dataset.xml");
        addExpectedDataSet = new CompositeDataSet(new IDataSet[] {
                new XmlDataSet(accountDataSetResource.getInputStream()),
                //new XmlDataSet(messageDataSetResource.getInputStream()),
                new XmlDataSet(inboxAddDataSetResource.getInputStream()) });

        Resource inboxDeleteDataSetResource = applicationContext.getResource("store-inbox-delete-assert-dataset.xml");
        messageDataSetResource = applicationContext.getResource("store-message-inbox-delete-dataset.xml");
        deleteExpectedDataSet = new CompositeDataSet(new IDataSet[] {
                new XmlDataSet(accountDataSetResource.getInputStream()),
                //new XmlDataSet(messageDataSetResource.getInputStream()),
                new XmlDataSet(inboxDeleteDataSetResource.getInputStream()) });

        databaseTester.onSetup();
    }

    @Test
    public void testAddInboxEntry() throws SQLException, Exception {
        DefaultTransactionDefinition txdef = new DefaultTransactionDefinition();
        txdef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        TransactionStatus tx = hibernateTransactionManager.getTransaction(txdef);

        Account account = accountRepository.findById("1");
        assertNotNull(account);
        Message message = messageRepository.findById("2@lms");
        assertNotNull(message);

        account.addToInbox(message);
        hibernateTransactionManager.commit(tx);

        QueryDataSet qds = new QueryDataSet(databaseTester.getConnection());
        qds.addTable("inbox");
        qds.addTable("account");
        qds.addTable("message");
        qds.addTable("destination");
        qds.addTable("contentstatistic");
        Assertion.assertEquals(addExpectedDataSet, qds);
    }

    @Test
    public void testRetrieveInboxEntry() throws SQLException, Exception {
        DefaultTransactionDefinition txdef = new DefaultTransactionDefinition();
        txdef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        {
            TransactionStatus tx = hibernateTransactionManager.getTransaction(txdef);

            Account account = accountRepository.findById("1");
            assertNotNull(account);
            Message message = messageRepository.findById("2@lms");
            assertNotNull(message);

            account.addToInbox(message);
            hibernateTransactionManager.commit(tx);
        }
        {
            TransactionStatus tx = hibernateTransactionManager.getTransaction(txdef);

            Account account = accountRepository.findById("1");
            assertNotNull(account);

            Set<InboxEntry> inbox = account.getInbox();
            InboxEntry entry = inbox.iterator().next();
            assertEquals("2@lms", entry.getMessage().getId());
            DataSource dataSource = entry.getContent();
            assertThat(dataSource, instanceOf(FileSectionDataSource.class));
            assertThat(dataSource.getName(), is("20070904.0:656071:1723"));
            hibernateTransactionManager.commit(tx);
        }
    }

    @Test
    @Ignore(value = "Should not throw an exception, but HSQLDB does")
    public void testAddDuplicateInboxEntry() throws SQLException, Exception {
        DefaultTransactionDefinition txdef = new DefaultTransactionDefinition();
        txdef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        TransactionStatus tx = hibernateTransactionManager.getTransaction(txdef);

        Account account = accountRepository.findById("1");
        assertNotNull(account);
        Message message = messageRepository.findById("2@lms");
        assertNotNull(message);

        account.addToInbox(message);
        account.addToInbox(message);
        hibernateTransactionManager.commit(tx);

        QueryDataSet qds = new QueryDataSet(databaseTester.getConnection());
        qds.addTable("inbox");
        qds.addTable("account");
        qds.addTable("message");
        qds.addTable("destination");
        qds.addTable("contentstatistic");
        Assertion.assertEquals(addExpectedDataSet, qds);
    }

    @Test
    public void testDeleteInboxEntry() throws SQLException, Exception {
        DefaultTransactionDefinition txdef = new DefaultTransactionDefinition();
        txdef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        TransactionStatus tx = hibernateTransactionManager.getTransaction(txdef);

        Account account = accountRepository.findById("2");
        assertNotNull(account);

        Message message = messageRepository.findById("2@lms");
        assertNotNull(message);

        InboxEntry entry = account.getInbox().iterator().next();
        entry.delete();

        // account.removeFromInbox(new InboxEntry(account, message));

        hibernateTransactionManager.commit(tx);

        QueryDataSet qds = new QueryDataSet(databaseTester.getConnection());
        qds.addTable("inbox");
        qds.addTable("account");
        qds.addTable("message");
        qds.addTable("destination");
        qds.addTable("contentstatistic");

        ITable filteredTable = DefaultColumnFilter.excludedColumnsTable(qds.getTable("destination"),
                new String[] { "statetimestamp" });

        Assertion.assertEquals(deleteExpectedDataSet.getTable("destination"), filteredTable);
        // Assertion.assertEquals(deleteExpectedDataSet,qds);
    }
}


posted on 2008-07-18 10:49 刘铮 阅读(1085) 评论(1)  编辑  收藏 所属分类: DBUnit

评论

# re: 一个很好的DBunit test的架构,和Hibernate结合 2010-10-16 22:38 discoverer

不完整  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

导航

统计

留言簿(1)

文章分类(141)

文章档案(147)

搜索

最新评论