Brief introduction
Assertions are using Java in the assert
statement to achieve. When performing assertion, it is considered to be correct. If it fails, JVM will throw a called AssertionError
wrong. It is mainly used for testing purposes during development.
assert
Statement is used in conjunction with Boolean expressions can be written in two different ways:
assert expression;
assert expression1 : expression2;
复制代码
Examples
public class AssertTest {
public static void main(String[] args) {
int value = 15;
assert value >= 20 : " Underweight";
System.out.println("value is " + value);
}
}
复制代码
Output:
value is 15
复制代码
We can see assert
the statement did not work, because when the Java program execution is not started by default assertion checking that all assert statements are ignored.
If you want to turn assertion checking, you need to use -enableassertions
or -ea
JVM parameters to open; if you want to manually ignore the assertion checking, you can use -disableassertions
or -da
JVM parameters to ignore the assertion statement.
Execute the command java -ea AssertTest
output after opening assertion:
Exception in thread "main" java.lang.AssertionError: Underweight
at AssertTest.main(AssertTest.java:11)
复制代码
Using the first syntax error message prompted to write:
public class AssertTest {
public static void main(String[] args) {
int value = 15;
assert value >= 20;
System.out.println("value is " + value);
}
}
复制代码
Output:
Exception in thread "main" java.lang.AssertionError
at AssertTest.main(AssertTest.java:11)
复制代码
Why assertion
- Ensure that the code does not seem to actually reach the unreachable
- Ensure the correct assumption when
- To ensure that
switch case
thedefault
branch can not reach - Check the status of objects
- Began to test the method of
- After testing method call
Precautions
Assertion mainly used when the checking logic impossible. For example, they can be used to check the code of the desired operating state or the state before the start of the code after the end of the run. And general exception / error handling different assertions usually disabled at runtime.
Where the use of assertions
- Parameter private methods. Private parameters provided only by the code developers, developers may want to check their assumptions about the parameters
- Branch conditions, for example,
switch
the statement - Conditions at the beginning of the method
Where not to use assertions
- Assertion should not be used to replace the error / exception messages
- Assertions do not apply to
public
the parameters of the process, as they may be provided by the user - Assertion should not be used on the command line parameter
summary
- Assertion is a debug mode, an assertion failure will throw
AssertionError
only in the development and testing phase enable assertions - Recoverable errors assertion can not be used, but should throw an exception
- JAVA asserts rarely used, a better approach is to write unit tests
references: