简体   繁体   English

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

[英]Dao Testing with DBUnit : Method threw `'org.dbunit.dataset.NoSuchTableException

I am trying to use DBUnit for testing DAO functionality. 我正在尝试使用DBUnit来测试DAO功能。 Fo that, I am trying to load dataset from a xml file. 为此,我正在尝试从xml文件加载数据集。 However, there are certain points that are confusing me. 但是,有些观点使我感到困惑。 Let me post my code first to get some perspective. 让我先发布我的代码以获得一些见解。

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

The datset file is dataset.xml 数据集文件是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>

Questions : 问题:

  1. I get the exception "Method threw 'org.dbunit.dataset.NoSuchTableException' exception." 我收到异常“方法抛出'org.dbunit.dataset.NoSuchTableException' exception." When I debug, I don not see any data being populated in the "loadedDataSet" variable. 调试时,在"loadedDataSet"变量"loadedDataSet"不到任何数据。 Isn't configuring DatabaseOperation.CLEAN_INSERT operation in getSetUpOperation() what is required to initilaize the data set ? DatabaseOperation.CLEAN_INSERT operation in getSetUpOperation()配置DatabaseOperation.CLEAN_INSERT operation in getSetUpOperation()不是初始化数据集所需要的吗?

  2. Since, I am using xml file for populating the data set, why do I need to give my MySQL connection details in getConnection() ? 由于我使用xml文件填充数据集,为什么我需要在getConnection()中提供MySQL连接详细信息? What is its significance ? 它的意义是什么? Can I use something else here ? 我可以在这里使用其他东西吗? I don't want it accessing my mysql database. 我不希望它访问我的mysql数据库。 The behaviour that I want is to read from xml file, write into xml file in case of any insert and update, and then as soon as the method completes revert the dataset to its origiunal content. 我想要的行为是从xml文件读取,在进行任何插入和更新的情况下写入xml文件,然后在该方法完成后立即将数据集还原为其原始内容。

  3. I don't want to be using a new operator to create na instance of the DAO class. 我不想使用新的运算符来创建DAO类的实例。 I want to use the spring managed instance. 我想使用spring托管实例。 I tried doing 我试着做

    String[] configLocations = { "classpath:applicationContext.xml" }; String [] configLocations = {“” classpath:applicationContext.xml“};
    ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocations); ApplicationContext ctx =新的ClassPathXmlApplicationContext(configLocations); personDao = (PersonDao) ctx.getBean("personDao"); personDao =(PersonDao)ctx.getBean(“ personDao”);

However. 然而。 it gave me 它给了我

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

I find the easiest way to use DBUnit with Spring is to set you tests up as follows 我发现将DBUnit与Spring一起使用的最简单方法是按照以下步骤进行测试

@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() {
 .....
}

}

You'll need to following dependency in your pom for the com.github.springtestdbunit.annotation.DatabaseSetup class 您需要遵循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 is 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>

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM