Is it possible to create a test suite and only run certain tests from
several different classes?
Option (1) (prefer this): You can actually do this using @Category
for which you can look here
Option (2): You can do this with few steps as explained below:
You need use JUnit custom Test @Rule
and with a simple custom annotation (given below) in your Test case. Basically, the Rule will evaluate the required condition before running the Test. If the pre-condition is met, Test method will be executed, otherwise, Test method will be ignored.
Now, you need all the Test classes to your @Suite
as usual.
The code is given below:
MyTestCondition Custom Annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTestCondition {
public enum Condition {
COND1, COND2
}
Condition condition() default Condition.COND1;
}
MyTestRule class:
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 class:
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 class:
@RunWith(Suite.class)
@Suite.SuiteClasses({MyTests.class
})
public class MyTestSuite {
}