JUnit Assumptions

Filed Under: JUnit

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.


import static org.junit.jupiter.api.Assumptions.*;

Let’s say we have a test method defined as:


@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.

junit assumptions requirement

assumeTrue()

We can use assumeTrue() to skip the test if the input number is negative. Below is the updated code:


@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.

JUnit Assumptions assumeTrue example skip test

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.


@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.


@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.

You can checkout complete code from our GitHub Repository.

Comments

  1. Victor says:

    Nice post. Concise even.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages