經驗二、不要假定測試用例中測試的執行次序 我們知道在一個junit 的測試用例類中可以包含多個測試,每個測試其實就是一個method。在下面的例子 中有兩個不同的測試,盡管testdothisfirst()在位置上先于testdothissecond(),但我們不能就此假定 testdothisfirst()會先執行。 public class sometestcase extends testcase{ public sometestcase(string testname){ super(testname); } public void testdothisfirst(){ ... } public void testdothissecond(){ } } 由于junit 內部使用一個vector 來存儲所有的test,因此在不同的操作系統和java 虛擬機上,test 的執行 次序是不可猜測的。 好的習慣是保持測試之間的獨立性,使得它們在任何次序下執行的結果都是相同的。假如真得需要某些測試 按照特定的次序執行,我們可以借助addtest 來實現。如下例: public static testsuite(){ suite.addtest(new sometestcase(“testdothisfirst”;)); suite.addtest(new sometestcase(“testdothissecond”;)); return suite; } 這樣我們可以確保junit先執行testdothisfirst(),然后執行testdothissecond()。
經驗三、測試要避免人工干預 假如某段測試代碼需要人工干預,那至少有兩個不良后果:一則不能被包括在自動測試中,比如夜間的回 歸測試;二則不能被重復執行,例如數據刪除的測試不能做完刪除就萬事大吉,比較好的做法是自動補上 刪除掉的數據。經驗二講的是不同的測試要避免相關性,而經驗三講的其實就是測試要避免自相關。 經驗四、在子類中調用父類的setup() 和teardown()讓我們看一看下面的代碼 public class sometestcase extends anothertestcase { // a connection to a database private database thedatabase; public sometestcase (string testname) { super (testname); } public void testfeaturex () { ... } public void setup () { // clear out the database thedatabase.clear (); } } 你發現其中的錯誤了嗎?setup()應該調用super.setup() 以確保anothertestcase 中定義的父類的環境被初 始化了。當然這也有例外,就是基類可以處理任意的測試數據。