Next page | Contents page |

Assertions

For testing, Java (since 1.4) has keyword assert, used in 2 ways:

	assert condition;
	assert condition : expression;

Both throw a java.lang.AssertionError if the condition is false. The expression is passed into the AssertionError constructor so it can form a message string.

By default assertions are disabled at run time - the class loader strips them out of the class completely, so there is no performance hit. Enable them on the command line:

	java –enableassertions MyApp

or more selectively:

	java –ea:X –ea:net.grelf.course –ea MyApp

switches on assertions for class X, package net.grelf.course and its subpackages, and the default package.

For unit testing most people use JUnit, from www.junit.org, which we will cover later. This was already well established before Java introduced assertions.

Next page | Contents page |