您的位置:軟件測(cè)試 > 開源軟件測(cè)試 > 開源單元測(cè)試工具 > junit
JUNIT源碼探秘系列(下)
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2013/4/16 14:34:04 ] 推薦標(biāo)簽:

Client(客戶端)

  public static void main(String[] args)

  {

     Component leaf1 = new Leaf();

     Component leaf2 = new Leaf();   

     Composite comp1 = new Composite();

   

     comp1.add(leaf1);

     comp1.add(leaf2);   

     Component leaf3 = new Leaf();

     Component leaf4 = new Leaf();   

     Composite comp2 = new Composite(); 

     comp2.add(comp1);

     comp2.add(leaf3);

     comp2.add(leaf4);   

     comp2.doSomething();

}

這樣對(duì)組合模式基本分析完成,繼續(xù)接著看下在Junit組合模式是樣實(shí)現(xiàn)的呢?

在Junit中有連個(gè)重要的概念,一個(gè)是TestCase一個(gè)是TestSuite;TestSuite是一個(gè)測(cè)試集合,一個(gè)TestSuite中可以包含一個(gè)或者多個(gè)TestSuite,當(dāng)然也可以一個(gè)或者多個(gè)TestCase,而這兩個(gè)對(duì)象都繼承與Test接口。這樣一分析,Test接口相當(dāng)于組合模式中的抽象構(gòu)件角色(Component),TestSuite相當(dāng)于樹枝構(gòu)件角色(Composite),TestCase相當(dāng)于樹葉構(gòu)件角色(Leaf)。接著我們對(duì)具體代碼分析看看這塊是否滿足組合模式。

Test接口類:

public interface Test {

 

   public abstract int countTestCases();

 

   public abstract void run(TestResult result);

}

TestSuite實(shí)現(xiàn):

 

  public int countTestCases() {

     int count= 0;

     for (Enumeration e= tests(); e.hasMoreElements(); ) {

        Test test= (Test)e.nextElement();

        count= count + test.countTestCases();

     }

     return count;

  }

 

  public void run(TestResult result) {

     for (Enumeration e= tests(); e.hasMoreElements(); ) {

        if (result.shouldStop() )

            break;

        Test test= (Test)e.nextElement();

        runTest(test, result);

     }

}

TestCase實(shí)現(xiàn)

  public int countTestCases() {

     return 1;

  }

public void run(TestResult result) {

     result.run(this);

}

根據(jù)代碼分析,Junit使用Composite模式后簡化了JUnit的代碼,JUnit可以統(tǒng)一處理組合結(jié)構(gòu)TestSuite和單個(gè)對(duì)象TestCase。使JUnit開發(fā)變得簡單容易,因?yàn)椴恍枰獏^(qū)分部分和整體的區(qū)別,不需要寫一些充斥著if else的選擇語句。

另外,通過對(duì)TestCase對(duì)象和TestSuite的類層次結(jié)構(gòu)基本對(duì)象的定義,TestCase可以被組合成更復(fù)雜的組合對(duì)象TestSuite,而這些組合對(duì)象又可以被組合,這樣不斷地遞歸下去。在程序的代碼中,任何使用基本對(duì)象的地方都可方便的使用組合對(duì)象,大大簡化系統(tǒng)維護(hù)和開發(fā)。

上一頁1234567下一頁
軟件測(cè)試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請(qǐng)使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd