junit 5 assertFalse Example

In this article, we will learn about assertFalse() 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 assertFalse() methods present in org.junit.jupiter.api.Assertions class.
Let me list out tools and technologies that I have used to develop JUnit 5 assertFalse Example.

Tools and Technologies Used

  1. Eclipse photon (only this eclipse version supports JUnit 5)
  2. Maven
  3. JUnit 5
  4. JDK 8 or later
assertFalse() method asserts that a condition is false. If it isn't it throws an AssertionError without a message.

assertFalse() Method Example

In this example, first we will create a complex logic containsWhitespace() method and then we will test this method using JUnit 5 assertFalse method.
public static boolean containsWhitespace(final CharSequence seq) {
 if (seq == null || seq.length() == 0) {
  return false;
 }
 final int strLen = seq.length();
 for (int i = 0; i < strLen; i++) {
  if (Character.isWhitespace(seq.charAt(i))) {
   return true;
  }
 }
 return false;
}
Let's write a JUnit test for the above method with different scenarios:
@Test
public void testContainsWhitespace() {
 assertFalse(containsWhitespace(null));
 assertFalse(containsWhitespace(""));
 assertFalse(containsWhitespace("a"));
 assertFalse(containsWhitespace("abc"));
 assertTrue(containsWhitespace(" "));
 assertTrue(containsWhitespace(" a"));
 assertTrue(containsWhitespace("abc "));
 assertTrue(containsWhitespace("a b"));
 assertTrue(containsWhitespace("a  b"));
}

Complete Program for Reference

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.jupiter.api.Test;

public class JUnit5AssertFalseExample {
 public static boolean containsWhitespace(final CharSequence seq) {
  if (seq == null || seq.length() == 0) {
   return false;
  }
  final int strLen = seq.length();
  for (int i = 0; i < strLen; i++) {
   if (Character.isWhitespace(seq.charAt(i))) {
    return true;
   }
  }
  return false;
 }

 @Test
 public void testContainsWhitespace() {
  assertFalse(containsWhitespace(null));
  assertFalse(containsWhitespace(""));
  assertFalse(containsWhitespace("a"));
  assertFalse(containsWhitespace("abc"));
  assertTrue(containsWhitespace(" "));
  assertTrue(containsWhitespace(" a"));
  assertTrue(containsWhitespace("abc "));
  assertTrue(containsWhitespace("a b"));
  assertTrue(containsWhitespace("a  b"));
 }
}

Output

Comments