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);
}
}
文章来源于领测软件测试网 https://www.ltesting.net/