JUnit is a very popular test framework, which includes a package commonly referred to as assertions. Assertions allow us to inspect variables in our test methods, to assert they either have been instantiated or have certain values.
This short blog post will discuss the AssertJ library and how it can help a developer to more intuitively assert their test functionality.
When building your test methods, you can assert, for instance, that an array has certain values. Source code structures below were taken from Joel Costigliola’s site.
TolkienCharacter frodo = new TolkienCharacter("Frodo"); TolkienCharacter sam = new TolkienCharacter("Sam"); TolkienCharacter pippin = new TolkienCharacter("Pippin"); TolkienCharacter boromir = new TolkienCharacter("Boromir"); Stream<TolkienCharacter> fellowshipOfTheRing = Stream.of( frodo, sam, pippin, boromir); //Check whether an array value exists boolean containsFrodo = fellowshipOfTheRing.allMatch( character -> character.getName().contains("Frodo")); assertTrue(containsFrodo);
Although this example uses Java 8, with the comfortable Stream package, you have to build the logic to check for the assertion of a specific value. You may ask, “So what?” And it is true. Developers have been designing tests like this for years. Then AspectJ comes along.
Taken from their Web site:
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.
Using the same example from above, and adding to it, we can make more intuitive assertions, as we string a series of assertions with one stream:
// TolkienCharacter objects created ... // Added to a stream container Stream<TolkienCharacter> fellowshipOfTheRing = Stream.of( frodo, sam, pippin, boromir, legolas, gandalf, gimli); // all List assertion are available assertThat(fellowshipOfTheRing).contains(frodo) .doesNotContain(sauron); .extracting(TolkienCharacter::getRace) .contains(HOBBIT, ELF) .doesNotContain(ORC); // WARNING : this assertion is not possible as fellowshipOfTheRing was // already consumed. assertThat(fellowshipOfTheRing).contains(frodo);
Note that everything starts with the assertThat method, followed by whatever series of checks/assertions you need to make on the corresponding object/variable.
We can quickly see that asserting test variables can become more intuitive and easier to maintain with AssertJ’s library. I encourage you to review your new JUnit test classes to see how AssertJ an help improve your code readability and testing.