LoginSignup
3
1

More than 1 year has passed since last update.

javaでコーディング中にちょっとした確認したいときにifの代わりにassertを使う

Posted at

例えば以下のようなケースです。
入門書とかにはしっかり書いてありますが、意外と忘れてたり使ってなかったりします

Main.java
public static void main(String[] args) throws Exception {
    // 構文 assert テスト対象 : 失敗したときのメッセージ
        assert sum(2 ,4) == 6 : "method \"sum\" result is Unexpected. arg[0]: 2, arg[1]: 4";
        assert sum(2 ,5) == 6 : "method \"sum\" result is Unexpected. arg[0]: 2, arg[1]: 5";
}

static int sum(int a, int b){
    return a + b;
}

assertが成功した場合何も起こりません。失敗すると以下のように教えてくれます。

Exception in thread "main" java.lang.AssertionError: method "sum" result is Unexpected. arg[0]: 2, arg[1]: 5
    at Main.main(Main.java:8)

アサーションを有効にするには、実行時のオプションに-enableassertionsを付けてやる必要があります。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1