Main()方法和suite()方法被用啟動測試。無論是從命令行還是IDE集成開發環境窗口,必須確保junit.jar在你的CLASSPATH環境變量里指定。然后為BadExampleTest.Class類編譯運行下列代碼:
import junit.framework.*;
public class BadExampleTest extends TestCase {
// For now, just verify that the test runs
public void testExampleThread()
throws Throwable {
System.out.println("Hello, World");
}
public static void main (String[] args) {
String[] name =
{ BadExampleTest.class.getName() };
junit.textui.TestRunner.main(name);
}
public static Test suite() {
return new TestSuite(
BadExampleTest.class);
}
}
運行BadExampleTest來驗證所建立的每一件事情的正確性。一旦,main()被調用,Junit框架將自動的執行任意一個用“test”開關命名的方法。繼續并試著運行測試類。如果你正確的做了每一件事,它應該在輸出窗口打印出“Hello World”。
現在,我們要給程序添加一個線程類。我將通過擴展java.lang.Runnable接口來做這件事情。最后,我們將改變策略,并且擴展一個使線程自動創建的類。
在DelayedHello的構造器中,我們創建一個新的線程并且調用它的start()方法。
import junit.framework.*;
public class BadExampleTest extends TestCase {
private Runnable runnable;
public class DelayedHello
implements Runnable {
private int count;
private Thread worker;
private DelayedHello(int count) {
this.count = count;
worker = new Thread(this);
worker.start();
}
public void run() {
try {
Thread.sleep(count);
System.out.println(
"Delayed Hello World");
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public void testExampleThread()
throws Throwable {
System.out.println("Hello, World"); //1
runnable = new DelayedHello(5000); //2
System.out.println("Goodbye, World"); //3
}
public static void main (String[] args) {
String[] name =
{ BadExampleTest.class.getName() };
junit.textui.TestRunner.main(name);
}
public static Test suite() {
return new TestSuite(
BadExampleTest.class);
}
}
文章來源于領測軟件測試網 http://www.kjueaiud.com/