org.junit.ComparisonFailure - example when equality test fails


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 throw ComparisonFailure 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.
import static org.junit.Assert.assertEquals;
public class AssertionsEqualExceptionExample {
   public static void main(String args[]) {
      String str1 = new String("ab");
      String str2 = new String("xy");
      assertEquals(str1, str2); //org.junit.ComparisonFailure: expected:<[ab]> but was:<[xy]>
      System.out.println("after assertEquals");     
   }
}
/*OUTPUT
Exception in thread "main" org.junit.ComparisonFailure: expected:<[ab]> but was:<[xy]>
   at org.junit.Assert.assertEquals(Assert.java:123)
   at org.junit.Assert.assertEquals(Assert.java:145)
   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.
import static org.junit.Assert.assertEquals;
public class AssertionsEqualExample {
   public static void 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.



RELATED LINKS>

Difference between equals method and == operator in java - testing with String and StringBuffer

Differences between throw and throws in java


No comments:

Post a Comment