In this JUnit Tutorial in java we will learn when org.junit.ComparisonFailure occurs with example and when equality test fails in java junit.

Before explaining org.junit.ComparisonFailure I will like to tell you about assertEquals() method, which can throwComparisonFailure Exception in java.

About assertEquals method in junit java >

assertEquals(string, string) - Method compares the two objects for equality in java.

How assertEquals method works internally in junit java >

assertEquals(string, string) method internally uses the equals() method to determine equality of the passed objects in the method.

So, internally assertEquals() methods checks for str1.equals(str2)

Program to show org.junit.ComparisonFailure is thrown - when equality test fails using assertEquals(str, str) in java junit >

String str1 and String str2 will be referring to two different string objects, assertEquals(str1, str2) will return false and throws org.junit.ComparisonFailure because assertEquals internally uses equals method and equals method returns false if characters in both String object doesn’t appears in same order.

at AssertionsEqualExceptionExample.main(AssertionsEqualExceptionExample.java:8)

*/

Jar used in above program > junit-4.8.2.jar

Example/ Program to show where equality test passes using assertEquals(str, str) and ComparisonFailure is not thrown in java junit >

String str1 and String str2 will be referring to two different string objects, but assertEquals(str1, str2) will return true because assertEquals internally uses equals method and equals method returns true if characters in both String object appears in same order.

importstatic org.junit.Assert.assertEquals;

publicclass AssertionsEqualExample {

publicstaticvoid main(String args[]) {

String str1 = new String("ab");

String str2 = new String("ab");

assertEquals(str1, str2);

System.out.println("after assertEquals");

}

}

/*OUTPUT

after assertEquals

*/

Jar used in above program > junit-4.8.2.jar

So in this JUnit Tutorial in java we learned when org.junit.ComparisonFailure occurs with example and when equality test fails in java junit.