How to chain multiple assertThat statement in AssertJ
Asked Answered
S

3

16

Here is an example:

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();

Is there anyway to chain this into a single assertThat statement


Sorry for the unclear question. I mean, is there some fluent method calls to chain multiple assertThat statement together. Here is an example I can think of:

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()
});
Stablish answered 31/7, 2018 at 4:45 Comment(3)
How would "chaining" these statements help you?Gabe
Please provide a sample of what you think it should do.Gabe
sorry for the unclear question. I've updated my question.Stablish
O
10

This is not possible at the moment, what is possible is to use extracting but that implies navigating from the current actual to the extracted one without being able to go back to the original actual.

Ostensible answered 17/8, 2018 at 18:4 Comment(0)
T
20

You can utilize satisfies method:

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();
});

This helps to eliminate repeating parts of code while testing nested structures.

If you want the commentById object itself to be tested by "one-liner", it is theoretically possible to apply same approach onto it (assertThat(commentById).satisfies(c -> {assertThat(c.getId()).isNotNull(); ...})), however I state it here only to literally answer your question, actually I don't see any benefit of such expression.

Topmost answered 22/7, 2021 at 9:11 Comment(1)
Thanks, didn't came across this, just now.Glossectomy
O
10

This is not possible at the moment, what is possible is to use extracting but that implies navigating from the current actual to the extracted one without being able to go back to the original actual.

Ostensible answered 17/8, 2018 at 18:4 Comment(0)
C
2

Try this

assertThat(myService.getById("sr2"))
    .returns("s2-new", from(MyClass::getField1))
    .returns("s2", from(MyClass::getField2))
    .returns(Boolean.TRUE, from(MyClass::getField));
Cassiterite answered 3/5 at 8:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.