Skip to content
Advertisement

How to perform deeper matching of keys and values with assertj

Say I have a class like this:

JavaScript

And later, a Map

JavaScript

Using assertj, what is the best way to test that characterAges includes the “Frodo” character? For the age, I can do:

JavaScript

And I know I could do:

JavaScript

But then I lose my fluency. What I really want it something like this:

JavaScript

Or even better, so that I can make sure my key and value match:

JavaScript

Is something like this possible?

Advertisement

Answer

There is no easy solution for this. One way is to implement a custom Assertion for the character map. Here is a simple custom Assertion example for this problem:

JavaScript

In the test case:

JavaScript

Be aware that you have for every custom data structure to write your own assertion. For you Character class you can generate a assertion with the AssertJ assertions generator.


Update Java 8

With Java 8 can also the Lambda Expression used

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement