Sunday, July 25, 2021

What is Assertion in Java - Java Assertion Tutorial Example

Java Assertion or assert keyword in Java is a little unknown and not many programmers are familiar with this and it's been rarely used especially if you have not written a unit test using JUnit which extensively uses Java assertion to compare test result. JUnit itself is the biggest manifestation of what assertion in Java can do and believe me by using assertion along with Exception you can write robust code. Assertion not only improves the stability of code but also help you to become a better programmer by forcing you to think about different scenario while writing production-quality code and improving your think through ability.


This article is in continuation of my earlier post like How SubString works in Java or Why main is public static in java if you haven’t read you may find interesting.


Java Assertion tutorial - How Assertion works in Java

What is assert keyword in Java

assert keyword is used to implement assertion in java. we can use assert keyword in two format

assert booleanExpression;
assert booleanExpression : errorMessage;

(here error message cannot be an invocation of a method with return type void)



How Assertion works in Java

What is assertion in Java, assert keyword in JavaAs shown above, assert keyword in Java has two forms first form "assert booleanExpression " is used to test the boolean expression and if the boolean expression is false then java throws AssertionError and your program terminates. 

You can use assert here to validate input or assumption for example for a method which calculates stock price for trading, name of stock should not be null or empty, but as Java recommends we should not use assertion to check arguments of public method instead public method should always check its argument and throw appropriate exception e.g. IllegalArgumentException.

The second form of assert keyword "assert booleanExpression : errorMessage" is more useful and provides a mechanism to pass additional data when Java assertion fails and java throws AssertionError.



The benefit of using Assertion in Java

The assertion in Java offers several benefits to the programmer if it used properly. even many of seasoned programmer has recommended using assertion in Java as good programming practice and good to add this point to your code review checklist? let's figure out why using assert keyword is desired and what benefit assertion offers :

1) assertion is simply great for data validation. In my opinion there is no better way than using java assert keyword to validate data passed to method, classic example is a method which calculates interest rates here we know that amount, time cannot be less than zero by using assert keyword in java we can validate this data at run-time and if by any chance your function is getting incorrect data your program will fail with AssertionError. See The Complete Java MasterClass for more details. 


2) The assertion in Java guarantees that at a certain point on function your assumption or a certain condition is true otherwise it would not have come to that point and would have been terminated with AssertionError, this makes debugging in Java lot easier.


3) Using Java assert keyword helps to detect bug early in development cycle which is very cost effective. The assertion in Java also makes debugging easier to me AssertionError is the best kind of error while debugging because its clearly tell source and reason of error. 

Also, code written using assert keyword fails close to the source of error and require less time to find out the cause as compared to code without assert keyword.


4) assert statement in Java is similar to unit test directly integrated into your code and have more chances to test your code with real-world data than JUnit test case, so it always complements your JUnit tests or integration test suite. See JUnit and Mockito Crash Course to learn more. 


5) writing code with assert statement will help you to be better programmer and improve quality of code, yes this is true based on my experience when we write code using assert statement we think through hard, we think about possible input to a function, we think about boundary condition which eventually results in better discipline and quality code.


6) assertion in java gives you lot of confidence while maintaining or refactoring code, you can create new code and use assertion to compare the output with the old method if your program works well then you can simply comment out your old method.

// original code snippet:
int stockPrice = calculateStockPrice();

// code while refactoring and testing:
assert(calculateStockPrice() == newCalculateStockPrice());
int stockPrice = newCalculateStockPrice();

// code after refactoring completed:
int stockPrice = newCalculateStockPrice();




How to enable or disable Assertion in Java

The good thing about Assertion in Java is that you can enable or disable Assertion at runtime. The designer of java is really very thoughtful, they have thought of many situations while designing java and its API. 

One of the gems is the ability to enable or disable assertion at runtime without any change in the code. In the last article, we see how Assertion works in Java and now we will see some step by step guide on how to disable or enable Assertion in Java By default assertions in Java are disabled at runtime and JVM provides following options to deal with the assertion in Java :

Enable or disable Assertion in Java

--ea[:...|:] or enableassertions  (to enable assertion at a particular package and class level)
--da[:...|:] or disable assertions (to disable assertion on a package or class level)
--esa or enablesystemassertions  (for enabling system assertion)
--dsa or disablesystemassertions (for disabling system assertion)

1) if we use -enableassertions or -disableassertions without arguments it enables or disables assertion in all classes except System classes

2) if we use -ea or -da with "packageName..." it enables or disables assertions in the named package and any subpackage.

3) -enable assertions with "..." only enable assertions in the unnamed package in the current working directory.

4) -enableassertions with "class name" only enable assertion in the named class in Java.




Example of Enable and Disable Assertion in Java

how to enable and disable assertions in Java example guideHere is an example of enabling assertion in java: in below example assertions will be enabled for package  "com.onlinestockbroker.electronicTrading" and it subpackage.

java -ea:com.onlinestockbroker.electronicTrading... EquityStocks

and here is another example of disabling Assertion in the same class

