http://qs1969.pair.com?node_id=356122

Most of the literature on unit testing focuses on testing code. But if you read around the edges you'll find some other uses for unit tests. One use that I've become rather fond of is in writing "tripwire" tests, which serve as an advance warning that some assumption has changed, or that some otherwise unwritten constraint has been violated.

Here's an example from some work that blakem and I did recently. We'd just done a refactoring that involved adding a requirement that each subclass of a factory class provide a class method that returned a unique product code. The question we then asked ourselves was "How can we add a test that would fail if someone violates this requirement in the future?" The answer was to write a tripwire test. The test looked something like this:

# All subclasses return unique product names my @classes = Factory->all_product_classes(); ok( scalar @classes, scalar keys %{{map { $_->product_name() => 1 } @classes}} );

Now, if some later work on the code base involves a new subclass in the factory class hierarchy, and someone forgets to override the product_name method, or overrides it and returns a product name that is used elsewhere in the hierarchy, we have a unit test to catch the problem before it sneaks in to production. The test will fail, someone will look at the test, and they'll be reminded (or informed) of the uniqueness constraint in a way that they might otherwise miss if we'd relied on comments in the superclass or (ugh) external written documentation.

Tripwire tests can be a great way to document constraints and future-proof your code base.

Updated (again) to fix a, uh, syntax error from transcription. Oops. :(