Assumptions in JUnit5

In this post under Junit5, I will show with example, how to use Assumptions feature.

Sometimes test case assertions depend on certain conditions. If a condition is met, then test case should be asserted otherwise we should skip the assertion.

To test whether the condition is met or not, we take the help of “assumeTrue” and “assumeFalse” static methods under “Assumptions” class.

These methods check whether the conditions are met or not. If met the test case is executed otherwise the test case is skip.

Lets go through an example.

In our example, I have written a integration test case which accesses the database to check whether a specified user exists. For the test case to work we have to make sure a connection to database exists.

So first we will use “assumeTrue” method to check whether connection to database exist. If true then we execute our assertion. If false we skip our assertion code.

Below is the class to be tested.

Class to be tested


package package7;

import java.util.Random;

public class MockUserRepository {
    public boolean isDatabaseConnectionExist() {
        Random random = new Random();
        int index = random.nextInt(2);
        return (index == 0) ? false : true;
    }

    public boolean isUserExist(String userName) {
        return false;
    }
}

In the above class, I have two methods, one checks whether database connection exists and another method checks whether user exists. The method “isDatabaseConnectionExist” is a utility method and our goal is not to test the method. Our goal is to test “isUserExist” method logic.

Below is the test class

Test Class


1  package package7;
2  
3  import static org.junit.jupiter.api.Assertions.assertTrue;
4  import static org.junit.jupiter.api.Assumptions.assumeTrue;
5  
6  import org.junit.jupiter.api.Test;
7  
8  public class MockUserRepositoryTest { 
9      @Test
10     public void testSeedData() {
11         MockUserRepository mockUserRepository = new MockUserRepository();
12         assumeTrue(mockUserRepository.isDatabaseConnectionExist());
13         
14         assertTrue(mockUserRepository.isUserExist("john"));
15     }
16 }

In the “testSeedData” method, we first check whether database connection exist by using “assertTrue” method. Refer to line 12.

Then if the assumption is true, we test “isUserExist” method logic by calling “assertTrue” method. Refer to line 13.

In this way we can use Assumption’s method “assumeTrue” and “assumeFalse” method.

One thought on “Assumptions in JUnit5

Leave a Reply