In this post, we will learn how to use the assertTrue() method with an example.
The assertTrue() method belongs to JUnit 4 org.junit.Assert class.
Check out JUnit 5 tutorials and examples at https://www.javaguides.net/p/junit-5.html
When to use assertTrue() method
In case we want to verify that a certain condition is true or false, we can respectively use the assertTrue assertion or the assertFalse one.
void org.junit.Assert.assertTrue(boolean condition)
Asserts that a condition is true. If it isn't it throws an AssertionError without a message.
Parameters:
- condition - condition to be checked
Assert.assertTrue() method example
The below example demonstrates how to use assertTrue() method check empty or null condition methods:
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class AssertTrueExample {
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:
Related JUnit Examples
- JUnit Assert.assertArrayEquals() Method Example
- JUnit Assert.assertEquals() Method Example
- JUnit Assert.assertTrue() Method Example
- JUnit Assert.assertFalse() Method Example
- JUnit Assert.assertNull() Method Example
- JUnit Assert.assertNotNull() Method Example
- JUnit Assert.assertSame() Method Example
- JUnit Assert.assertNotSame() Method Example
- JUnit Assert.fail() Method Example
Comments
Post a Comment
Leave Comment