最簡單的范例如下:
1、創建一個TestCase的子類:
package junitfaq;
import java.util.*;
import junit.framework.*;
public class SimpleTest extends TestCase {
public SimpleTest(String name) {
super(name);
}
2、寫一個測試方法斷言期望的結果:
public void testEmptyCollection() {
Collection collection = new ArrayList();
assertTrue(collection.isEmpty());
}
注意:JUnit推薦的做法是以test作為待測試的方法的開頭,這樣這些方法可以被自動找到并被測試。
3、寫一個suite()方法,它會使用反射動態的創建一個包含所有的testXxxx方法的測試套件:
public static Test suite() {
return new TestSuite(SimpleTest.class);
}
4、寫一個main()方法以文本運行器的方式方便的運行測試:
public static void main(String args[]) {
junit.textui.TestRunner.run(suite());
}
}
5、運行測試:
以文本方式運行:
java junitfaq.SimpleTest
通過的測試結果是:
.
Time: 0
OK (1 tests)
Time上的小點表示測試個數,如果測試通過則顯示OK。否則在小點的后邊標上F,表示該測試失敗。
每次的測試結果都應該是OK的,這樣才能說明測試是成功的,如果不成功就要馬上根據提示信息進行修正了。
如果JUnit報告了測試沒有成功,它會區分失。╢ailures)和錯誤(errors)。失敗是你的代碼中的assert方法失敗引起的;而錯誤則是代碼異常引起的,例如ArrayIndexOutOfBoundsException。
文章來源于領測軟件測試網 http://www.kjueaiud.com/