DbUnit Data-tier testing

Source: Internet
Author: User

Objective:

Preliminary study Dbunit, Master dbunit Basic usage, prepare for data layer test.


This is an extended unit test framework from JUnit that focuses on testing the data tier. Use is very simple (will make later), the document is very few, especially the Chinese document, there is no detailed explanation, the official several pages of simple introduction, if not to do it, it is difficult to understand.


Since this framework is based on JDBC data testing, the current environment is the SSH architecture, looking at the pages of documents, do not do, I really do not understand how it achieved.


Through this document, I hope that people like me who know how to do it, simply start using this framework for testing.


let's get started:

People who see this article probably know a basic JUnit unit test structure, so we start with a basic test structure:

This structure has only one Test class:


Package com.ceopen.wjx.test.dbunit;

...... Code slightly ...

public class Testsql extends testcase{

...... Code slightly ...

public void Testsql () throws SQLException, exception{

Class Driverclass = Class.forName ("Com.mysql.jdbc.Driver");

Connection jdbcconnection = drivermanager.getconnection (

"Jdbc:mysql://localhost:3306/zshop-demo", "root", "root");

Statement Statement = Jdbcconnection.createstatement ();

ResultSet rs = statement.executequery ("SELECT count (*) as NUM from ' DEMO '. ' Uc_account ';");

Rs.next ();

System.out.println (rs.getstring ("NUM"));

int num = rs.getint ("num");

Asserttrue (num>0);

}

...... Code slightly ...

}


Here you need a MySQL database and related driver Jar pack, or you can directly change to any database connection you need.


Now it's just a standard JUnit test class, and there's nothing strange about it. If you haven't used JUnit before, Google it and spend one hours tutoring it.


Inside this class, the database is connected, and the number of records in a table called Uc_account is queried. Let's assume that there are several records in this table, the basic JDBC query, nothing to say, or should we focus on dbunit.


dbunit Admission:

Here's the play, DBUnit, what the hell is it capable of? Its main task is to set up a test environment at the beginning of the test, first to use a look.


The Testsql parent class is first changed from TestCase to Dbtestcase. This is the implementation of a dbunit multiple inheritance testcase. Implement the GetDataSet () method, and then declare several environment variables in the constructor. The modified code is as follows:


public class Testsql extends Dbtestcase {


Constructors

Public Testsql () {

Super (); System.setproperty (Propertiesbasedjdbcdatabasetester.dbunit_driver_class, "com.mysql.jdbc.Driver"); System.setproperty (Propertiesbasedjdbcdatabasetester.dbunit_connection_url, "jdbc:mysql://localhost:3306/ Zshop-demo ");

System.setproperty (propertiesbasedjdbcdatabasetester.dbunit_username, "root");

System.setproperty (Propertiesbasedjdbcdatabasetester.dbunit_password, "root");

}


Test method

public void Testsql () throws SQLException, exception{

Class Driverclass = Class.forName ("Com.mysql.jdbc.Driver");

Connection jdbcconnection = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/demo", "root", "root");

Statement Statement = Jdbcconnection.createstatement ();

ResultSet rs = statement.executequery ("SELECT count (*) as NUM from ' Zshop-demo '. ' Uc_account ' LIMIT 0, 100;");

Rs.next ();

System.out.println (rs.getstring ("NUM"));

int num = rs.getint ("num");

Asserttrue (num>0);

}


@Override

Protected Idataset GetDataSet () throws Exception {

return null;

}

}



Here's the key, initialization data, we're going to initialize uc_account This table, if the data inside is important to you, you'd better back up the database first.

First, create a new XML file, called the Uc_account.xml Bar, which reads as follows:


<?xml version= ' 1.0 ' encoding= ' gb2312 '?>

<dataset>

<uc_account id= "0001" version= "1" user_login_name= "test001"/>

<uc_account id= "0002" version= "2" user_login_name= "test002"/>

</dataset>


