Not to long ago I was writing a complex Regular Expression and ran into a rather difficult problem. This was an update to a regular expression in Drupal and needed to be validated before the bug fix could be committed. The problem was that I couldn’t find anyone who was comfortable working through the regex with me. This is where the required tests in Drupal saved the day. The tests provided feedback when things failed and eventually validated the expression when it was right so other developers didn’t need to. Let me walk through the process of how this worked.
A Black Box
The first thing I started with was a black box function for the unit tests to call what will eventually contain the regex. The unit tests don't care about the inner working of the function just the inputs and outputs.I wrote unit tests to pass in a known input and look for the expected output from the function. The unit tests are testing a unit of code, in this case a function, and don’t care about the inner workings of that code. They care if the inputs and outputs are as expected.
To make these tests more well rounded I wrote tests that would fail the regex but are very similar to ones that would pass. It’s important to test for false positives.