且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

您可以将自定义消息添加到AssertJ assertThat吗?

更新时间:2022-11-18 20:15:28

以经典方式,发布问题后,我发现了自己想要的片刻.希望这将使下一个人更容易找到,而不必首先知道它的名字.神奇的方法是名称上被骗人的可描述的,而不是基本的Assert接口.

And in classic fashion, I found what I was looking for moments after posting the question. Hopefully this will make it easier for the next person to find without first having to know what it's called. The magic method is the deceptively short-named as, which is part of another interface that AbstractAssert implements: Descriptable, not the base Assert interface.

public S as(String description, Object... args)

设置支持String.format(String, Object...)语法的对象的说明.
例子:

Sets the description of this object supporting String.format(String, Object...) syntax.
Example :

try {
  // set a bad age to Mr Frodo which is really 33 years old.
  frodo.setAge(50);
  // you can specify a test description with as() method or describedAs(), it supports String format args
  assertThat(frodo.getAge()).as("check %s's age", frodo.getName()).isEqualTo(33);
} catch (AssertionError e) {
  assertThat(e).hasMessage("[check Frodo's age] expected:<[33]> but was:<[50]>");
}

如果断言失败,则捕获在模块hasMessage中的带引号的字符串将出现在单元测试输出日志中.

Where that quoted string in the catch block hasMessage is what appears in your unit test output log if the assertion fails.

我通过注意到问题中链接的自定义断言页面. JavaDoc 指出它已受到保护,因此调用者无法使用它来设置自定义消息.但是,它确实提到了as助手:

I found this by noticing the failWithMessage helper in the custom assert page linked in the question. The JavaDoc for that method points out that it is protected, so it can't be used by callers to set a custom message. It does however mention the as helper:

此外,此方法支持使用as(String, Object...)设置的任何描述或用户使用overridingErrorMessage(String, Object...)定义的覆盖错误消息.

Moreover, this method honors any description set with as(String, Object...) or overridden error message defined by the user with overridingErrorMessage(String, Object...).

...和

... and the overridingErrorMessage helper, which completely replaces the standard AssertJ expected: ... but was:... message with the new string provided.

在功能突出显示页面之前,AssertJ主页没有提到任何一个助手,该页面在

The AssertJ homepage doesn't mention either helper until the features highlights page, which shows examples of the as helper in the Soft Assertions section, but doesn't directly describe what it does.