【问题标题】:JUnit Test Suite- Only include Specific tests, not every test in the Class?JUnit 测试套件 - 仅包括特定测试,而不是类中的每个测试?
【发布时间】:2017-03-28 00:12:39
【问题描述】:

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

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

如果是这样,我该怎么做?

【问题讨论】:

    标签: java unit-testing junit test-suite


    【解决方案1】:

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

    选项(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 {  
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多