Knot Always Write

I recently came across the following test code:

void someTest() {
   assertThat("").isEqualTo(service.getStatus());
   assertThat("").isEqualTo(service.getUser());
}

The linter was complaining that this should have been a chained assertion, rather than two separate assertions on the same value of "":

void someTest() {
   assertThat("")
     .isEqualTo(service.getStatus())
     .isEqualTo(service.getUser());
}

This is proof if you needed it that nothing amplifies stupidity more than a well-intentioned linter. The original author of the test had probably written this:

void someTest() {
   assertEquals(service.getStatus(), "");
   assertEquals(service.getUser(), "");
}

And then the intern came along with his JUnit assertions to assertJ tool and made it change to the second version. With the linter deciding that this was a test on the outcome of "".

Crazy times.

The root cause of this is the intensely non-intuitive syntax of JUnit’s native asserts. They assert expected = actual, which is backwards no matter which way you try to think of it. It’s because of this stubborn resistance to the logical reading order that people go to the more self-explanatory assertJ, and so they should!

However, assertJ has some much richer ways of expressing assertions than just plain equals. For example, I recently discovered their isZero assertion, which seems richer than isEqualTo(0) in subtle ways I can’t quite describe.

So, the correct version of the code above, should have been:

void someTest() {
   assertThat(service.getStatus()).isEmpty();
   assertThat(service.getUser()).isEmpty();
}

Which is semantically much closer to what the test was trying to prove.

Conclusion

Never take a linting remark at face value. Go back to the root cause of the issue and see if there’s a rethink which makes the linter’s point obsolete.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s