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()
});
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With