「アサート」と「例外のスロー」の適切な使い方は何ですか?各シナリオはいつ適切ですか?アサートの適切な使用
シナリオ1
CODE
public Context(Algorythm algo) {
if (algo == null) {
throw new IllegalArgumentException("Failed to initialize Context");
}
this.algo = algo;
}
TEST
public void testContext_null() {
try {
context = new Context(null);
fail();
} catch (IllegalArgumentException e) {
assertNotNull(e);
}
}
シナリオ2
CODE
public Context(Algorythm algo) {
assert (algo != null);
this.algo = algo;
}
TEST
public void testContext_null() {
try {
context = new Context(null);
fail();
} catch (AssertionFailedError e) {
assertNotNull(e);
}
}
null例外をキャッチすることはできません。 assertNotNull(e)は真でなければなりません。 –
JUnit 4を使用していますか?もしあなたがそうであれば、テストメソッドで 'try' /' catch'の代わりに '@Test(expected = IllegalArgumentException.class)'アノテーションを使用してください。 – Asaph
そして、fail();またはテストが間違った理由で合格する可能性があります。 –