Conditionally ignoring tests in JUnit 4 Conditionally ignoring tests in JUnit 4 java java

Conditionally ignoring tests in JUnit 4


The JUnit way is to do this at run-time is org.junit.Assume.

 @Before public void beforeMethod() {     org.junit.Assume.assumeTrue(someCondition());     // rest of setup. }

You can do it in a @Before method or in the test itself, but not in an @After method. If you do it in the test itself, your @Before method will get run. You can also do it within @BeforeClass to prevent class initialization.

An assumption failure causes the test to be ignored.

Edit: To compare with the @RunIf annotation from junit-ext, their sample code would look like this:

@Testpublic void calculateTotalSalary() {    assumeThat(Database.connect(), is(notNull()));    //test code below.}

Not to mention that it is much easier to capture and use the connection from the Database.connect() method this way.


You should checkout Junit-ext project. They have RunIf annotation that performs conditional tests, like:

@Test@RunIf(DatabaseIsConnected.class)public void calculateTotalSalary() {    //your code there}class DatabaseIsConnected implements Checker {   public boolean satisify() {        return Database.connect() != null;   }}

[Code sample taken from their tutorial]


In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:

public class CustomRunner extends BlockJUnit4ClassRunner {    public CTRunner(Class<?> klass) throws initializationError {        super(klass);    }    @Override    protected boolean isIgnored(FrameworkMethod child) {        if(shouldIgnore()) {            return true;        }        return super.isIgnored(child);    }    private boolean shouldIgnore(class) {        /* some custom criteria */    }}