Wednesday, June 16, 2010

This is Why We Write Unit Tests

[StringLengthValidator(0, 29,
MessageTemplate = "Material cannot exceed nineteen (19) characters.",
Tag = "Material")]
public string Material { get; set; }

This is a snippet of code that makes use of the Validation Application Block’s attribute validation. Can you see where the problem is? Which rule is correct? 19 or 29?

Unit tests for both string length boundary conditions and the return message would have caught this bug. Is it a small bug? Yes. Does it matter that it’s a small bug? No.

This code will be rejected by QA and now it must be fixed, re-deployed, and regression tested. If QA does let it pass, then you have to contend with the client rejecting it. This is a much bigger loss because on top of the QA process, you have UAT and re-deployment to production and all of the people and processes involved with that. Unit testing (and specifically TDD) helps us prevent bugs from finding their way into our codebase.

Think of the time, effort, energy, manpower, and money that would have been saved by spending an extra few minutes to write three or four units tests.

1 comment:

  1. MessageTemplate = "Material cannot exceed {5} characters."

    Three or four tests would have ensure that *this* message and limit is correct. But if you want to cover all messages, you need to multiply that by the number of properties - or maybe validators - in the entire codebase. Not saying you shouldn't do it, just that it might be more that the insignificant time investment you make it out to be.

    And yeah, I'm probabably the person that didn't write that test :-)

    And I hate that weird practice - maybe from the legal profession? - of writing the number twice. As if anyone fluent enough to use the interface at all would be confused by "19" or "nineteen," and need to see it both ways. Just a pet peeve.