How to enable Assertions - assert keyword in eclipse in java


In this JUnit Tutorial in java we will learn how to enable Assertions i.e. assert keyword in eclipse in java with snapshots.



Generally during testing phase we use assert keyword to avoid Runtime Exceptions in java.

How to enable Assertions - assert keyword in eclipse in java
Step 1) Right click on program in which you want to enable assertions.

Step 2) Pass -ea as argument in VM arguments:



Example/Program to use use Assertions - assert keyword in java
Before executing below you must pass -ea as JVM argument.
public class AssertionsExample {
   public static void main(String args[]) {
          String str = null;
          assert (str != null);
          System.out.println(str.charAt(0));
   }
}
/*OUTPUT
Exception in thread "main" java.lang.AssertionError
   At AssertionsExample.main(NullPointerExceptionAvoidExample10_assertions.java:4)
*/




What will happen if we execute above program without enabling assertions in eclipse in java -
If we doesn’t enable assertions by passing -ea as argument to JVM then output of above program will be totally different, assertions will be ignored at runtime and line below it will throw NullPointerException at runtime in java junit.

Output of above program when we doesn’t enable assertions by passing -ea as argument to JVM  -
Exception in thread "main" java.lang.NullPointerException
   at AssertionsExample.main(AssertionsExample.java:5)



/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */

So in this JUnit Tutorial in java we learned how to enable Assertions i.e. assert keyword in eclipse in java junit.

No comments:

Post a Comment