2016-11-14 69 views

回答

2

是否有可能創建一個測試套件,並只從 幾個不同的類運行某些測試?

選項(1)(喜歡這個):實際上,你可以做到這一點使用@Category爲這你可以看看here

選擇(2):你可以用幾個步驟做到這一點的解釋如下:

您需要使用JUnit自定義測試@Rule並在您的測試用例中使用一個簡單的自定義註釋(以下給出)。基本上,規則將在運行測試之前評估所需條件。如果滿足前提條件,將執行Test方法,否則將忽略Test方法。

現在,您需要像往常一樣將所有測試類別與您的@Suite相關聯。

MyTestCondition自定義註解:

的代碼如下給出

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface MyTestCondition { 

     public enum Condition { 
       COND1, COND2 
     } 

     Condition condition() default Condition.COND1; 
} 

MyTestRule類:

public class MyTestRule implements TestRule { 

     //Configure CONDITION value from application properties 
    private static String condition = "COND1"; //or set it to COND2 

    @Override 
    public Statement apply(Statement stmt, Description desc) { 

      return new Statement() { 

     @Override 
     public void evaluate() throws Throwable { 

       MyTestCondition ann = desc.getAnnotation(MyTestCondition.class); 

       //Check the CONDITION is met before running the test method 
       if(ann != null && ann.condition().name().equals(condition)) { 
         stmt.evaluate(); 
       } 
     }   
     }; 
    } 
} 

MyTests類:

public class MyTests { 

     @Rule 
     public MyTestRule myProjectTestRule = new MyTestRule(); 

     @Test 
     @MyTestCondition(condition=Condition.COND1) 
     public void testMethod1() { 
       //testMethod1 code here 
     } 

     @Test 
     @MyTestCondition(condition=Condition.COND2) 
     public void testMethod2() { 
       //this test will NOT get executed as COND1 defined in Rule 
       //testMethod2 code here 
     } 

} 

MyTestSuite類:

@RunWith(Suite.class) 
@Suite.SuiteClasses({MyTests.class 
}) 
public class MyTestSuite { 
}