JUnit寫TestCase

junitjava中書寫unit testframework,目前一些流行的unit test工具大都都是在junit上擴展而來的。

Eclipse中配置junit

在要使用JUNITproject名上,點擊properties--java build path-libraries, 點擊Add External JARs,JUNIT包點上就行了. 並在需要測試的項目上新建junit test case

 

 

用法

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

- 創建,從junit.framework.TestCase派生unit test需要的test case

- 書寫測試方法,提供類似於如下函數簽名的測試方法:

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. setUptearDown,這兩個函數是junit framework中提供初始化和反初始化每個測試方法的。setUp在每個測試方法調用前被調用,負責初始化測試方法所需要的測試環境;tearDown在每個測試方法被調用之後被調用,負責撤銷測試環境。它們與測試方法的關係可以描述如下:

 

測試開始 -> setUp -> testXXXX -> tearDown ->測試結束

 

4. 使用例子:

import junit.frmework.TestCase;

public class TestSample extends TestCaset{

protected void setUp(){

//初始化……

}

 

public void testMethod1(){

assertTrue( true);

}

 

potected void tearDown(){

//撤銷初始化……

}

}

5. 區分failexception

- fail,期望出現的錯誤。產生原因:assert函數出錯(如assertFalse(true));fail函數產生(如fail(……))。

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

對於assertfail等函數請參見junitjavadoc

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”); //應該到達點

}

……

}

 

potected void tearDown(){

//撤銷初始化……

}

}

7. 組裝TestSuite,運行更多的test。在junit中,TestTestCaseTestSuite三者組成了composiste pattern。通過組裝自己的TestSuite,可以完成對添加到這個TestSuite中的所有的TestCase的調用。而且這些定義的TestSuite還可以組裝成更大的TestSuite,這樣同時也方便了對於不斷增加的TestCase的管理和維護。

它的另一個好處就是,可以從這個TestCase樹的任意一個節點(TestSuiteTestCase)開始調用,來完成這個節點以下的所有TestCase的調用。提高了unit test的靈活性。

8. 使用例子:

import junit.framework.Test;

import junit.framework.TestSuite;

public class TestAll{

public class TestAll{

//定義一個suite,對於junit的作用可以視爲類似於java應用程序的main

public static Test suite(){

TestSuite suite = new TestSuite("Running all tests.");

suite.addTestSuite( TestCase1.class);

suite.addTestSuite( TestCase2.class);

return suite;

}

}

運行同運行單獨的一個TestCase是一樣的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章