Witscale Test Center

5.6 Assertions > 5.6.1 How to use assertions


5.6.1 How to use assertions

Assertions are the new addition to Java with version 1.4 onwards. With assertions, you can verify your assumptions about the code during the development cycle. You need not write the handling code for erroneous conditions, which you assume will never appear in the deployment. Let us try to understand how the assertion mechanism works with an example. In the following code, the method generateSchedule(int month) generates a monthly schedule. While testing this method, you need to make sure that the month passed is a value between 1 and 12.

 

private void generateSchedule(int month) {

  if(month >= 1 && month <= 12) {

     // Generate the schedule for the month

  } else {

     System.out.println(“Invalid month “ + month + ” is passed”);

     return;

   }

}

 

At runtime, if the month passed is not between 1 and 12, the method will not function properly. You do not want to continue execution after that. Therefore, the control is returned and debugging message is printed. You can write the same code using the assert statement as:

 

private void generateSchedule(int month) {

   assert(month >= 1 && month <= 12);

   // Generate the schedule for the month

}

As you can see the second form of code with assert is cleaner and concise than the previous one. If you compile and run this code appropriately (we will soon see how to do that), the code will fail to run for an invalid month. It will throw an error called as AssertionError at runtime. Not only are the assertions concise and simpler, you can turn them off if you want at runtime. In that case the generateSchedule() will run as if there is no assert statement in it.