使用dbunit,可以幫助我們?cè)跍y(cè)試中維護(hù)數(shù)據(jù),也可以輔助我們的測(cè)試。
首先當(dāng)然是下載dbunit, http://dbunit.sourceforge.net
我測(cè)試用的是 MYSQL 5.0 。
建立數(shù)據(jù)庫(kù):
create table test1(
id int not null auto_increment,
user_name varchar(50),
primary key(id)) engine=innodb;
保存數(shù)據(jù)的xml文件:
xml 代碼
- <dataset>
- <test1 user_name="tom"/>
- <test1 user_name="John"/>
- <test1 user_name="Rose"/>
- </dataset>
首先建立一個(gè) JunitTest 的類(lèi):
java 代碼
- public class Test2 extends TestCase {
-
- protected void setUp() throws Exception {
-
- }
-
- protected void tearDown() throws Exception {
-
- }
-
- }
我不喜歡繼承dbunit的類(lèi),所以我們?cè)贘unitTest 的類(lèi)里增加這個(gè)變量:
java 代碼
- public class Test2 extends TestCase {
-
- private IDatabaseTester databaseTester;
-
- protected void setUp() throws Exception {
-
- }
-
- protected void tearDown() throws Exception {
-
- }
-
- }
然后,我們可以該寫(xiě) setUp() 方法了,無(wú)非就是連接數(shù)據(jù)庫(kù),把數(shù)據(jù)倒入到表里。
java 代碼
- protected void setUp() throws Exception {
-
- databaseTester = new JdbcDatabaseTester("com.mysql.jdbc.Driver",
- "jdbc:mysql://127.0.0.1:3306/test", "root", "123");
-
- IDataSet dataSet = getDataSet();
-
- databaseTester.setDataSet( dataSet );
- databaseTester.onSetup();
-
- }
-
- protected IDataSet getDataSet() throws Exception
- {
-
- return new FlatXmlDataSet(new FileInputStream(new File("dataset.xml")));
- }
然后是 tearDown 方法
java 代碼
- protected void tearDown() throws Exception
- {
-
- databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
- databaseTester.onTearDown();
- }
好了,準(zhǔn)備工作完成了,下面開(kāi)始寫(xiě)測(cè)試方法。
java 代碼
- public void test1() throws Exception{
-
- ITable test1Table = databaseTester.getDataSet().getTable("test1");
- assertEquals(test1Table.getRowCount(), 3);
-
- }
這個(gè)方法就是測(cè)試 test1 表有多少條記錄
java 代碼
- public void test2() throws Exception{
-
- ITable test1Table = databaseTester.getConnection().createQueryTable("any_name",
- "select user_name from test1 where user_name='tom'");
-
- assertTrue(test1Table.getRowCount()==1);
-
- }
這個(gè)方法測(cè)試是否有 user_name='tom' 這個(gè)記錄.
那么自動(dòng)增加字段怎么辦呢?
只要在 tearDown 里增加
java 代碼
- databaseTester.setTearDownOperation(DatabaseOperation.TRUNCATE_TABLE);
就可以了! |