您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > DBunit
DBUnit 進(jìn)行單元測試
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2013/6/28 13:22:03 ] 推薦標(biāo)簽:

  測試類 EmployeeSessionFacadeTest,需要擴(kuò)展DBUnit的基礎(chǔ)類DatabaseTestCase并且必須提供對getConnection()和getDataSet()方法的實現(xiàn),在getConnection()方法中將獲得與EJB容器初始化時一樣的數(shù)據(jù)庫實例,getDataSet()方法負(fù)責(zé)讀取上面提及的employee_hr_seed.xml文件的數(shù)據(jù)。  
  測試方法相當(dāng)簡單,因為DBUnit已經(jīng)為我們處理了復(fù)雜的數(shù)據(jù)庫生命周期任務(wù)。為了測試getEmployeeBySocialSecNum()方法,只需要簡單的傳遞一個存在于種子文件中的社保代碼號即可,比如
  "333-29-9999".  
  //譯者注:EmployeeFacade 類型對象,譯者認(rèn)為是代表底層數(shù)據(jù)庫數(shù)據(jù)的映射體
  
      public void testFindBySSN() throws Exception{ 
       
      EmployeeFacade facade = //obtain somehow 
       
      EmployeeValueObject vo = 
      facade.getEmployeeBySocialSecNum("333-29-9999"); 
       
      TestCase.assertNotNull("vo shouldn't be null", vo); 
      TestCase.assertEquals("should be Drew", 
      "Drew", vo.getFirstName()); 
      TestCase.assertEquals("should be Smith", 
      "Smith", vo.getLastName()); 
      } 
  
  為了確保操作周期中的創(chuàng)建職員方法createEmployee()沒有問題,我們只需簡單的執(zhí)行一下這個方法,然后校驗一下看有沒有異常拋出,另外,下一步我們要做的是在這條新增的記錄上進(jìn)行查找操作,看是否可以找到剛創(chuàng)建的記錄。
完整實例:
使用dbunit,可以幫助我們在測試中維護(hù)數(shù)據(jù),也可以輔助我們的測試。
首先當(dāng)然是下載dbunit, http://dbunit.sourceforge.net
我測試用的是 MYSQL 5.0 。
建立數(shù)據(jù)庫:

    create table test1(  
    id int not null auto_increment,  
    user_name varchar(50),  
    primary key(id)) engine=innodb;  

 

保存數(shù)據(jù)的xml文件:

    <dataset>   
        <test1 user_name="tom"/>                 
        <test1 user_name="John"/>   
        <test1 user_name="Rose"/>      
    </dataset> 
    <dataset> 
        <test1 user_name="tom"/>              
        <test1 user_name="John"/> 
        <test1 user_name="Rose"/>   
    </dataset> 


首先建立一個 JunitTest 的類:

    public class Test2 extends TestCase {    
       
        protected void setUp() throws Exception { }    
       
        protected void tearDown() throws Exception { }    
          
    }   
     
    public class Test2 extends TestCase { 
     
        protected void setUp() throws Exception {} 
     
        protected void tearDown() throws Exception {} 
       
    } 

上一頁12345下一頁
軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd