Java assert assertion usage

Java assert assertion usage

Tips before viewing:

The IDEA version used in this article is ultimate 2019.1, and the JDK version is 1.8.0_141.

1 Introduction

When writing code, we always make some assumptions. Assertions are used to capture these assumptions in the code. Assertions can be regarded as an advanced form of exception handling. Assertions are expressed as Boolean expressions that the programmer believes to be true at a certain point in the program. You can enable and disable assertion verification at any time, so you can enable assertions during testing and disable assertions during deployment. Similarly, after the program is put into operation, the end user can re-enable assertions when they encounter problems.

2. Usage

The assert keyword quoted in JAVA SE 1.4 is turned off by default. If you want to enable assertion, you need to use the switch -enableassertions or -ea to enable it.

Two usages:

  1. assert <boolean expression>
    If <boolean expression> is true, the program executes normally.
    If <boolean expression> is false, a java.lang.AssertionError will be thrown and the program will be terminated.

  2. assert <boolean expression>: <error message>
    If <boolean expression> is true, the program executes normally.
    If <boolean expression> is false, java.lang.AssertionError is thrown, the output information is <error information>, and the program is terminated.

3. Examples

Test code Test.java

package testAssert;

public class Test {
    
    

    public static void main(String[] args) {
    
    

        assert true;
        System.out.println("assert true 断言通过");

        assert false : "assert false 断言失败";
        System.out.println("assert false 断言通过");
    }
}

When the -ea switch is not started, the result is that
Insert picture description here
if you want to enable assertions, you need to configure -ea or -enableassertions in VM options
Insert picture description here
Insert picture description here

After turning on the -ea switch, the running result is
Insert picture description here

4. Summary

  1. Assert is similar to junit, but its functionality is far inferior to junit. It is recommended that you avoid using assert as much as possible.

  2. The program that fails the assertion will exit. In the actual production environment, exception capture is usually used to solve the problem. If the assertion is used, the assertion failure means that the system hangs.

  3. When using assert to debug programs, the mainstream Java IDE tools now turn off the -ea switch by default, and need to turn on the -ea switch to use it. For Java web applications, it is necessary to change the configuration parameters of the web application, which is very inconvenient for the deployment of the program.

Guess you like

Origin blog.csdn.net/weixin_43611145/article/details/106998074