Programming languages like C, Java and others have a less known or less used test mechanism known as assertion. Assertions allows us to quickly test if an expression evaluates to true at run-time without using any extra test tools such as Junit. Assertion expects results of an expression to always be True or else the code immediately stops execution. This answer from SO bellow explains when it is ideal to use assertions.
Assertions should be used to check something that should never happen, while an exception should be used to check something that might happen.
For example, a function might divide by 0, so an exception should be used, but an assertion could be used to check that the harddrive suddenly disappears.
Basic Java example:
// This will throw an exception because, 5 > 10 = false assert 5 > 10;
Append a message to the thrown exception in Java example:
/// Message will be appended to the exception assert 5 > 10 : "Number is less than 5"
Note, assertions are disabled by default in Java, therefor your assert statements will be ignored when your code runs. You need to enable assertions by passing one of these 2 command parameters
-enableassertions when you run you code. In C compilers assertions are not disabled by default but you can disable them by defining the
#define NDEBUG preprocessor directive
Enable assertion when running Java code:
java -ea MyClass
There are other ways to run your code with assertions, checkout the compiler documentation for your language. 😎👊
Photo by Christina Morillo from Pexels