简体   繁体   中英

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

I am trying to use DBUnit for testing DAO functionality. Fo that, I am trying to load dataset from a xml file. 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

<?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." When I debug, I don not see any data being populated in the "loadedDataSet" variable. Isn't configuring DatabaseOperation.CLEAN_INSERT operation in getSetUpOperation() what is required to initilaize the data set ?

  2. Since, I am using xml file for populating the data set, why do I need to give my MySQL connection details in getConnection() ? What is its significance ? Can I use something else here ? I don't want it accessing my mysql database. 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.

  3. I don't want to be using a new operator to create na instance of the DAO class. I want to use the spring managed instance. I tried doing

    String[] configLocations = { "classpath:applicationContext.xml" };
    ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocations); 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

@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

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

applicationContext-test.xml is

<?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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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