Wednesday, August 21, 2024

What is Assertion in Java? When and How to use in Code? Example

Where and when to use Assertion in Java is probably the most important thing you want to know about Assertions. In last couple of articles we have seen What is Assertion in Java and How to enable or disable Assertion in Java while in this article 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.


What is Assertion in Java?

Assertion is a Java feature which allows you to run conditional code based upon JVM arguments. You can test a condition on your code using assert keyword and take decision based upon the outcome.  

This is often used to validate assumption in testing and development stage and then you can disable assertion in your production code by using JVM arguments --da or -disableassertions.

In terms of working assert keyword is very straight forward, it test a condition and if condition is not true it fail, but if pass it doesn't do anything and let the code run normally. 

You can use assertion using the assert keyword in Java and enable it using java -ea JVM argument. 

Here is also a code example of how to use assert keyword in Java and how it throws AssertionError if condition its testing is not true:

public class AssertionExample {

    public static void main(String[] args) {
        int number = 5;

        // Assertion to check if the number is positive

        assert number > 0 : "Number should be positive";
        System.out.println("Number is positive: " + number);

        // Example of an assertion that will fail
        number = -5;
        // This will throw an AssertionError
        assert number > 0 : "Number should be positive"; 

        System.out.println("This line will not be executed because 
               the assertion above will fail.");

    }
}

Where to use Java Assertion in Code?

Here are couple of places where its recommended to use Java assertion and than 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 assumption. 

This is even better with comments because many time developer forget to update the comment while maintaining code but assert keyword will ensure your 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  post condition  in both public and nonpublic methods in java.

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

And, here is a nice Java Assertion cheat sheet for your reference to revise the important Assertion concepts

Java assert keyword cheatsheet




Where not to use assertion in Java?

when to use assertion in java, assertEquals codeHere are places where use of Assertion is not recommended in Java:

1) 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. 

Assertion is extremely useful during development phase to find out the loop holes and source of 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 message.

So just remember Assertion does not replace Exception it just complement it.


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

3) 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 concern than you definitely wants to save those CPU cycle, another concern related to gracefully handling of error condition which I have discussed in 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 public method, instead it should be checked by method itself and an appropriate exception e.g. IllegalArgumentException should be thrown in case of violation.


That’s all on What is Java Assertion, benefits of assertion in Java and where to use assertion in Java. 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.


1 comment :

Andy Till said...

It's not very helpful to anyone if your software crashes because of an uncaught runtime exception in production. Especially if it is not so easy for users to restart.

This is why I use asserts to check arguments. Why do you believe this is wrong for all cases?

Post a Comment