使用dbunit,可以幫助我們在測試中維護數據,也可以輔助我們的測試。
首先當然是下載dbunit, http://dbunit.sourceforge.net
我測試用的是 MYSQL 5.0 。
建立數據庫:
create table test1(
id int not null auto_increment,
user_name varchar(50),
primary key(id)) engine=innodb;
保存數據的xml文件:
xml 代碼
- <dataset>
- <test1 user_name="tom"/>
- <test1 user_name="John"/>
- <test1 user_name="Rose"/>
- </dataset>
首先建立一個 JunitTest 的類:
java 代碼
- public class Test2 extends TestCase {
-
- protected void setUp() throws Exception {
-
- }
-
- protected void tearDown() throws Exception {
-
- }
-
- }
我不喜歡繼承dbunit的類,所以我們在JunitTest 的類里增加這個變量:
java 代碼
- public class Test2 extends TestCase {
-
- private IDatabaseTester databaseTester;
-
- protected void setUp() throws Exception {
-
- }
-
- protected void tearDown() throws Exception {
-
- }
-
- }
然后,我們可以該寫 setUp() 方法了,無非就是連接數據庫,把數據倒入到表里。
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();
- }
好了,準備工作完成了,下面開始寫測試方法。
java 代碼
- public void test1() throws Exception{
-
- ITable test1Table = databaseTester.getDataSet().getTable("test1");
- assertEquals(test1Table.getRowCount(), 3);
-
- }
這個方法就是測試 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);
-
- }
這個方法測試是否有 user_name='tom' 這個記錄.
那么自動增加字段怎么辦呢?
只要在 tearDown 里增加
java 代碼
- databaseTester.setTearDownOperation(DatabaseOperation.TRUNCATE_TABLE);
就可以了! |