使用DBUnit进行Dao测试:方法抛出`' org.dbunit.dataset.NoSuchTableException

时间:2016-01-29 07:52:48

标签: spring hibernate dbunit

我正在尝试使用DBUnit来测试DAO功能。我想,我试图从xml文件加载数据集。但是,有些问题让我感到困惑。让我先发布我的代码以获得一些观点。

public class MyDaoTest extends DatabaseTestCase
{
    private XmlDataSet loadedDataSet;

    MyDao dao;

    protected void setUp() throws Exception
    {
        dao = new CourierUploadQueueMilestonedDaoImpl();
        super.setUp();
    }

    @Override
    protected IDatabaseConnection getConnection() throws Exception
    {
        Class driverClass = Class.forName("com.mysql.jdbc.Driver");
        Connection jdbcConnection = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
        return new DatabaseConnection(jdbcConnection);
    }

    @Override
    protected IDataSet getDataSet() throws Exception
    {
        FileInputStream in = new FileInputStream("dataset.xml");
        loadedDataSet = new XmlDataSet(in);
        return loadedDataSet;
    }

    protected DatabaseOperation getSetUpOperation() throws Exception
    {
        return DatabaseOperation.CLEAN_INSERT;
    }

    protected DatabaseOperation getTearDownOperation() throws Exception
    {
        return DatabaseOperation.NONE;
    }

    public void testCheckLoginDataLoaded() throws Exception
    {
        assertNotNull(loadedDataSet);
        int rowCount = loadedDataSet.getTable("person").getRowCount();
        assertEquals(2, rowCount);
    }
}

datset文件是 dataset.xml

<?xml version='1.0' encoding='UTF-8'?>
<dataset>
    <person id="25" name="Saurabh" phone="61458972564"/>
    <person id="21" name="Saurabh" phone="61458972564"/>
</dataset>

问题:

  1. 我得到异常&#34;方法抛出'org.dbunit.dataset.NoSuchTableException' exception." 当我调试时,我看不到"loadedDataSet"变量中填充的任何数据。 是否未配置DatabaseOperation.CLEAN_INSERT operation in getSetUpOperation()初始化数据集所需的内容?

  2. 因为我使用xml文件来填充数据集,为什么我需要在getConnection()中提供我的MySQL连接细节? 它的意义是什么?我可以在这里使用其他东西吗?我不希望它访问我的mysql数据库。 我想要的行为是从xml文件中读取,在任何插入和更新的情况下写入xml文件,然后在方法完成后将数据集恢复为其原始内容。

  3. 我不想使用新的运算符来创建DAO类的na实例。我想使用spring托管实例。 我试着做了

    String [] configLocations = {&#34; classpath:applicationContext.xml&#34; };
    ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocations);         personDao =(PersonDao)ctx.getBean(&#34; personDao&#34;);

  4. 然而。它给了我

    Method threw   'org.springframework.beans.factory.BeanDefinitionStoreException' exception.
    Unexpected exception parsing XML document from class path resource [applicationContext.xml]
    detailMessage : org/springframework/core/type/AnnotatedTypeMetadata
    

1 个答案:

答案 0 :(得分:1)

我发现在Spring中使用DBUnit的最简单方法是按如下方式设置测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-test.xml")
@DatabaseSetup("/dataset.xml")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        DbUnitTestExecutionListener.class })
public class SomeTest {


@Test
public void test1() {
 .....
}

}

你需要在你的pom中跟踪com.github.springtestdbunit.annotation.DatabaseSetup类的依赖

<dependency>
    <groupId>com.github.springtestdbunit</groupId>
    <artifactId>spring-test-dbunit</artifactId>
    <version>1.2.1</version>
    <scope>test</scope>
</dependency>

applicationContext-test.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:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
    http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

    <context:component-scan base-package="net.isban" />
    <tx:annotation-driven />
    <jpa:repositories base-package="net.isban.fmis.repository" />

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:fmis-test.properties" />
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="net.isban.fmis.entity" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
            </props>
        </property>
    </bean>

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

    <cache:annotation-driven />
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcache" />
    </bean>
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache-test.xml" />
    </bean>

</beans>

希望这有帮助。