Rule #1: don’t tell me the rule, state the principle behind it

Some days ago, one of my colleagues showed me an unit test, coded by someone else. It was something like

public void TestALotOfThings()
  var instance = new UnitUnderTest();


  var check = 
    instance =! null &&
    somefunc(instance.Property1) == expectedVal &&
    instance.Property3 == null &&
    instance.Property4 == expectedValue4 &&
    instance.Property5 == expectedValue5 &&
    instance.Property6 == expectedValue6 &&
    instance.Property7 / instance.Property8 
        == expectedValue;




Wat??“, I said?

Yes“, he said with a smile, “the fact is the boss gave this guy a rule: never, ever write more than one assert for each unit test. Apparently, that guy followed the rule, without understanding the principle behind it. That’s why one should never give rules, but just state principles. Rules should be a natural consequence.

How could I agree more? We Italians have a proverb:

Fatta la legge, trovato l’inganno

which could be translated as

No matter the law you will provide, I’ll find out a workaround.

The rule “One assert for unit test” should be the consequence of the principle “A unit tst should stress one single behavior, so that when it fails it can be used to exactly seek where the problem is” (as I stated in Unit tests lie, that’s why I love them).

But if you just follow the rule, without asking yourself “Why? Where does this rule come from?“, you may be tempted to use a dirt workaround, which invalidates the rule’s benefits themselves: paradoxically, the unit test above would have been much better with several asserts, so that a single bug would invalidate a single assert.

For a pure coincidence, just few days later I read the post So procedures are extremely important but … by Piergiorgio Grossi.

I think it’s about the same topic.

To me, a developer should have a book of laws, with this content:

Rule#1: there won't be any other rules beyond this one.




One thought on “Rule #1: don’t tell me the rule, state the principle behind it

Leave a Reply

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

You are commenting using your 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