用 Netbeans 5.5 開發 JUnit Test Case 并輸出測試結果
最近在學習/培訓 Java EE 5 的過程中深入使用了一下 Netbeans 5.5, 下面就簡單介紹以下如何用 Netbeans 5.5 快速的開發 Test Case 并運行出 測試 結果. 首先我們新建一個類, 里面寫一個加法運算的方法: package junit test; /** * * @author Administrator */
最近在學習/培訓 Java EE 5 的過程中深入使用了一下 Netbeans 5.5, 下面就簡單介紹以下如何用 Netbeans 5.5 快速的開發 Test Case 并運行出
測試結果.
首先我們新建一個類, 里面寫一個加法運算的方法:
package
junittest; /** * * @author Administrator */ public class Main { public int add(int a, int b) { return a + b; } } 接著我們在 Projects 視圖中源代碼節點上點擊鼠標右鍵, 選擇 Tools -> Create J
Unit Tests, Netbeans 將會自動在 Test Packages 源碼子目錄下為你生成好一個
測試用例(TestCase), 而且還會幫你填好默認的調用方法骨架代碼:
/* * MainTest.
java * JUnit based test */ package junittest; import junit.framework.*; public class MainTest extends TestCase { public MainTest(String testName) { super(testName); } /** * Test of add method, of class junittest.Main. */ public void testAdd() { int a = 0; int b = 0; Main instance = new Main(); int expResult = 0; int result = instance.add(a, b); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } } 接著我們需要修改輸入的參數: int a = 2; int b = 3; 以及期望的輸出參數: int expResult = 5; 然后把 fail 開頭的這行代碼刪除掉, 這樣一個 TestCase 就完成了.
運行也非常簡單, 選擇主菜單的 Run -> Test "項目名", 我們就可以看到輸出的結果了:
PS: 學員有人熟用 Eclipse, 試了一下沒有生成調用代碼的類似機制, 只有新建 TestCase 的向導(注:未安裝其他插件的情況下).
原文轉自:http://www.kjueaiud.com