Assertions


You have been using assert methods defined as part of the JUnit API. These assert methods, defined in junit.framework.Assert, throw an AssertionFailedError when appropriate.

Java supports a similar assertion feature that you can turn on or off using a VM flag. An assertion statement begins with the keyword assert. It is followed by a conditional; if the conditional fails, Java throws a RuntimeException of type AssertionError. You can optionally supply a message to store in the AssertionError by following the conditional with a colon and the String message. An example:

 assert name != null : "name is required"; 

Without the message:

 assert name != null; 

Assertions are disabled by default. When assertions are disabled, the VM ignores assert statements. This prevents assert statements from adversely affecting application performance. To turn assertions on:

 java -ea MainClass 

or, more explicitly:

 java -enableassertions MainClass 

Both of these statements will enable assertions for all your code but not for the Java library classes. You can turn assertions off using -da or -disableassertions. To turn assertions on or off for system classes, use -enablesystemassertions (or -esa) or -disablesystemassertions (or -dsa).

Java allows you to enable or disable assertions at a more granular level. You can turn assertions on or off for any individual class, any package and all its subpackages, or the default package.

For example, you might want to enable assertions for all but one class in a package:

 java -ea:sis.studentinfo... -da:sis.studentinfo.Session SisApplication 

The example shown will enable assertions for all classes in sis.studentinfo with the exception of Session. The ellipses means that Java will additionally enable assertions for any subpackages of sis.studentinfo, such as sis.studentinfo.ui. You represent the default package with just the ellipses.

Assertions are disabled/enabled in the order in which they appear on the java command line, from left to right.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net