AssertJ 断言原因消息
AssertJ assert on the cause message
有没有一种方法可以在再次使用 AssertJ 时抛出异常来检查原因中的消息是否等于某个字符串。
我目前正在做类似的事情:
assertThatThrownBy(() -> SUT.method())
.isExactlyInstanceOf(IllegalStateException.class)
.hasRootCauseExactlyInstanceOf(Exception.class);
并想添加一个断言来检查根本原因中的消息。
不完全是,目前您能做的最好的事情是使用 hasStackTraceContaining
,例如
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).hasCauseInstanceOf(Exception.class)
.hasStackTraceContaining("no way")
.hasStackTraceContaining("you shall not pass");
从 AssertJ 3.16 开始,有两个新选项可用:
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).getCause()
.hasMessage("you shall not pass");
Throwable rootCause = new RuntimeException("go back to the shadow!");
Throwable cause = new Exception("you shall not pass", rootCause);
Throwable runtime = new RuntimeException("no way", cause);
assertThat(runtime).getRootCause()
.hasMessage("go back to the shadow!");
从 AssertJ 3.14 开始,可以使用 extracting
和 InstanceOfAssertFactory
:
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).extracting(Throwable::getCause, as(THROWABLE))
.hasMessage("you shall not pass");
as()
是从 org.assertj.core.api.Assertions
静态导入的,THROWABLE
是从 org.assertj.core.api.InstanceOfAssertFactories
.
静态导入的
有没有一种方法可以在再次使用 AssertJ 时抛出异常来检查原因中的消息是否等于某个字符串。
我目前正在做类似的事情:
assertThatThrownBy(() -> SUT.method())
.isExactlyInstanceOf(IllegalStateException.class)
.hasRootCauseExactlyInstanceOf(Exception.class);
并想添加一个断言来检查根本原因中的消息。
不完全是,目前您能做的最好的事情是使用 hasStackTraceContaining
,例如
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).hasCauseInstanceOf(Exception.class)
.hasStackTraceContaining("no way")
.hasStackTraceContaining("you shall not pass");
从 AssertJ 3.16 开始,有两个新选项可用:
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).getCause()
.hasMessage("you shall not pass");
Throwable rootCause = new RuntimeException("go back to the shadow!");
Throwable cause = new Exception("you shall not pass", rootCause);
Throwable runtime = new RuntimeException("no way", cause);
assertThat(runtime).getRootCause()
.hasMessage("go back to the shadow!");
从 AssertJ 3.14 开始,可以使用 extracting
和 InstanceOfAssertFactory
:
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).extracting(Throwable::getCause, as(THROWABLE))
.hasMessage("you shall not pass");
as()
是从 org.assertj.core.api.Assertions
静态导入的,THROWABLE
是从 org.assertj.core.api.InstanceOfAssertFactories
.