In this post we’re going to figure out how AssertJ can make our life easier if we need to validate complex objects in Java.
Let’s start with the simple object
Author that has only 2 fields
AssertJ maven dependency
Regular objects validation in Java with AssertJ
see AssertJ. Custom fail messages (assertion messages)
Validate objects with isEqualToComparingFieldByField. AssertJ
Even for simple objects like this we already have some benefits - less code.
Let’s see how failures look like if something is wrong with our object, for example
actualAuthor = new Author("Jane", "Doe");.
Very informative and readable, isn’t it?
Validate objects with isEqualToComparingFieldByFieldRecursively. AssertJ
In the real world we have to validate objects much more complex then the example above.
Let’s make it more complex
Our test looks like this
Let’s see how the failure would look like if something is wrong with actualBook, for example
actualBook = new Book("Book title", new Author("Jane", "Doe"), 2018, 300);
You have everything to quckly understand why it’s failing and what is wrong with the object that you validate.
Validate objects with isEqualToIgnoringGivenFields. AssertJ
What if we accept any author’s firstName but expect the exact lastName (in our case “Doe”)? In that case the test would look like this
Validate objects with isEqualToComparingOnlyGivenFields. AssertJ
There is another way to that with
Try it - you’ll love it.
You may also find these posts interesting: