In this post under JUnit, I will explain the purpose of “assumingThat” assertion method.
In my previous post
Assumptions in JUnit 5
I showed you how to use “assumeTrue” and “assumeFalse” assumption statements.
Lets add that code here again for recap
Below is the class to be tested.
MockUserRepository
package package14;
public class MockUserRepository {
private boolean status = false;
public boolean isDatabaseConnectionExist() {
status = (status) ? false : true;
return status;
}
public boolean isUserExist(String userName) {
return false;
}
}
The above class is mock object, it has method “isDatabaseConnectionExist” which returns true or false.
True if the database connection exist otherwise false.
The next method “isUserExist” check whether the specified user exist or not.
The test case that we wrote earlier was like below
Previous test case
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 above test class, at line 12, I am checking whether my assumption is true or not. If true, the assert method will be executed if false the assert method will
be skipped.
We can improve the above code even better by using “assumingThat” method. It combines the functionality of both “assumeTrue” and “assertTrue” as shown below
assumingThat(mockUserRepository.isDatabaseConnectionExist(), () -> {
mockUserRepository.isUserExist("john");
});
So in the above code snippet, to the “assumingThat” method we are sending two arguments
1) Supplier functional interface code which checks whether database connection exist or not
2) Executable functional interface code which gets executed when the function passed as first argument returns true.
So in short “assumingThat” method can be used instead of using “assumeTrue” or “assertFalse” with assert methods. We can combine both in “assumingThat” method itself.