Unit Testing: Why I prefer assertThat()

Consider:

[Test]
public function null_criteria_should_not_match():void
{
  assertFalse("passing null should return false", instance.match(null));
}

When reading the test above I have to do a lot of scanning.

First I see the string message in the middle because it jumps out. The message is redundant as it’s included in the test name. If I change the test I’ll need to change both the method name and the string description. I can see that the string message would be useful for a test with multiple asserts, but that’s generally not a good idea.

After reading the string I look to the right to see what is being tested and mentally try to evaluate it.

Then I look to the left to see what the expectation is, possibly flipping the evaluation I just did to match the expectation.

It’s disconnected, and it’s hard work.

Consider this instead:

[Test]
public function null_criteria_should_not_match():void
{
  assertThat(matcher.match(null), isFalse());
}

Now I just read normally: top-to-bottom, left-to-right. I read the test name, look at what is being evaluated and see what is expected.

Posted in Banter, Code | Tagged , , , | 1 Comment
  • Sandro Manke

    readability owns. i prefer this way too actually