}
//測試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大概會生成如下的測試代碼:
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方法。
延伸閱讀
文章來源于領測軟件測試網 http://www.kjueaiud.com/