???? 閑逛東大浦口圖書館,看到《單元測試之道——java版》,早已聞此書之大名,借來一閱。
??????JUnit有多重要等等就不多說了,如果你想接觸它,Come on,書上有個簡單的例子。下面是一個被測試的例子:
public class Largest {
???? public static int largest(int[] list)
??? {
????????? int index, max = Integer.MAX_VALUE;
??????????for(index=0;index<list.length-1;index++){
????????? if(list[index]>max)max=list[index];
????????? }
???????? return max;
??????? ?}
}
這是一段有錯誤的程序,明眼人應該能看出來,以它來說明JUnit的用法。
我使用的Eclipse 3.1 ,JDK是1.4.2版本的。
在此工程里新建一個JUnit Test Case(JUnit在整個工程中所占的位置在后面有說暫時就隨意了,可以放在被測程序同一個package內,也可以重新新建一個package)
剛生成的Test Case是如下這樣的
package com.test.ray;
import junit.framework.TestCase;
public class TestLargest extends TestCase {
}
標記紅色是因為這是一個test case 一定要繼承的,而上面引用進來的junit.framework.TestCase包含了一個TestCase的具體框架。
跟普通的類一樣,它需要一個構造函數。
public TestLargest(String name)
?{
??super(name);
?}
其中的name到底是什么,下一篇再講。
接下來就可以寫測試函數了,如果你想讓自己寫的測試函數自動被編譯器運行的話,請務必以test作為方法名的開頭。
public void testSimple()
?{
??assertEquals(9,Largest.largest(new int[]{7,8,9}));
??assertEquals(-7,Largest.largest(new int[]{-8,-7,-9}));
?}
測試方法體一般是有斷言組成的(關于斷言的內容,以后再講),第一個斷言主要是測試邊界的,可以看到9位于數組的最后,運行后可以在Eclipse里面看到一個紅條,會有相關的錯誤信息。
junit.framework.AssertionFailedError: expected:<9> but was:<2147483647>
?從此你可以分析到,程序中循環語句判斷條件應該是index<list.length,哈哈,一個錯誤找到了。
可是改過之后還是有錯
仔細看看……
God,max的初始化!!!
可能很多人會想當然地把它改成max=0;
讓我們看看接下來會發生什么。
junit.framework.AssertionFailedError: expected:<-7> but was:<0>
知道為什么了嗎?如果數組里面有負數,得到的結果當然是0了。
應該是這樣max=Integer.MIN_VALUE;
測試順利通過!
其實這個程序還是有漏洞的,就是如果傳入的數組是一個空數組的情況,可以這樣改寫
public class Largest {
?public static int largest(int[] list)
?{
??int index, max = Integer.MIN_VALUE;
??if(list.length==0){throw new RuntimeException("Empty list");}
??for(index=0;index<list.length;index++)
??{
???if(list[index]>max)max=list[index];
??}
??return max;
?}
}
對應的Test Case也改變一下
public class TestLargest extends TestCase {
?public TestLargest(String name)
?{
??super(name);
?}
?public void testSimple()
?{
??assertEquals(9,Largest.largest(new int[]{7,8,9}));
??assertEquals(-7,Largest.largest(new int[]{-8,-7,-9}));
?}
?public void testEmpty()
?{
??try{
???Largest.largest(new int[]{});
???fail("lallal");
???}catch(RuntimeException e){System.out.println("cuo la!");}
?}
}
增加了一個測試數組為空的測試方法,從Test Case下面的Console中可以知道Test Case 已經捕獲了這個異常。
好了,今天就寫到這里,下次有更精彩的內容哦。
?