您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > junit
junit使用手冊
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2013/1/9 15:51:21 ] 推薦標簽:

在使用XP進行開發(fā)的過程,unit test是必不可少的環(huán)節(jié)。作為unit test,junit是的工具。本文從使用目的、如何使用、以及使用中需要考慮的問題,簡略描述了junit的基本用法。

使用目的
      junit是java中書寫unit test的framework,目前一些流行的unit test工具大都都是在junit上擴展而來的。目前它的版本是junit3.8.1,可以從www.junit.org上下載。

用法
1.       基本使用步驟,Junit的使用非常簡單,它的基本使用步驟:

-          創(chuàng)建,從junit.framework.TestCase派生unit test需要的test case

-          書寫測試方法,提供類似于如下函數(shù)簽名的測試方法:

public void testXXXXX();

-          編譯,書寫完test case后,編譯所寫的test case類

-          運行,啟動junit test runner,來運行這個test case。

Junit提供了2個基本的test runner:字符界面和圖形界面。啟動命令分別如下:

a 圖形界面:

java junit.swingui.TestRunner XXXXX

b 字符界面:

java junit.textui.TestRunner XXXXX

2.       使用例子:

import junit.frmework.TestCase;

public class TestSample extends TestCaset{

       public void testMethod1(){

              assertTrue( true);

}

}

3.       setUp與tearDown,這兩個函數(shù)是junit framework中提供初始化和反初始化每個測試方法的。setUp在每個測試方法調(diào)用前被調(diào)用,負責初始化測試方法所需要的測試環(huán)境;tearDown在每個測試方法被調(diào)用之后被調(diào)用,負責撤銷測試環(huán)境。它們與測試方法的關(guān)系可以描述如下:

 

    測試開始 -> setUp -> testXXXX -> tearDown ->測試結(jié)束

 


4.       使用例子:

import junit.frmework.TestCase;

public class TestSample extends TestCaset{

       protected void setUp(){

              //初始化……

}

 

       public void testMethod1(){

              assertTrue( true);

}

 

potected void tearDown(){

      //撤銷初始化……

}

}

5.       區(qū)分fail、exception。

-          fail,期望出現(xiàn)的錯誤。產(chǎn)生原因:assert函數(shù)出錯(如assertFalse(true));fail函數(shù)產(chǎn)生(如fail(……))。

-          exception,不期望出現(xiàn)的錯誤,屬于unit test程序運行時拋出的異常。它和普通代碼運行過程中拋出的runtime異常屬于一種類型。

對于assert、fail等函數(shù)請參見junit的javadoc。

6.       使用例子:

import junit.frmework.TestCase;

public class TestSample extends TestCaset{

       protected void setUp(){

              //初始化……

}

 

       public void testMethod1(){

              ……

              try{

                     boolean b= ……

                     assertTrue( b);

                     throw new Exception( “This is a test.”);

                     fail( “Unable point.”);     //不可能到達

              }catch(Exception e){

                     fail( “Yes, I catch u”); //應(yīng)該到達點

}

……

}

 

potected void tearDown(){

      //撤銷初始化……

}

}

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