默認的測試類的執行結果是全部都不能通過的,結果如下:
我們需要對生成的測試代碼進行修改,將我們的測試用例以及期望的結果寫入測試代碼中,將fail(“測試案例為原型”);語句刪除。testAdd的代碼修改后如下:
public void testAdd() {
System.out.println("testAdd");
// TODO add your test code below by replacing the default call to fail.
// fail("The test case is empty.");
// Ceate the objects we will use during the test. These objects are commonly
// referred to as a test'sfixture. All we need for the testAdd test are some
// Money objects.
Money m12CHF= new Money(12, "CHF");
Money m14CHF= new Money(14, "CHF");
Money expected= new Money(26, "CHF");
// Exercise the objects in the fixture
Money result= m12CHF.add(m14CHF);
// Verify the result
Assert.assertTrue(expected.equals(result));
}
該方法創建了兩個進行加法操作的對象m12CHF和m14CHF,相加的結果為result對象,然后將result與期望的對象expected對象進行相等性測試。對修改后的測試代碼再次執行結果如下:
對所有的測試用例進行測試通過后,即可以開始填寫單元測試報告。通過單元測試的類比沒有經過測試的類的穩定性將大大提高。
6 總結
NetBeans集成的Junit單元測試工具為單元測試提供了一個很好的框架,我們無需將精力浪費在寫單元測試代碼上,而將更多的關注測試用例的設計。開發人員進行測試越來越方便,這也增強了開發人員進行單元測試的信心,在趕工期的同時將單元測試做好,是保證項目最后能夠成功,不成為“無底洞”的一個重要手段。