In this article, we will learn about assertTrue() static method which belongs to JUnit 5 org.junit.jupiter.api.Assertions Class. Note that in JUnit 5 all JUnit 4 assertion methods are moved to org.junit.jupiter.api.Assertions class.
There are many overloaded version of assertTrue() methods present in org.junit.jupiter.api.Assertions class.
Let me list out tools and technologies that I have used to develop JUnit 5 assertTrue Example.
Tools and Technologies Used
- Eclipse photon (only this eclipse version supports JUnit 5)
- Maven
- JUnit 5
- JDK 8 or later
assertTrue() method asserts that a condition is true. If it isn't it throws an AssertionError without a message.
assertTrue() method Example
In this example, first we will create a logical isEmpty()_ and isBlank methods and then we will test these methods using JUnit 5 assertTrue method.
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
public static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
Let's write a JUnit test for the above methods with different scenarios:
@Test
public void isEmptyTest() {
assertTrue(isEmpty(null));
assertTrue(isEmpty(""));
assertFalse(isEmpty(" "));
assertFalse(isEmpty("bob"));
assertFalse(isEmpty(" bob "));
}
@Test
public void isBlankTest() {
assertTrue(isBlank(null));
assertTrue(isBlank(""));
assertTrue(isBlank(" "));
assertFalse(isBlank("bob"));
assertFalse(isBlank(" bob "));
}
Complete Program for Reference
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
public class JUnit5AssertTrueExample {
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
public static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
@Test
public void isEmptyTest() {
assertTrue(isEmpty(null));
assertTrue(isEmpty(""));
assertFalse(isEmpty(" "));
assertFalse(isEmpty("bob"));
assertFalse(isEmpty(" bob "));
}
@Test
public void isBlankTest() {
assertTrue(isBlank(null));
assertTrue(isBlank(""));
assertTrue(isBlank(" "));
assertFalse(isBlank("bob"));
assertFalse(isBlank(" bob "));
}
}
Output
Reference
https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/Assertions.html
Comments
Post a comment