Learning JUnit Assumptions with Assume

Sometimes our test fails due to an external environment configuration or a date or time zone issue that we don’t have control over. We can defend our tests by using the org.junit.Assume class. This class offers many static methods, such as assumeTrue(condition) or assumeNotNull(condition) and etc. Before executing a test, we can check our assumption using the static methods of the Assume class. If our assumption fails, then the JUnit runner ignores the tests with failing assumptions.

Here are some examples how to use the JUnit Assumptions.

package com.memorynotfound.test;

import org.junit.Test;
import java.io.File;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assume.*;

public class TestExecutionOrder {

    @Test
    public void assumeThatFileSeparatorTest(){
        assumeThat(File.separatorChar, is('/'));
        System.out.println("execute test");
    }

    @Test
    public void assumeNotNullTest(){
        Object object = null;
        assumeNotNull(object);
        System.out.println("execute test");
    }

    @Test
    public void assumeServerIsRunningTest(){
        boolean isServerRunning = false;
        assumeTrue(isServerRunning);
        System.out.println("execute test");
    }
}
A failing assumption in a @Before or @BeforeClass method will have the same effect as a failing assumption in each @Test method of the class.

References

You may also like...