java -da:com.onlinestockbroker.electronicTrading... EquityStocks


That’s all about how to enable and disable Java Assertion. The important point is that you don’t need to change anything on code and can disable assertion at runtime with just changing some JVM options, which gives you the flexibility to run the same code on development and production environment. 

While in development you can enable assertion, you can disable assertion in production with just JVM switch. If you are not familiar with JVM, then you can see the Comprehensive Introduction of Java Virtual Machine to learn more. 




How to use Assertion in Java Code - When, Where

Where and when to use Assertion in Java is probably the most important thing you want to know about Assertions. In the last couple of paragraph, we have seen What is Assertion in Java and How to enable or disable Assertion in Java while in this section we will discuss most important part “Where to use Java Assertions”.

As I have always said Java Assertion should be taken as replacement of JUnit testing or Exception in Java Instead Assertion compliments both Unit testing and Exception and if used property provides you another testing tool which may test application with more real data than JUnit tests.


Where to use Java Assertion in Code

Here are a couple of places where its recommended to use Java assertion and then we will see code places where Assertion is not recommended:

1) Whenever we write a method in java we put some code comment around it to document our assumptions, we can also put similar assert statement in Java to validate the assumption. this is even better with comments because many time developers forget to update the comment while maintaining code but assert keyword will ensure yours remember by throwing AssertionError.


2) you can use java assertion to check argument or parameter of non-public method e.g. private method.


3) you can use assertion in java to check "lock status precondition" where a non-synchronized helper method is called form synchronized one and that method assume that a particular thread holds a lock.


4) you can use assertion in java to check postcondition in both public and nonpublic methods in java.

Some popular example of Assertion is in Junit tests like assertEquals() in JUnit testing etc.




Where NOT to use Assertion in Java

Here are places where the use of Assertion is not recommended in Java:

1) The assertion in Java is not a replacement of Exception, so don't confuse Assertion with Exception though both help you to write robust Java Application. The assertion is extremely useful during the development phase to find out the loopholes and source of the problem but in production, you really don't want that your program crashes with just a bad input, instead, you want to handle that situation gracefully using Exception, log the error and continue with processing other messages. So just remember Assertion does not replace Exception it just complements it.


2) Another important point about Assertion is that it should not be considered as a replacement of Unit testing, though it also works with the same concept of validation as unit testing it just complements it and doesn't replace an automatic suite of well thought JUnit test cases. 


3) The assertion should not be used in Production environment, though this is my personal opinion I found that assert statement at least take some CPU and if performance is a concern then you definitely want to save those CPU cycle, another concern related to gracefully handling of an error condition which I have discussed in the first point. 

You can simply disable assertion in java by using runtime switch -da or you can put your assert code inside isDebug() call so that you enable them in debug mode and control via logging in Java for more code coverage.


4) You should not use Java assertion to check arguments or parameters of the public method, instead, it should be checked by the method itself and an appropriate exception e.g. IllegalArgumentException should be thrown in case of violation.


What is Assertion in Java - Java Assertion Tutorial



That’s all about Java Assertion, benefits of assertion in Java and where to use assertion in Java. The key point is Assertion should be thought as replacement of unit testing or Exception rather it compliments both of them, with Java assertion you can have more real-world data for testing than unit testing.


Important points about Java Assertion

1) The assertion is introduced in JDK 1.4 and implemented using assert keyword in Java.

2) assertion can be enabled and disable at runtime by using the switch -da or -disableassertion

3) Always remember Assertion does not replace Exception but compliments it.

4) Another important point is Assertion also doesn't replace the need for unit testing instead if you see JUnit it shows how an assertion can be useful to validate conditions.

5) do not use assertion to validate arguments or parameters of the public method.

6) you can compile java code where assert is a legal identifier instead of keyword because bypassing -source 1.3 during compilation. if you are working on java version 1.2 you can compile your code with the assertion as below "

javac -source 1.4 OnlineStockTradingDemo.java

That’s all about Java Assertion, benefits of assertion in Java, and where to use assertion in Java. The key point is Assertion should be thought as a replacement of unit testing or Exception rather it compliments both of them, with Java assertion you can have more real-world data for testing than unit testing.


Other Java Articles You may like
Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any questions or feedback, please drop a note.  


3 comments :

Tahir said...

I love Junit because of Assertion. JUnit uses Assertion at its best. methods like assertEquals(), assertTrue() are just remarkable and shows how powerful assertion mechanism can be. We have been using assert keyword to test precondition of private methods from long time and benefited a lot. we also learned from mistake of using assertion to validate argument of public method which is apparently not a correct way, instead Exception should be used to check argument of public method and throw IllegalArgumentException if arguments are not proper.

Srikanth goud said...

"do not use assertion to validate arguments or parameters of public method."
Please Explain this point more with a good example.


Unknown said...

I think Javin Paul has missed out a very important point of Assertion in java which is it is disabled by default. Hence, it has no overhead in performance issue.
http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html#enable-disable

Post a Comment