JUnit 是 Java 社區中知名度高的單元測試工具。它誕生于 1997 年,由 Erich Gamma 和 Kent Beck 共同開發完成。其中 Erich Gamma 是經典著作《設計模式:可復用面向對象軟件的基礎》一書的作者之一,并在 Eclipse 中有很大的貢獻;Kent Beck 則是一位極限編程(XP)方面的專家和先驅。
麻雀雖小,五臟俱全。JUnit 設計的非常小巧,但是功能卻非常強大。Martin Fowler 如此評價 JUnit:在軟件開發領域,從來沒有如此少的代碼起到了如此重要的作用。它大大簡化了開發人員執行單元測試的難度,特別是 JUnit 4 使用 Java 5 中的注解(annotation)使測試變得更加簡單。
從推出到現在,JUnit3.8.1和JUnit4的工作原理和使用區別還是比較大的,下面首先用一段代碼來演示JUnit3.8.1的快速使用,以便熟悉JUnit的原理
1.首先,我們在Eclipse的項目中創建一個待測試的類Hello.java,代碼如下:
public class Hello {
public int abs(int num)
{
return num>0?num:-num;
}
public double division(int a,int b)
{
return a/b;
}
}
2.右擊該類,選擇 新建->JUnit測試用例,選擇JUnit3.8.1,setUp和tearDown方法,點擊下一步,選擇需要測試的方法,JUnit會自動生成測試的代碼框架,手動添加自己的測試代碼后如下:
import junit.framework.TestCase;
public class HelloTest extends TestCase {
private Hello hello;
public HelloTest()
{
super();
System.out.println("a new test instance...");
}
//測試前JUnit會調用setUp()建立和初始化測試環境
protected void setUp() throws Exception {
super.setUp(); //注意:在Junit3.8.1中這里要調用父類的setUp()
hello=new Hello();
System.out.println("call before test...");
}
//測試完成后JUnit會調用tearDown()清理資源,如釋放打開的文件,關閉數據庫連接等等
protected void tearDown() throws Exception {
super.tearDown(); //注意:在Junit3.8.1中這里要調用父類的tearDown()
System.out.println("call after test...");
}
//測試Hello類中的abs函數
public void testAbs() {
System.out.println("test the method abs()");
assertEquals(16, hello.abs(16));
assertEquals(11, hello.abs(-10));//在這里,會出現故障,應該把左邊的參數改為10
assertEquals(0, hello.abs(0));
}
//測試Hello類中的division函數
public void testDivision() {
System.out.println("test the method division()");
assertEquals(3D, hello.division(6, 2));
assertEquals(6D, hello.division(6, 1));
assertEquals(0D, hello.division(6, 0));//在這里,會出現錯誤,java.lang.ArithmeticException: /by zero
}
}
3.運行該測試類,輸出如下:
a new test instance...
a new test instance...
call before test...
test the method abs()
call after test...
call before test...
test the method division()
call after test...
從上面的輸出結果中,可以看出JUnit大概會生成如下的測試代碼:
try {
HelloTest test = new HelloTest(); // 建立測試類實例
test.setUp(); // 初始化測試環境
test.testAbs(); // 測試abs方法
test.tearDown(); // 清理資源
}
catch(Exception e){}
try {
HelloTest test = new HelloTest(); // 建立測試類實例
test.setUp(); // 初始化測試環境
test.testDivision(); // 測試division方法
test.tearDown(); // 清理資源
}
catch(Exception e){}
所以,每測試一個方法,JUnit會創建一個xxxTest實例,如上面分別生成了兩個HelloTest實例來分別測試abs和division方法。