Author
Oleksandr Miadelets
Head of Developers Team at CodeGym

Java Assertions

Published in the Statements in Java group
Assert statement In Java is used to test certain assumptions about the state of a program during execution. This helps to easily detect errors and debug the program. An assertion statement in Java is written using the Java assert keyword followed by a boolean expression. If the expression evaluates to true, the assertion passes silently and the program does its job. If it evaluates to false, the assertion fails and an AssertionError is thrown. Let’s have an example of a program with Java assertions.

//Assertion in Java example
public class AssertDemo1 {
   public static void main(String[] args) {
       int x = 5;
       assert x == 5 : "x should be 5";
       System.out.println(x);
   }
}
Here the expression is true, so the program just continues its job. The output is just as it expected to be:
5

AssertionError Example

In Java, an AssertionError is a subclass of the Error class and it is thrown when an assertion fails. Assertions in Java are typically used to check that preconditions, postconditions, or invariants hold true. As we said below, an AssertionError is thrown when an assertion statement fails to evaluate to true. Now let's rewrite our program so that the boolean expression is false.

//AssertionError example
public class AssertDemo1 {
   public static void main(String[] args) {
       int x = 5;
       assert x == 7 : "x should be 7";
       //here should be AssertionError
       System.out.println(x);
   }
}
Well, we run it and the output is…
5
Something definitely went wrong in our example! We should have an AssertionError here because our x is 5 and the assertion expects it to be 7. What’s wrong here? It's important to note that Java assertions can be just disabled in the JVM, so they shouldn’t be used as the only means of error checking in a program. They are useful for debugging and testing, but shouldn’t be relied on for production code. So to use assertions, you need to enable them using the vm -ea (or -enableassertions) option. If you are working with command line, you can use next command for your program AssertDemo1:
java -ea AssertDemo1
if you enable assertions and rerun the same program you’ll get the next:
Exception in thread "main" java.lang.AssertionError: x should be 7 at AssertDemo1.main(AssertDemo1.java:4)
That’s the point.

How to enable exceptions in IntelliJ IDEA

  1. Go to Run menu → Edit Configurations....
  2. Enter the -ea parameter in the line VM options
Java Assertions - 1Now the assertions are enabled and you can use them.

Assertions for unit testing in Java

In Java, unit testing is a technique that involves testing individual modules of code to make sure they work correctly. Java Assertions - 2Assertions are commonly used in unit testing in Java to verify that the tested code is working as expected. In unit testing, a unit of code, for example a particular method, is tested in isolation to ensure that it works correctly under different conditions and inputs. Let’s have an example. Here we’ve got a simple calculator for addition, subtraction, multiplication and division 2 integers.

public class MyMath {

   public static int add (int a, int b) {
       return a + b;
   }

   public static int sub (int a, int b) {
       return a - b;
   }

   public static int mult (int a, int b) {
       return a*b;
   }

   public static double div (int a, int b) {
       return a/b;
   }
}
Of course, there are many questions about this implementation (for example, what happens if we add the largest int to another number), but for now we will leave this implementation as it is. Now let's write a class in which we will test the methods of the myMath class with the help of unit tests. True, only two of them. In fact, you can write tests that check arguments for validity, whether a method handles special cases, and so on. But here we will limit ourselves to just a couple of tests for demonstration purposes.

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MyMathTesting {
   @Test
   public void testAdd() {
       MyMath calculator = new MyMath();
       int sum = calculator.add(2, 3);
       assertEquals(5, sum);
   }

   @Test
   public void testSub() {
       MyMath calculator = new MyMath();
       int sub = calculator.sub(5, 2);
       assertEquals(3, sub);
   }

}
The assertEquals method is an assertion that checks whether two values are equal. If the values are not equal, an AssertionError will be thrown, indicating that the test has failed. Using assertions in unit tests can help you catch bugs and ensure that your code is working correctly under different conditions and inputs. Try to add such tests for division and multiplication yourself. It is not difficult.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION