February 2020 Archives

To Hardcode, or Not to Hardcode: That Is the (Unit) Test-ion

In my last blog post, there was a bit of a discussion in the comments about whether data in unit tests should be hardcoded or not.  Tom Metro scored the last point with this comment:

We always coach developers to use hard coded test data to the extent practical. When writing tests you have to unlearn a lot of DRY principles. We tolerate a lot more repetition, and factor it out sparingly.

and then I said that this really required a longer discussion than blog post comments would allow.  This, then, is that longer discussion.

So, first of all, let me agree whole-heartedly with Tom’s final statement there: “We tolerate a lot more repetition, and factor it out sparingly.” Absolutely good advice.  The only problem is that, as I noted previously on my Other Blog, we humans have a tendency to want to simplify things in general, and rules and “best practices” in particular.  I don’t think that Tom was saying “always hardcode everything in your unit tests!” ... but I think some people will read it that way nonetheless.  I would like to make the argument that this is a more nuanced topic, and hopefully present some reasons why you want to consider this question very carefully.1

About Buddy Burden

user-pic 14 years in California, 25 years in Perl, 34 years in computers, 55 years in bare feet.