Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain multiple assertThat statement in AssertJ

Tags:

assertj

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()
});
like image 270
cdxf Avatar asked Jul 31 '18 04:07

cdxf


People also ask

Is AssertJ better than JUnit?

First of all, JUnit is an automated test framework that is built in Java, whereas AssertJ is an opensource library used for writing fluent and rich assertions in Java tests. It's true that you can write assertions just using JUnit, but if you ever have an extra half an hour for studying AssertJ, be sure to go for it.

What is AssertJ in Java?

AssertJ core is a Java library that provides a fluent interface for writing assertions. Its main goal is to improve test code readability and make maintenance of tests easier. AssertJ core provides assertions for JDK standard types and can be used with JUnit, TestNG or any other test framework.


2 Answers

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.

like image 95
Joel Costigliola Avatar answered Sep 25 '22 20:09

Joel Costigliola


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.

like image 31
Tomáš Záluský Avatar answered Sep 24 '22 20:09

Tomáš Záluský