13

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()
});
cdxf
  • 5,501
  • 11
  • 50
  • 65

2 Answers2

17

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.

Tomáš Záluský
  • 10,735
  • 2
  • 36
  • 64
9

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.

Joel Costigliola
  • 6,308
  • 27
  • 35