JUnit测试套件-仅包括特定测试,不是类中的每个测试?

java123999

我设立一个Junit的Test Suite我知道如何使用运行类中所有测试的标准方法来设置测试套件,例如here

是否可以创建一个test suite并且只能运行来自几个不同类的某些测试?

如果是这样,我怎么办呢?

开发商

是否可以创建测试套件并仅运行来自几个不同类的某些测试?

选项(1)(首选):您实际上可以使用@Category进行操作,请参见此处

选择(2):您可以在下面的解释有几个步骤做到这一点:

你需要使用JUnit自定义测试@Rule,并用简单的自定义注释在你的测试用例(如下)。基本上,该规则将在运行测试之前评估所需条件。如果满足前提条件,则将执行Test方法,否则将忽略Test方法。

现在,您需要@Suite照常使用所有Test类

代码如下:

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 {  
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章