如何在 AssertJ 中链接多个 assertThat 语句

How to chain multiple assertThat statement in AssertJ

这是一个例子:

assertThat(commentById.getId()).isNotNull();
assertThat(commentById.getContent()).isNotBlank();
assertThat(commentById.getAuthor()).isNotNull();
assertThat(commentById.getAuthor().getUsername()).isNotBlank();
assertThat(commentById.getAuthor().getAvatar()).isNotBlank();
assertThat(commentById.getAuthor().getId()).isNotNull();

是否可以将其链接成一个 assertThat 语句


对于不清楚的问题,我们深表歉意。我的意思是,是否有一些流畅的方法调用可以将多个 assertThat 语句链接在一起。这是我能想到的一个例子:

assertThat(commentById)
.isNotNull()
.and(Comment::getID).isNotNull()
.and(Comment::getContent).isNotBlank()
.and(Comment::getAuthor).is(author->{
         author.isNotNull()
        .and(User::getID).isNotNull()
        .and(User::getAvatar).isNotBlank()
        .and(User::getUsername).isNotBlank()
});

目前这是不可能的,可以使用 extracting 但这意味着从当前实际导航到提取的实际无法返回到原始实际。

您可以利用satisfies方法:

assertThat(commentById.getId()).isNotNull();
assertThat(commentById.getContent()).isNotBlank();
assertThat(commentById.getAuthor()).isNotNull().satisfies(author -> {
    assertThat(author.getUsername()).isNotBlank();
    assertThat(author.getAvatar()).isNotBlank();
    assertThat(author.getId()).isNotNull();
});

这有助于在测试嵌套结构时消除代码的重复部分。

如果您希望 commentById 对象本身通过“单行”进行测试,理论上可以对其应用相同的方法 (assertThat(commentById).satisfies(c -> {assertThat(c.getId()).isNotNull(); ...})),但我仅在此说明从字面上回答你的问题,实际上我没有看到这样的表达有任何好处。