Java 线程測试框架
《Java编程思想》中的測试框架整理:
1、首先定义个一接口。仅用此接口表示在代码中提供有意义的名字,表示状态。
package com.jereh;
public interface InvariantState {}
2、定义两种状态类,表示成功或者失败。失败类对象包含一个对象,该对象表示有关失败的原因信息,这样通常是为了把这样的信息显示出来。
package com.jereh;
public class InvariantOK implements InvariantState{}
package com.jereh;
public class InvariantFailure implements InvariantState{
public Object value;
public InvariantFailure(Object value){
this.value = value;
}
}
3.定义一个接口,不论什么须要对约束条件进行測试的类都必须实现这个接口:
package com.jereh;
public interface Invariant {
InvariantState invariant();
}
4.定义一个类并继承Timer,假设不出现异常状况则一段时间后自己主动结束程序:
package com.jereh;
import java.util.Timer;
import java.util.TimerTask;
public class Timeout extends Timer{
public Timeout(int delay,final String msg){
super(true);
schedule(new TimerTask(){
public void run(){
System.out.println(msg);
System.exit(0);
}
},delay);
}
}
5.定义一个线程,使用Invariant接口和Timeout类。用来当作观察者:
package com.jereh;
public class InvariantWatcher extends Thread{
private Invariant invariant;
public InvariantWatcher(Invariant invariant){
this.invariant = invariant;
setDaemon(true);
start();
}
public InvariantWatcher(Invariant invariant, final int timeOut){
this(invariant);
new Timeout(timeOut,"Timed out without violating invariant");
}
public void run(){
while(true){
InvariantState state = invariant.invariant();
if(state instanceof InvariantFailure){
System.out.println("Invariant violated:"+((InvariantFailure)state).value);
System.exit(0);
}
}
}
}
6.測试一下类,将观察者放入要測试的目标类中:
package com.jereh;
public class EvenGenerator implements Invariant{
private int i ;
public void next(){ i++; i++; }
public int getValue(){ return i; }
@Override
public InvariantState invariant() {
int val = i;
if( val%2 == 0){
return new InvariantOK();
}else{
return new InvariantFailure(new Integer(val));
}
}
public static void main(String[] args){
EvenGenerator gen = new EvenGenerator();
new InvariantWatcher(gen);
while(true)
gen.next();
}
}