2016-11-14 51 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 { 
}