JUnit Assert.assertEquals() Method Example

 assertEquals() method belongs to JUnit 4 org.junit.Assert class. In JUnit 5 all JUnit 4 assertion methods are moved to org.junit.jupiter.api.Assertions class.

void org.junit.Assert.assertEquals(Object expected, Object actual)

This method asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null, they are considered equal.
Parameters:
  • expected - expected value actual - the value to check against expected

Assert.assertEquals() Method Example

Let's create trimWhitespace() method to trim leading and trailing whitespace from the given String. We will create a JUnit test for trimWhitespace() method to do unit testing.
import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class AssertEqualsExamples {
 /**
  * Trim leading and trailing whitespace from the given {@code String}.
  * 
  * @param str
  *            the {@code String} to check
  * @return the trimmed {@code String}
  * @see java.lang.Character#isWhitespace
  */
 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:

Related JUnit Examples

Comments