Dbunit getting started (from: http://www.blogjava.net/liuzheng/articles/190128.html)

Source: Internet
Author: User

I believe that people who have done unit testing will be very familiar with JUnit, today to introduce dbunit (http://dbunit.sourceforge.net/) is a dedicated database testing for JUnit an extension, it can place the test object database between a test cycle. In view of the rare cases of introducing dbunit in China, this article will show you the wonderful world of dbunit in terms of theory and examples.

Dbunit Design Philosophy
Developers familiar with unit testing know that when conducting unit tests on databases, there are usually two solutions used: mock objects and stubs. Database operations can be simulated and tested by isolating associated database operation classes, such as JDBC operation classes. However, for some special systems, such as those that use the ejb cmp (container-managed persistence), the database access objects are at the bottom layer and hidden, these two solutions are insufficient for these systems.

Dbunit is designed to back up the database before testing, implant the required data to the object database, and finally read the data into the backup database after testing, goes back to the status before the test;
Besides, dbunit is an extension of JUnit. developers can create test case codes to compare the database operation results within the lifecycle of these test cases.

Dbunit test basic concepts and procedures
The main interface for dbunit-based testing is idataset. Idataset indicates the data of one or more tables.
All content in the database mode can be expressed as a single idataset instance. These tables are represented by itable instances.
There are many implementations of idataset, each of which corresponds to a different data source or loading mechanism. The most common idataset implementations are:
Flatxmldataset: XML Representation of a simple flat file of data
Querydataset: data obtained by SQL query
Databasedataset: a representation of the database table content.
Xlsdataset: Excel representation of data

Generally, the unit test process using dbunit is as follows:
1. Prepare data for testing and expected results based on business requirements. Generally, prepare XML files.

2. Back up the associated tables in the database in the setup () method.

3. Read the prepared data in the setup () method.

4. Install the corresponding test methods of the test class: Execute the object method and compare the actual execution results of the database with the expected results.

5. In the teardown () method, restore the database to the pre-test state.

Dbunit Development Instance

The following example illustrates the practical use of dbunit.


Prepare an instance

For example, a student table [Student] has the following structure:

Id char (4) PK student ID

Name char (50) Name

Sex char (1) Gender

Birthday Date of birth

Prepare the following data:

ID name sex birthday

0001 Weng Zi m

0002 Wang Cuihua F

The test object class is studentope. Java, which has two methods:

Findstudent (string ID): searches for records based on the primary key ID

Addstudent: Add a record


When testing the addstudent method, we are going to add the following data.

ID name sex birthday

0088 Wang ear m

After this method is executed, the data in the student table of the database is as follows:

ID name sex birthday

0001 Weng Zi m

0002 Wang Cuihua F

0088 Wang ear m

Then we will explain how to perform unit tests on the two methods.


Expand instance

1. Convert the prepared data and expected data into an XML file.

Student_pre.xml

<? XML version = '1. 0' encoding = "gb2312"?> <Dataset> <student ID = "0001" name = "Weng zi" Sex = "M" Birthday = "1979-12-31"/> <student ID = "0002" name = "Wang Cuihua "Sex =" F "Birthday =" 1982-08-09 "/> </dataset>





Student_exp.xml

<? XML version = '1. 0' encoding = "gb2312"?> <Dataset> <student ID = "0001" name = "Weng zi" Sex = "M" Birthday = "1979-12-31"/> <student ID = "0002" name = "Wang Cuihua "Sex =" F "Birthday =" 1982-08-09 "/> <student ID =" 0088 "name =" "Sex =" M "Birthday =" 1982-01-01 "/> </ dataset>



2. For more information about the setup method, see code comments.

Protected void setup () {idatabaseconnection connection = NULL; try {super. setup (); // This example uses the PostgreSQL database class. forname ("org. postgreSQL. driver "); // connect to DB connection conn = drivermanager. getconnection ("JDBC: PostgreSQL: testdb. test "," Postgres "," Postgres "); // obtain the database connection = new databaseconnection (conn ); // back up querydataset backupdataset = new querydataset (connection); backupdataset on the database operation object table student. addtable ("stud Ent "); file = file. createtempfile ("student_back ",". XML "); // backup file flatxmldataset. write (backupdataset, new fileoutputstream (File); // read idataset dataset = new flatxmldataset (New fileinputstream ("student_pre.xml" ));databaseoperation.clean_insert.exe cute (connection, dataset );} catch (exception e) {e. printstacktrace ();} finally {try {If (connection! = NULL) connection. Close () ;}catch (sqlexception e ){}}}



3. For more information about the installation test method, see the code comments.


* You can use the assertequals () method to compare the table fields.

// Findstudent public void testfindstudent () throws exception {// execute the findstudent method studentope = new studentope (); student result = studentope. findstudent ("0001"); // comparison between the expected result and the actual result assertequals ("Weng zi", result. getname (); assertequals ("M", result. getsex (); assertequals ("1979-12-31", result. getbirthday ());}





* Update, add, delete, and other methods. You can use assertion. assertequals () to compare the entire table.

Public void testaddstudent () throws exception {// execute the addstudent method studentope = new studentope (); // student newstudent = new student ("0088 ", "", "M", "1982-01-01"); // execute the append Method Student result = studentope. addstudent (newstudent); // compare the expected results with the actual results. idatabaseconnection connection = NULL; try {// obtain the expected results idataset expecteddataset = new flatxmldataset (New fileinputstream ("student_exp.xml"); itable expectedtable = Expecteddataset. gettable ("student"); // obtain the connection conn = getconnection (); connection = new databaseconnection (conn); idataset databasedataset = connection. createdataset (); itable actualtable = databasedataset. gettable ("student"); // compare assertion. assertequals (expectedtable, actualtable);} finally {If (connection! = NULL) connection. Close ();}}





* If some fields do not need to be compared during table comparison, you can use the defaultcolumnfilter. excludedcolumnstable () method,

Exclude the specified field from the comparison scope. For example, if you do not need to compare the birthday field in the above example, you can process it as follows:

ITable filteredExpectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[]{"birthday"});ITable filteredActualTable = DefaultColumnFilter.excludedColumnsTable(actualTable,new String[]{"birthday"});Assertion.assertEquals(filteredExpectedTable, filteredActualTable);





4. In the teardown () method, restore the database to the status before testing.

protected void tearDown() throws Exception{IDatabaseConnection connection =null;try{super.tearDown();Connection conn=getConnection();connection =new DatabaseConnection(conn);IDataSet dataSet = new FlatXmlDataSet(file);DatabaseOperation.CLEAN_INSERT.execute(connection,dataSet);}catch(Exception e){e.printStackTrace();}finally{try{if(connection!=null) connection.close();}catch(SQLException e){}}}





Last

Undoubtedly, using dbunit can greatly improve the efficiency of database testing. We hope that this article will help you master this powerful tool for database testing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.