Note here that as the root element dataset is required, its child element name is the table name, the property name is the field name, and the property value is the field value. The field values do not repeat with the values in the existing database, and you will know why.

Then, complete the method in the GetDataSet, as follows:

...... Code slightly ...

@Override

Protected Idataset GetDataSet () throws Exception {

Return to New Flatxmldatasetbuilder (). Build (New FileInputStream ("Uc_account.xml"));

}

...... Code slightly ...



Here to ensure that the Uc_account.xml file can be found, if not found the file, adjust the path bar.


Now, run this unit test. As a result, no matter what the previous data looks like, the results of the current run are only two data in the table. Then look at the database, really only two data (just want to have no backup, now want to restore the rest of the crying).


Dismantling Dbunit

Why, then? What's going on? The database changed. What about the other tests?


I also think so, so will dbunit source code to find to disassemble and reread (English is not good, only read code, bitter AH).


This is the way: Our test class inherits Dbtestcase first returns a Propertiesbasedjdbcdatabasetester instance in the Newdatabasetester method, This instance connects to the database through the environment variables we set in the constructor, and then, at the beginning of the JUnit test, invokes the Setup method, which is implemented by a Dbtestcase parent class and invokes the data provided by GetDataSet. emptying and copying data from the datasheet; Finally, this is the turn of our test method, when the deletion of the delete, the insertion of the insert, so we see the result.


Continue to disassemble, in fact, you can not provide database connection information by environment variables. Dbunit offers a number of Dbtestcase brothers:


Jdbcbaseddbtestcase

Datasourcebaseddbtestcase

Jndibaseddbtestcase


The essence is to return a subclass of a Idatabasetester interface by Newdatabasetester method, thus providing the implementation of getconnection and GetDataSet methods. What is already implemented in the class library is:


Jdbcdatabasetester

Propertiesbasedjdbcdatabasetester

Datasourcedatabasetester

Jndidatabasetester


Even you can do it yourself, interested people to study their own, I am in good enough thought, will no longer be investigated.


The data provides the method GetDataSet also may use other data to provide the way, in a word returns idataset the realization to be good. I'm not studying here.

The database has, the data has, why it is emptied data after the insertion of data.


Is Dbtestcase again, its parent class Databasetestcase returns Databaseoperation.clean_insert in the Getsetupoperation method, This is a databaseoperation implementation that determines that the Insert method inserts data when the Delete method is called to remove data when the Setup method for the unit test is invoked.


Similarly, Dbunit provides some other means for this section:


Databaseoperation.none

Databaseoperation.refresh

Databaseoperation.insert

Databaseoperation.delete

Databaseoperation.delete_all databaseoperation.truncate_table

Databaseoperation.clean_insert


When needed, we cover the getsetupoperation and return the desired class.


Or, to implement a databaseoperation subclass of your own, that is not the content of this article. I think, usually databaseoperation.clean_insert should be enough.


So, Dbunit clears the database before we start the test and then inserts its own data. How can this be done. Other data is also useful. You're not the only one to say that, I say.


There is also a problem, the data has been covered by Dbunit, the original data on how to recover after the test. Dbunit the solution is to back up the data before the test starts, and then restore the data after the data is finished. Related articles Online A lot, you can Google, or you are as lazy as me, look at this article, probably also understand:


Http://www.blogjava.net/iamlibo/archive/2009/03/14/259731.html


I don't like the plan, so I'm not studying it here. I only need to dbunit the database initialization ability, at the beginning of the test, initialization data. Outside, using Spring's test framework, the entire test is treated as a transaction, and after the test ends, the transaction ends and rolls back, and the data returns.


The realization of this idea will be explained in my next article, giving a preview of unit testing with spring and dbunit.


In addition, I have to admit that the blog to publish a more orderly format of the article really troublesome, if someone wants to see a more tidy format, you can go to my library:


Http://wenku.baidu.com/view/218a706bb84ae45c3b358ca7.html?st=1


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.