JUnit 5 assertEquals Example

In this article, we will learn how to check two objects are equal. assertEquals() is static method 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 assertEquals() methods present in org.junit.jupiter.api.Assertions class.
Let me list out tools and technologies that I have used to develop JUnit 5 assertEquals 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
assertEquals method asserts that two objects are equal. If they are not a AssertionError without a message is thrown. If expected and actual are null, they are considered equal.

assertEquals(Object expected, Object actual) Method Example

In this example, first we will create a complex method and we will test it using JUnit 5 framework.
package com.javaguides.junit5.assertions;

import static org.junit.Assert.assertEquals;

import org.junit.jupiter.api.Test;

public class JUnit5AssertEqualsExample {
 public static String trimWhitespace(final String str) {
  if (!(str != null && str.length() > 0)) {
   return str;
  }

  int beginIndex = 0;
  int endIndex = str.length() - 1;

  while (beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex))) {
   beginIndex++;
  }

  while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) {
   endIndex--;
  }

  return str.substring(beginIndex, endIndex + 1);
 }

 @Test
 public void testTrimWhitespace() {
  assertEquals(null, trimWhitespace(null));
  assertEquals("", trimWhitespace(""));
  assertEquals("", trimWhitespace(" "));
  assertEquals("", trimWhitespace("\t"));
  assertEquals("a", trimWhitespace(" a"));
  assertEquals("a", trimWhitespace("a "));
  assertEquals("a", trimWhitespace(" a "));
  assertEquals("a b", trimWhitespace(" a b "));
  assertEquals("a b  c", trimWhitespace(" a b  c "));
 }
}

Output

Comments