Assertions
An assertion is a simple pass/fail test of some condition, performed while your application is running. Assertions can be used to “sanity check” your code anywhere you believe certain conditions are guaranteed by correct program behavior. Assertions are distinct from other kinds of tests because they check conditions that should never be violated at a logical level: if the assertion fails, the application is to be considered broken and generally halts with an appropriate error message. Assertions are supported directly by the Java language and they can be turned on or off at runtime to remove any performance penalty of including them in your code.
Using assertions to test for the correct behavior of your application is a simple but powerful technique for ensuring software quality. It fills a gap between those aspects of software that can be checked automatically by the compiler and those more generally checked by “unit tests” and human testing. Assertions test assumptions about program behavior and make them guarantees (at least while they are activated).
If you have programmed before, you may have written something like the following:
if(!condition)thrownewAssertionError("fatal error: 42");
An assertion in Java is equivalent to this example, but is performed
with the assert language keyword.
It takes a Boolean condition and an optional expression value. If the
assertion fails, an AssertionError is thrown,
which usually causes Java to bail out of the application.