Not only are unit tests great for securing the behaviour of your code but they also serve as form of living documentation and one area where I find this especially true is when covering regular expressions with your unit tests.
Imagine you get a pull request from one of your coworkers which contains this code snippet:
What does this snippet do? We can guess based on the name of the method that it extracts some sort of initials based on a name, right?
Now I don’t speak fluent Regex, so I’m not sure what this does just by looking at it. I have an idea, but I’m not sure.
For example, what would happen if the name I’m passing in has a middle name? Or two last names? And what will happen if I just pass in a first name? Or null? Or empty?
No more guessing
Imagine that your coworkers had also included this test in his or her pull request:
That’s more like it, now there is not a doubt in my mind what this method does. See not only will this test help me review this pull request better but also everyone who reviews this pull request will get a full understanding of how this method works and they can start using it in their own implementations without worrying about potential edge cases.
This is obviously true for all unit tests but I find it especially important for regular expression tests since they are not always in a human readable format.
Cheers friends! ❤️