Unit testing: why is the expected argument always first in equality tests?

It seems that most early frameworks used expected before actual (for some unknown reason though, dice roll perhaps?). Yet with programming languages development, and increased fluency of the code, that order got reversed. Most fluent interfaces usually try to mimic natural language and unit testing frameworks are no different.

In the assertion, we want to assure that some object matches some conditions. This is the natural language form, as if you were to explain your test code you’d probably say

“In this test, I make sure that computed value is equal to 5”

instead of

“In this test, I make sure that 5 is equal to computed value”.

Difference may not be huge, but let’s push it further. Consider this:

Assert.That(Roses, Are(Red));

Sounds about right. Now:

Assert.That(Red, Are(Roses));

Hm..? You probably wouldn’t be too surprised if somebody told you that roses are red. Other way around, red are roses, raises suspicious questions. Yoda, anybody?

That doesn't sound natural at all

Yoda’s making an important point – reversed order forces you to think.

It gets even more unnatural when your assertions are more complex:

Assert.That(Forest, Has.MoreThan(15, Trees));

How would you reverse that one? More than 15 trees are being had by forest?

This claim (fluency as a driving factor for modification) is somehow reflected in the change that NUnit has gone through – originally (Assert.AreEqual) it used expected before actual (old style). Fluent extensions (or to use NUnit’s terminology, constraint basedAssert.That) reversed that order.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)