What is assert keyword - How to use Assertions in java


In this JUnit Tutorial in java we will learn what is assert keyword in java? What are advantages of using assertions keyword in java junit ?



  1. assert is keyword in java, it was added in java 4.
  2. Generally during testing phase we use assert keyword to avoid Runtime Exceptions in java.
  3. Assertions makes our code easy to debug at runtime in java.
  4. Assertions makes our code production ready.


Before writing programs to use assert you must know  : How to enable Assertions - assert keyword in eclipse in java


Program to use use Assertions - assert keyword in java junit >
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(AssertionsExample.java:4)
*/

To avoid NullPointerException at line 5 you must use assert before that.



Use assertEquals method in java junit >

assertEquals()  - Method compares the two objects for equality.
assertEquals() method internally uses the equals() method to determine equality of the passed objects in the method.

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
*/



Use assertTrue and assertFalse() method in java junit>

assertTrue() - Method tests whether a value returned is true.
assertFalse() -  Method tests whether a value returned is false

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 what is assert keyword in java. And advantages of using assertions keyword in java junit.


RELATED LINKS>

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



No comments:

Post a Comment