Chance Favors the Prepared Unit Test
Sometimes you just get lucky.
I was at my desk last Sunday working on some items for the upcoming release of Storyist, when my unit tests (I am religious about unit tests) started complaining. Since the problem was in an area of code that I hadn’t touched for quite a while, I was curious to see what broke.
The assertion was in some date code. Date code?
Drumming fingers on the keyboard. “Something about today… What is it? Aha! Spring forward, fall back!”
Sunday was the first day of standard time.
A quick debugging session identified the culprit: NSTimeZone. The offending line of code was
int seconds = [[date timeZone] secondsFromGMT];
Now, the intent of the code was to do some arithmetic with “date”. However, the documentation for secondsFromGMT reads
Returns the current difference in seconds between the receiver and Greenwich Mean Time.
The bug lies in the fact that the method returns “the current difference,” not (as is obvious in retrospect) the seconds from GMT of the date of interest. The correct code is
int seconds = [[date timeZone] secondsFromGMTForDate:date];
I would never have found this bug without unit tests. The way the code is structured, the bug only occurs two days a year. And any bug report not investigated on these two days would have resulted in the bug being closed with the dreaded “works for me” status.
So some times you just get lucky–if you are prepared for it.







