您的位置:軟件測(cè)試 > 開源軟件測(cè)試 > 開源單元測(cè)試工具 > junit
JUnit4之隱藏特性"曝光"
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2014/3/14 13:13:16 ] 推薦標(biāo)簽:JUnit4 單元測(cè)試

只要做Java開發(fā)的,99%的都用過(guò)JUnit。在JUnit4里面除了@Test, @Before, @BeforeClass這樣基本的特性,JUnit4還有些很酷但是大家平時(shí)不太用的特性。我這里做一下介紹,大家可以用一下,或者至少把玩一下:) 以下特性都基于4.8版本。

    ParallelComputer: 并行測(cè)試

當(dāng)需要同時(shí)測(cè)試testcase的時(shí)候,你不需要為自己寫thread來(lái)做這個(gè)事情。JUnit4已經(jīng)有了這個(gè)特性,而且還提供多種同步選擇。例如:

    /**
     * @author 盧聲遠(yuǎn)<michaellufhl@yahoo.com.cn>
     */ 
    public class ParallelComputerTest { 
        
       @Test 
        public void test() {     
          Class[] cls={ParallelTest1.class,ParallelTest2.class }; 
           
          //Parallel among classes 
          JUnitCore.runClasses(ParallelComputer.classes(), cls); 
           
          //Parallel among methods in a class 
          JUnitCore.runClasses(ParallelComputer.methods(), cls); 
           
          //Parallel all methods in all classes 
          JUnitCore.runClasses(new ParallelComputer(true, true), cls);    
        } 
       public static class ParallelTest1{ 
          @Test public void a(){} 
          @Test public void b(){} 
       } 
       public static class ParallelTest2{ 
          @Test public void a(){} 
          @Test public void b(){} 
       } 
    } 

你有3種同步方式:

1: ParallelComputer.classes():所有測(cè)試類同時(shí)開始執(zhí)行,但是每個(gè)類里面的方法還是順序執(zhí)行。在例子里面ParallelTest1和ParallelTest2同時(shí)開始,但是各自的a(),b()還是順序執(zhí)行。

2: ParallelComputer.methods():測(cè)試類順序執(zhí)行,但是每個(gè)類里面的方法是同時(shí)開始執(zhí)行。在例子里面ParallelTest1的a()和b()同時(shí)開始,等結(jié)束之后再開始ParallelTest2。

3: new ParallelComputer(true, true):所有測(cè)試類里面方法同時(shí)開始執(zhí)行。在例子里面4個(gè)方法同時(shí)開始執(zhí)行。

很有意思吧。

    Category: 分類測(cè)試

當(dāng)你有很多testcase,但是你不想每次都執(zhí)行一遍的時(shí)候。你可以把testcase分成若干類,然后可以分類有選擇的來(lái)執(zhí)行這些testcase。

例子:譬如你有2類testcase,一類是重要的用Important.class表示,還有一類不那么重要的用Secondary.class表示。

    /**
     * @author 盧聲遠(yuǎn)<michaellufhl@yahoo.com.cn>
     */ 
    interface Important{}; 
    interface Secondary{}; 
    @RunWith(Categories.class) 
    @IncludeCategory(Important.class) 
    @ExcludeCategory(Secondary.class) 
    @SuiteClasses( { CategoryTest.Alpha.class,  
                     CategoryTest.Beta.class }) 
    public class CategoryTest { 
        
       @Category(Important.class) 
       public static class Alpha{//Alpha is Important except b 
          @Test  
          public void a(){} 
           
          @Test 
          @Category(Secondary.class) 
          public void b(){} 
       } 
        
       public static class Beta{ 
          @Test  
          @Category(Important.class) 
          public void a(){}//a is Important 
       } 
    } 

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