JUnit Assumptions With Examples

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.

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

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:

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.

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.

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.

By admin

Leave a Reply

%d bloggers like this: