java123999 java123999 - 1 year ago 73
Java Question

JUnit Test Suite- Only include Specific tests, not every test in the Class?

I am setting up a Junit

Test Suite
. I am aware of how to set up a test suite using the standard method that runs all tests in a class, for example here.

Is it possible to create a
test suite
and only run certain tests from several different classes?

If so, how do I do so?

Answer Source

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:

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

   public Statement apply(Statement stmt, Description desc) {

           return new Statement() {

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

MyTests class:

public class MyTests {

        public MyTestRule myProjectTestRule = new MyTestRule();

        public void testMethod1() {
                //testMethod1 code here

        public void testMethod2() {
                //this test will NOT get executed as COND1 defined in Rule
                //testMethod2 code here


MyTestSuite class:

public class MyTestSuite {  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download