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

當你執(zhí)行后會發(fā)現(xiàn)只有Alpha.a()和Beta.a()執(zhí)行到,Alpha.b()被@ExcludeCategory掉了。

    MaxCore: 失敗優(yōu)先

  當需要反復測試大量testcase的時候,你往往比較關注那些前一次失敗的case。這個時候你可以利用MaxCore特性在每次執(zhí)行testcase的時候優(yōu)先執(zhí)行那些上次失敗的case。

例如:

    /**
     * @author 盧聲遠<michaellufhl@yahoo.com.cn>
     */ 
    public class MaxCoreTest { 
        
       private MaxCore fMax; 
        
       @Before 
       public void createMax() { 
          File fMaxFile= new File("MaxCore.ser"); 
          fMax= MaxCore.storedLocally(fMaxFile); 
       } 
        
       @Test  
       public void test(){ 
          Request request= Request.aClass(Delta.class); 
          fMax.run(request); 
          fMax.run(request);//b->c->a 
       } 
        
       public static class Delta{ 
          @Test public void a(){} 
          @Test public void b(){ 
             Assert.fail(); 
          } 
          @Test public void c(){} 
       } 
    } 

可以觀察到第2次執(zhí)行的時候Delta.b()由于第1次的失敗而提前到了先執(zhí)行。

    DataPoint: 參數(shù)數(shù)據(jù)

當需要測試不同輸入?yún)?shù)的時候是不是要寫一大堆testcase?不需要,因為JUnit4提供了參數(shù)化測試數(shù)據(jù)的特性。例如你想要測試2個整型數(shù)據(jù)作為輸入?yún)?shù)的時候:

    /**
     * @author 盧聲遠<michaellufhl@yahoo.com.cn>
     */ 
    @RunWith(Theories.class) 
    public class DataPointTest { 
       @DataPoint 
       public static int ONE= 1; 
       @DataPoint 
       public static int TWO= 2; 
      
       /* You could also use @DataPoints instead of @DataPoint
       @DataPoints
       public static int[] points= { 1, 2 };*/ 
      
       @Theory 
       public void test(int first, int second) { 
       } 
    } 

通過觀察test()被執(zhí)行了4次,每次不同的組合作為參數(shù)輸入。而且如果參數(shù)數(shù)目過多,你可以通過@DataPoints一下子把參數(shù)都設進去。用過@RunWith(Parameterized.class)的朋友可以和DataPoint做一下比較。

    TestedOn

這個功能也是參數(shù)化數(shù)據(jù),只不過它是直接在參數(shù)上配置。例如:

    @Theory 
    public void test2(@TestedOn(ints={1,2})int first) { 
        System.out.println(first); 
    } 

結(jié)果打印出來"1,2"。

    PrintableResult: 打印結(jié)果

這個我認為倒是一個小功能,它只是把測試失敗的結(jié)果以比較美觀的格式打出來。例如:

    Result result = JUnitCore.runClasses(SomeTest.class); 
    System.out.println(new PrintableResult(result.getFailures())); 

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