by Sophie Engle on Aug 2013
Assertions are another tool you can use to help debug and test your Java code. However, assertions are not enabled by default in Eclipse. This guide will show you how to enable assertions for a specific Java project, or by default in Eclipse for all Java projects.
In Eclipse, select "Run » Run Configurations..." from the menu bar. This will open up a dialog window. If you do not already have a run configuration for the current file, go ahead and create one. Otherwise, select the "Arguments" tab and enter -ea
in the "VM Arguments" text box as follows:
When you run this file, Eclipse should automatically use the run configuration you setup and enable assertions. A simple way to test if assertions are enabled is to put an assert false;
statement in your main
method. You should see an AssertionError
. If so, you can remove that line from your code. Otherwise, examine your run configuration again.
If you always want assertions enabled for any Java project you run in Eclipse, you have to change the settings for your installed JREs. Go to the Eclipse Preferences window (either "Window » Preferences" or "Eclipse » Preferences" from the menu bar). Open the "Java" submenu, and select "Installed JREs". You should see something similar to:
Select the JREs you have installed and click the "Edit" button. Here, you need to add -ea
to the default VM arguments as follows:
Click "Finish" and test it out. For example, add an assert false;
statement in code that does not have the -ea
flag turned on in the run configuration. You should still see the AssertionError
output to the console.