Saturday, October 08, 2022
What is a “unit test?”
Despite the emphasis on testing at The Enterprise, no one there was able to answer the simple question I would often ask, “what is a unit test?”
On thinking about it since I left, I don't think there's an answer to that question. I'm thinking it really depends upon the language being used, and it's a similar concept to Design Patterns, a collection of patterns seen in Smalltalk development and later forced onto other languages, applicability be damned.
Since most of the coding I do is in C, a “unit” would most likely be a function, or maybe a collection of functions known colloquially as “a library.” The various components I worked on, like “Project: Lumbergh” or “Project: Sippy-Cup” aren't libraries, and most functions in those projects are single use that exist just for organizational sake, so of course the “unit” ended up being the entire program.
But I'm also looking at some of my own projects,
like mod_blog
.
There's a fair number of stand-alone functions in here I could possibly “unit test” if I were inclined.
The first one is this function (found here):
int max_monthday(int year,int month) { static int const days[] = { 31,0,31,30,31,30,31,31,30,31,30,31 } ; assert(year > 1969); assert(month > 0); assert(month < 13); if (month == 2) { /*---------------------------------------------------------------------- ; in case you didn't know, leap years are those years that are divisible ; by 4, except if it's divisible by 100, then it's not, unless it's ; divisible by 400, then it is. 1800 and 1900 were NOT leap years, but ; 2000 is. ;----------------------------------------------------------------------*/ if ((year % 400) == 0) return 29; if ((year % 100) == 0) return 28; if ((year % 4) == 0) return 29; return 28; } else return days[month - 1]; }
I'm sorry, there's no way I'm going to even waste time writing unit tests for a function this simple. I didn't bother when I first wrote it in Debtember of 1999, and there's no point in writing one now. Even if the leap year rules change in 1,980 years, I probably still won't write unit tests for this function (probably because I'll be dead by then, but that's besides the point).
But that's not to say there aren't other functions that couldn't be “unit tested.” The next one I have in mind is simple, but I would love to see a unit test purist tell me how they would write a unit test for it.