为什么断言在不应该通过所有测试案例时却通过了呢

huangapple go评论71阅读模式
英文:

Why is assert passing all test cases when it shouldn't

问题

    public class Main {
        public static void main(String args[]) {
            sumArray(8);
        }
    
        public static int sumArray(int nums){
           assert nums == 5;
           return nums;
        }
    }

我只是在想当我传递一个不等于5的数字时为什么编译器不会抛出任何错误因为我断言`nums`等于5呢
英文:
public class Main {
    public static void main(String args[]) {
        sumArray(8);
    }

    public static int sumArray(int nums){
       assert nums == 5;
       return nums;
    }
}

I was just wondering, when I pass a number that is not equal to 5, why doesn't the compiler throw any errors, since I am asserting that nums is equal to 5?

答案1

得分: 1

如果程序在启用断言的情况下运行,则会在运行时检查条件。如果条件为false,则Java运行时系统会抛出一个AssertionError

为了保持向后兼容性,默认情况下JVM会禁用断言验证。必须通过使用-enableassertions命令行参数或其简写-ea显式启用断言。

参考链接:https://www.baeldung.com/java-assert

英文:

If the program is running with assertions enabled, then the condition is checked at runtime. If the condition is false, the Java runtime system throws an AssertionError.

For backward compatibility, the JVM disables assertion validation by default. They must be explicitly enabled using either the -enableassertions command line argument, or its shorthand -ea

Reference: https://www.baeldung.com/java-assert

huangapple
  • 本文由 发表于 2020年9月28日 12:34:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/64096002.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定