それを実行する方法の 1 つは次のとおりです。
@Test
public void foo() {
try {
// execute code that you expect not to throw Exceptions.
} catch(Exception e) {
fail("Should not have thrown any exception");
}
}
これをもっときれいに行う方法はありますか? (おそらく Junit を使用するのでしょうか@Rule
?)
ベストアンサー1
JUnit5 について(Jupiter) は、例外の有無をチェックする 3 つの関数を提供します。
●assertAll()
提供されたすべてがexecutables
例外をスローしないことを確認します。
●assertDoesNotThrow()
提供されたexecutable
/の実行がいかなる種類のsupplier
エラーも発生しないことをアサートします例外。
この機能は
、JUnit5.2.0 より(2018年4月29日)。
●assertThrows()
指定されたの実行により例外がexecutable
スローされexpectedType
、が返されることをアサートします。例外。
例
package test.mycompany.myapp.mymodule;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class MyClassTest {
@Test
void when_string_has_been_constructed_then_myFunction_does_not_throw() {
String myString = "this string has been constructed";
assertAll(() -> MyClass.myFunction(myString));
}
@Test
void when_string_has_been_constructed_then_myFunction_does_not_throw__junit_v520() {
String myString = "this string has been constructed";
assertDoesNotThrow(() -> MyClass.myFunction(myString));
}
@Test
void when_string_is_null_then_myFunction_throws_IllegalArgumentException() {
String myString = null;
assertThrows(
IllegalArgumentException.class,
() -> MyClass.myFunction(myString));
}
}