JUnit Assumptions helps us in skipping a test for some specific scenario. Sometimes our test cases are dependent on the inputs, operating systems or any third party data. If our test is not written for some specific inputs, then we can use assumptions to skip our test method.
JUnit Assumptions
JUnit Jupiter Assumptions class provide a useful collection of assumption methods. It’s a good idea to import them in our test class and write fluent code.
1 2 3 |
import static org.junit.jupiter.api.Assumptions.*; |
Let’s say we have a test method defined as:
1 2 3 4 5 6 7 8 9 10 11 |
@ParameterizedTest @ValueSource(ints = {1,2,3,-1}) void test(int i) { try { Thread.sleep(i); } catch (InterruptedException e) { e.printStackTrace(); } } |
For simplicity, I am using ValueSource
but we could have a third party method to feed the input test data. If we run above test, one of the tests will fail.
assumeTrue()
We can use assumeTrue() to skip the test if the input number is negative. Below is the updated code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@ParameterizedTest @ValueSource(ints = {1,2,3,-1}) void test(int i) { assumeTrue(i >=0); // assumeTrue(i >=0, "Wrong Input, Only positive ints please"); try { Thread.sleep(i); } catch (InterruptedException e) { e.printStackTrace(); } } |
Now when we run the test, JUnit will skip when the input number is negative.
assumeFalse()
We can use assumeFalse() to validate that the condition is returning false. Let’s say we have a test method that we don’t want to run with ‘root’ user. We can use assumeFalse() to skip the test, in this case, using system environment variable.
1 2 3 4 5 6 7 |
@Test void test_assumeFalse() { assumeFalse("root".equals(System.getenv("USER"))); //code that I don't want to run as root user } |
assumingThat()
This method executes the supplied Executable if the assumption is valid. If the assumption is invalid, this method does nothing. We can use this for logging or notifications when our assumptions are valid.
1 2 3 4 5 6 7 |
@Test void test_assumingThat() { assumingThat("pankaj".equals(System.getenv("USER")), () -> {System.out.println("USER is pankaj, continue further");}); } |
JUnit assume vs assert
JUnit assert is used to write testing scenarios for our test methods. Whereas assume is used to validate favorable conditions for our test cases.
If JUnit assert fails, the test fails. If junit assumptions fails then test method is skipped.
That’s all for a quick roundup on JUnit Jupiter assumptions.