JUnit - Ignore test when part of Suite

1.7k views Asked by At

I am organizing some tests into suites, which is great, but I need to ignore the tests that are part of a suite so that my build doesn't run them automatically.

I can achieve that by excluding them from the build process, but wanted to see if JUnit supports that natively.

What is the cleanest way to achieve that?

EDIT: In order to achieve that in a maven build I can categorize the tests (https://stackoverflow.com/a/14133020/819606) and exclude an entire category (https://stackoverflow.com/a/18678108/819606).

1

There are 1 answers

1
Naman On

Junit4 - You can try using

@Ignore 
public class IgnoreMe {
           @Test public void test1() { ... }
           @Test public void test2() { ... }
}

transformed to something like -

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@SuiteClasses( {IgnoreMe.class, AnotherIgnored.class})
@Ignore
public class MyTestSuiteClass {
....
// include BeforeClass, AfterClass etc here
}

Source - Ignore in Junit4


Junit5 - You can try something similar like -

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

@Disabled
class DisabledClassDemo {
    @Test
    void testWillBeSkipped() {
    }
}

Source - Disabling Tests in Junit5

along with suite implementation in Junit5 as

If you have multiple test classes you can create a test suite as can be seen in the following example.

import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.runner.SelectPackages;
import org.junit.runner.RunWith;

@RunWith(JUnitPlatform.class)
@SelectPackages("example")
@Disabled
public class JUnit4SuiteDemo {
}

The JUnit4SuiteDemo will discover and run all tests in the example package and its subpackages. By default, it will only include test classes whose names match the pattern ^.*Tests?$.

where @SelectPackages specifies the names of packages to select when running a test suite via @RunWith(JUnitPlatform.class), so you can specify those which you want to execute OR those which you don't want to execute and mark them disabled as above.

Further reads - @Select in Junit5 and Running a Test Suite in Junit5