您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > junit
JUNIT源碼探秘系列(下)
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 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();

}

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

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

Test接口類:

public interface Test {

 

   public abstract int countTestCases();

 

   public abstract void run(TestResult result);

}

TestSuite實現(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實現(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和單個對象TestCase。使JUnit開發(fā)變得簡單容易,因為不需要區(qū)分部分和整體的區(qū)別,不需要寫一些充斥著if else的選擇語句。

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

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