What is java.lang.AssertionError in junit java


In this JUnit Tutorial in java we will learn when java.lang.AssertionError occurs with example in java junit.

What is hierarchy of java.lang.AssertionError in java ?

-java.lang.Object
-java.lang.Throwable
 -java.lang.Error
  -java.lang.AssertionError


assertTrue and assertFalse methods can throw java.lang.AssertionError in java >
assertTrue(boolean) - Method tests whether a value returned is true in java.
assertFalse(boolean) -  Method tests whether a value returned is false in java.



Example program where assertFalse(boolean) method throws  java.lang.AssertionError in java >
import static org.junit.Assert.assertFalse;
public class AssertionsFalseExceptionExample {
   public static void main(String args[]) {
      String str1 = new String("ab");
      String str2 = new String("ab");
      assertFalse(str1.equals(str2));
      System.out.println("after assertFalse");
   }
}
/*OUTPUT
Exception in thread "main" java.lang.AssertionError:
   at org.junit.Assert.fail(Assert.java:91)
   at org.junit.Assert.assertTrue(Assert.java:43)
   at org.junit.Assert.assertFalse(Assert.java:68)
   at org.junit.Assert.assertFalse(Assert.java:79)
   at AssertionsFalseExceptionExample.main(AssertionsFalseExceptionExample.java:8)
*/




Example program where assertTrue(boolean) method throws  java.lang.AssertionError in java junit >
import static org.junit.Assert.assertTrue;
public class AssertionsTrueExceptionExample {
   public static void main(String args[]) {
      String str1 = new String("ab");
      String str2 = new String("xy");
     
      assertTrue(str1.equals(str2));
      System.out.println("after assertTrue");
   }
}
/*OUTPUT
Exception in thread "main" java.lang.AssertionError:
   at org.junit.Assert.fail(Assert.java:91)
   at org.junit.Assert.assertTrue(Assert.java:43)
   at org.junit.Assert.assertTrue(Assert.java:54)
   at AssertionsTrueExceptionExample.main(AssertionsTrueExceptionExample.java:8)
*/



How to solve java.lang.AssertionError in java junit >

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class AssertionsTrueFalseExample {
   public static void main(String args[]) {
      String str1 = new String("ab");
      String str2 = new String("ab");
     
      assertTrue(str1.equals(str2));
      System.out.println("after assertTrue");
      assertFalse(!str1.equals(str2));
      System.out.println("after assertFalse");
   }
}
/*OUTPUT
after assertTrue
after assertFalse
*/

Jar used in above program > junit-4.8.2.jar

So in this JUnit Tutorial in java we learned when java.lang.AssertionError occurs with example in java junit.

Related >>

Error in exception handling in java

Labels: Core Java JUNIT
eEdit
Must read for you :