问题
Why doesn't my assert statement yield any result? I think the first assert statement should fail, but I don't see anything being displayed on Eclipse.
I'm using Eclipse to run this program.
package java.first;
public class test {
public static void main(String[] args) throws Exception {
String s = "test1";
assert (s == "test");
s = "test";
assert (s == "test");
}
}
回答1:
You need to set the -ea
(Enable Assertions) in your JVM options.
Unrelated, but you almost always want string1.equals(string2)
rather than ==
.
回答2:
You have to enable assertions with the -ea
argument (short for -enableassertions
).
In Eclipse:
- Right-click on the project, then "Run As" → "Run Configurations..."
- Select the "Arguments" tab
- Put
-ea
in the "VM arguments" field. - Select "Apply"
Now, running should cause an AssertionError
.
回答3:
By default, Java disables assertions. They must be enabled for them to work, with the -ea option when running your program.
回答4:
You need to turn assertion checking on at runtime. The Oracle documentation for Java states:
To enable assertions at various granularities, use the -enableassertions, or -ea, switch. To disable assertions at various granularities, use the -disableassertions, or -da, switch.
Full details on the Oracle website at http://docs.oracle.com/javase/1.4.2/docs/guide/lang/assert.html#enable-disable
To change the run-time options for programs run inside Eclipse you will need to modify the parameters Eclipse runs your program with. How to do this will vary depending on your version of Eclipse, but here's how it works in Eclipse Europa...
- Open the Run Dialog (this should be an option under the "Run" menu).
- Click on the tab, "(x)= Arguments."
- In the field for "VM arguments," enter -ea to enable assertions.
- Click on the "Apply" button.
Answer "borrowed" from http://www.coderanch.com/t/416987/vc/enable-Assertions-eclipse
回答5:
You have to enable it by using -ea argument.
来源:https://stackoverflow.com/questions/17930266/java-assertion-error-does-not-throw-error