JUnit Gossip: TestCase 軟件測試
使用JUnit時(shí),您主要都是透過(guò)繼承TestCase類(lèi)別來(lái)撰寫(xiě)測試案例,預設上您可以使用testXXX() 名稱(chēng)來(lái)撰寫(xiě)單元測試。
在測試一個(gè)單元方法時(shí),有時(shí)您會(huì )需要給它一些物件作為運行時(shí)的資料,例如您撰寫(xiě)下面這個(gè)測試案例:
MaxMinTest.java
package onlyfun.caterpillar.test;import onlyfun.caterpillar.MaxMinTool;import junit.framework.TestCase; public class MaxMinTest extends TestCase { public void testMax() { int[] arr = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5}; assertEquals(5, MaxMinTool.getMax(arr)); } public void testMin() { int[] arr = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5}; assertEquals(-5, MaxMinTool.getMin(arr)); } public static void main(String[] args) { junit.swingui.TestRunner.run(MaxMinTest.class); }}
您將設計的MaxMinTool包括靜態(tài)方法getMax()與getMin(),當您給它一個(gè)整數陣列,它們將個(gè)別傳回陣列中的最大值與最小值,顯然的,您所準備的陣列重復出現在兩個(gè)單元測試之中,重復的程式碼在設計中可以減少就儘量減少,在這兩個(gè)單元測試中,整數陣列的準備是單元方法所需要的資源,我們稱(chēng)之為fixture,也就是一個(gè)測試時(shí)所需要的資源集合。
fixture必須與上下文(Context)無(wú)關(guān),也就是與程式執行前后無(wú)關(guān),這樣才符合單元測試的意涵,為此,通常將所需的fixture撰寫(xiě)在單元方法之中,如此在單元測試開(kāi)始時(shí)創(chuàng )建fixture,并于結束后銷(xiāo)毀fixture。
然而對于重復出現在各個(gè)單元測試中的fixture,您可以集中加以管理,您可以在繼承TestCase之后,重新定義setUp()與tearDown()方法,將數個(gè)單元測試所需要的fixture在setUp()中創(chuàng )建,并在tearDown()中銷(xiāo)毀,例如:
MaxMinTest.java
package onlyfun.caterpillar.test;import onlyfun.caterpillar.MaxMinTool;import junit.framework.TestCase;public class MaxMinTest extends TestCase { private int[] arr; protected void setUp() throws Exception { super.setUp(); arr = new int[]{-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5}; } protected void tearDown() throws Exception { super.tearDown(); arr = null; } public void testMax() { assertEquals(5, MaxMinTool.getMax(arr)); } public void testMin() { assertEquals(-5, MaxMinTool.getMin(arr)); } public static void main(String[] args) { junit.swingui.TestRunner.run(MaxMinTest.class); }}
setUp()方法會(huì )在每一個(gè)單元測試testXXX()方法開(kāi)始前被呼叫,因而整數陣列會(huì )被建立,而tearDown()會(huì )在每一個(gè)單元測試 testXXX()方法結束后被呼叫,因而整數陣列參考名稱(chēng)將會(huì )參考至null,如此一來(lái),您可以將fixture的管理集中在 setUp()與tearDown()方法之后。
最后按照測試案例的內容,您完成MaxMinTool類(lèi)別:
MaxMinTool.java
package onlyfun.caterpillar;public class MaxMinTool { public static int getMax(int[] arr) { int max = Integer.MIN_VALUE; for(int i = 0; i < arr.length; i++) { if(arr[i] > max) max = arr[i]; } return max; } public static int getMin(int[] arr) { int min = Integer.MAX_VALUE; for(int i = 0; i < arr.length; i++) { if(arr[i] < min) min = arr[i]; } return min; }}
Swing介面的TestRunner在測試失敗時(shí)會(huì )顯示紅色的棒子,而在測試成功后會(huì )顯示綠色的棒子,而 "Keep the bar green to keep the code clean." 正是JUnit的名言,也是測試的最終目的。
文章來(lái)源于領(lǐng)測軟件測試網(wǎng) http://kjueaiud.com/