Writing readable test with AssertJ
AssertJ is a library that provides "fluent assertions for java". The fluent interface of the assertions allows developers to write very readable tests. In this article I will try to show how this can be accomplished for your own domain objects.
Let's imagine there is some kind of Validator that returns a ValidationResult. The ValidationResult could look like that:
When testing the validator the ValidationResult will be checked according to the expectations of the test. One way to describe the assertions with AssertJ is the following.
If done like that, you do not really win something in comparison to other assertion libraries.
It is possible to have the assertion automatically generated. That would make the test code look like that.
The problem here is, that the readability can still be improved.
AssertJ lets you write your own Assert classes for your domain objects. That means all the methods can be named the way that really readable tests can be produced. The class ValidationResultAssert could look like that.
This leads to a assertion that can be read like a sentence, which makes it very easy to understand why the expectations in the test are the way they are. In addition to that a test like that also provides an explicit description of the dependencies within you domain model.
This is is a rather simple example, but as your code's complexity grows the readability of your tests gets more and more important.