Thursday 16 July 2020

AssertJ and how your IDE can help

So I am using AssertJ1 to verify results of my Unit Tests.

I also (after the advice of a colleague) installed a Plugin into my IntelliJ IDEA called Concise AssertJ Optimizing Nitpicker ​(Cajon)​2

So I needed to verify the equivalence of an object. I wanted to make sure it was the exact same object I was expecting.

In my naivite I tried something like this.

assertThat(getItems()).hasSize(1);
Optional<Item> first = CollectionUtilities.getFirst(getItems());
assertThat(first).isPresent();
assertThat(first.get() == originalitem).isTrue();

My IDE complained that "Moving binary expression out of assertThat() would be more meaningful".

I completely agreed with that.

assertThat(getItems()).hasSize(1);
Optional<Item> first = CollectionUtilities.getFirst(getItems());
assertThat(first).isPresent();
assertThat(first.get()).isSameAs(originalitem);

Then my IDE commplained that "Moving get() expression out of assertThat() would be more concise", which of course is obvious.

assertThat(getItems()).hasSize(1);
Optional<Item> first = CollectionUtilities.getFirst(getItems());
assertThat(first).isPresent();
assertThat(first).containsSame(originalitem);

Then, of course, Multiple assertThat() statements can be joined together

assertThat(getItems()).hasSize(1);
Optional<Item> first = CollectionUtilities.getFirst(getItems());
assertThat(first).isPresent().containsSame(originalitem);

Which means that Implicit isPresent() assertion is covered by containsSame()

assertThat(getItems()).hasSize(1);
Optional<Item> first = CollectionUtilities.getFirst(getItems());
assertThat(first).containsSame(originalitem);

And that's what I ended up with.

Truly, sometimes my IDE has some good ideas.

Alternative

Of course, there are easier methods, but I wanted to verify that it is the exact same instance.

Otherwise, I could have simply done something like:

assertThat(getItems()).containsExactly(originalitem);

Still not entirely sure that this is not better, despite not an exact match check.

References

[1] AssertJ
https://assertj.github.io/doc/
[2] Concise AssertJ Optimizing Nitpicker ​(Cajon)​
https://plugins.jetbrains.com/plugin/12195-concise-assertj-optimizing-nitpicker-cajon-/

No comments:

Post a Comment