Java 線程測試架構

來源:互聯網
上載者:User

標籤: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();    }}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java 線程測試架構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.