Eclipse: 启用断言

我正在运行 Eclipse Galileo。如何在 Eclipse 中启用断言?

正如其他网站所建议的那样,我尝试添加参数: -ea。我还尝试将编译器遵从级别更改为 1.4。这两个建议都不管用。

78894 次浏览
  1. Go to the menu Run, and then to the menu item Run Configurations.

enter image description here

  1. In the left panel, go to Java Application, and then go to Assertions.

  2. In the right panel, choose the tab Arguments.

  3. Under the field for VM arguments, type -ea to enable assertions.

enter image description here

  1. Click on the Apply and then Run button.

To globally set it as the default for everything:

  1. Go to menu Window (if you are on Windows), or go to menu Eclipse (if you are on Mac). For Linux it might be something similar.

  2. Go to Preferences.

  3. Choose Java, and then Installed JREs from the left panel.

  4. Select your JRE, and then click the Edit... button in the right panel.

  5. In the Default VM arguments field, add -ea.

You want to enable assertions for an application you're running from Eclipse? I usually just add -ea to the command line parameters in the "Run As" profile.

If you want to solve this issue globally for all JUnit tests then go to Preferences > Java > JUnit and at the top click the checkbox for "Add 'ea' to VM arguments when creating new JUnit launch configuration" Now Eclipse won't bug you for every new test you want to run. For existing tests you have to remove their's run configurations in Run Configuration > JUnit.

On maven projects you can run main method with auto-magic classpath by:

bash> export MAVEN_OPTS="-ea" && mvn exec:java -Dexec.mainClass="com.your.class.with.main"
cmd> set MAVEN_OPTS="-ea" && mvn exec:java -Dexec.mainClass="com.your.class.with.main"

In linux/eclipse you can add terminal window with bash for more convenient use.

To do this globally for all Java runs, edit the Installed JREs properties.

For example: Windows -> Preferences -> highlight the default JRE -> click Edit... -> In the Default VM arguments input box, enter -ea -> click the finish button.

This worked on Eclipse Kepler SR2.