Unit testing triumphs - Verifying an experimental bug fix

Two ways I use unit tests while fixing bugs

Background

My previous post covers a bug that I recently fixed as part of a .NET upgrade. This post covers the role that unit testing played in that bug fix. This post can be understood without having read my previous one, but it is linked here for those who are interested:

Testing when experimenting

The crux of the bug fix was that I needed to rewrite some C# reflection logic. This is code that can be difficult to reason about, and I'm not very familiar with all of its nuances. I needed to quickly experiment with different approaches, and be able to make tweaks in response to errors.

Unit testing is perfect for this. Without unit tests, I would have had to write my code, then build & launch my site, wait for my local server to be ready to handle a request, then make a request which would trigger my code. I could then have read any errors in my browser's network tab. However, with a single unit test I could quickly check whether or not my latest code was working. In addition, I could see any errors without leaving my IDE.

Testing when refactoring

The first solution I found was one that I wasn't happy with. It fixed the bug, but had the same fundamental problem as the original code (which was that a future change to .NET could potentially break it). I committed the fix (always commit your code when your tests pass!) but refactored the code to find a better solution. Again, the unit test was invaluable for checking that I hadn't reintroduced the original bug (or a different one!)