05. Use of DBUnit

 

I believe that those who have done unit testing will be very familiar with JUnit. The DbUnit ( http://dbunit.sourceforge.net/  ) to be introduced today is an extension to JUnit specifically for database testing. The database is put into a state between test rounds. In view of the fact that the domestic introduction of DbUnit system tutorial is relatively rare, this article will take you to experience the wonderful world of DbUnit from two aspects: theory and example.

In the above section we used the hashmap to simulate the operation of the real database, in this chapter we can use the dbunit tool to test the operation of the database

The first step is to download the corresponding jar package

The above two jar packages are required

The second step is to create an xml file in the src directory. The name of the xml file should be the same as the table name in the test database t_user.xml

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
 <t_user id ="1" username="admin" password="123" nickname="超级管理员"/>

</dataset>

It can also be created in the following way

The difference between the two is that the DataSet used is different. The xml method uses XmlDataSet, and the first method above uses FlatXmlDataSet

 

Step 3: Create the conncetion of dbunit

Depends on the connection created in DButils in the above section

DatabaseOperation.UPDATE: This operation updates the content of the data set read from the test data source to the database. Note that the premise of correct execution of this operation is that the test data table already exists. If the test case does not exist, the test case will fail

DatabaseOperation.INSERT: This operation inserts the content of the data set read from the test data source into the database. Note that the premise of correct execution of this operation is that the test data table does not exist, and this operation will create a new data table. This test case will fail if the test data table already exists. In addition, pay special attention to the order of the data tables in the dataset when performing this operation, otherwise the test case may fail due to violation of foreign key constraints

DatabaseOperation.DELETE: This operation deletes data from the database. Note that this operation only deletes data rows that exist in the data set, not the data in the entire data table

DatabaseOperation.DELETE_ALL: This operation deletes all rows in the data table. Note that this operation only affects the data tables declared in the data set. The data in the data tables not involved in the data set will not be deleted.

DatabaseOperation.TRUNCATE: This operation will delete the data table declared in the data set. If some tables in the data are not mentioned in the predefined data set, this data table will not be affected. Note that this operation is performed in reverse order

DatabaseOperation.REFRESH: As the name suggests, this operation will synchronize the data in the predefined data set to the database, that is to say, this operation will update the existing data in the data number and insert the data that is not in the database. Rows that are already in the database but not in the dataset will not be affected. We can use this operation to synchronize predefined data to the production database when testing with a copy of the production database

DatabaseOperation.CLEAN_INSERT: Delete all the data in the data table, and then insert the data defined in the data set, if you want to ensure that the database is controlled, you will prefer this.

DatabaseOperation.NONE: Do nothing

CompositeOperation: Combines multiple operations into one for easy maintenance and reuse

TransactionOperation: perform multiple operations within a transaction

IdentityInsertOperation: When using MSSQL, we have no way to control the IDENTITY column when inserting data. We can control it with this. It can only be used when using MSSQL.

We write our test class

package com.fjnu.service;

import java.sql.SQLException;
import static org.junit.Assert.*;

import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.dataset.xml.FlatXmlProducer;
import org.dbunit.operation.DatabaseOperation;
import org.junit.Test;
import org.xml.sax.InputSource;

import com.fjnu.model.User;
import com.weiyuan.dao.IUserDao;
import com.weiyuan.dao.UserDao;
import com.weiyuan.test.DBUtils;

public class TestDBUtils {
    @Test
    public void testLoad(){
        try {
            IDatabaseConnection con = new DatabaseConnection(DBUtils.getConnection());
            IDataSet dataSet = new FlatXmlDataSet( new FlatXmlProducer(
                     new InputSource(TestDBUtils.class .getClassLoader ().getResourceAsStream("t_user.xml" ))));
             // Empty the data in the database and insert the data in xml 
            DatabaseOperation.CLEAN_INSERT.execute (con, dataSet);
            
            IUserDao userDao = new UserDao();
            User u = userDao.load("admin");
            assertEquals(u.getUsername(), "admin55");
            assertEquals(u.getPassword(), "123");
            
            
        } catch (DatabaseUnitException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

that's it

There is a problem with the above method, it first clears all data in the database, and then inserts the file in xml into the database

In actual operation: we should back up all the data in the database first, then operate the data in the xml, and then restore the backed up data after the operation is completed

package com.fjnu.service;

import java.io.FileWriter;
import java.sql.SQLException;

import static org.junit.Assert.*;

import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.dataset.xml.FlatXmlProducer;
import org.dbunit.operation.DatabaseOperation;
import org.junit.Test;
import org.xml.sax.InputSource;

import com.fjnu.model.User;
import com.weiyuan.dao.IUserDao;
import com.weiyuan.dao.UserDao;
import com.weiyuan.test.DBUtils;

public class TestDBUtils {
    @Test
    public void testLoad(){
        try {
            IDatabaseConnection con = new DatabaseConnection(DBUtils.getConnection());
            IDataSet dataSet = new FlatXmlDataSet( new FlatXmlProducer(
                     new InputSource(TestDBUtils.class .getClassLoader ().getResourceAsStream("t_user.xml" ))));
             // Empty the data in the database and insert the data in xml 
            DatabaseOperation.CLEAN_INSERT.execute (con, dataSet);
            
            IUserDao userDao = new UserDao();
            User u = userDao.load("admin");
            assertEquals(u.getUsername(), "admin");
            assertEquals(u.getPassword(), "123");
            
            
        } catch (DatabaseUnitException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    @Test
    public void testBackup(){
        try {
            IDatabaseConnection con = new DatabaseConnection(DBUtils.getConnection());
            IDataSet createDataSet = con.createDataSet();
            FlatXmlDataSet.write(createDataSet, new FileWriter("d:/test.xml"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324648643&siteId=291194637