Changing To A More Focused Approach

I remember when I first really understood mock objects.  I was working as a developer at Progressive Insurance and all of a sudden it hit me that I could test a method without having to test the objects it called in its work.  This seems like an obvious statement, but it takes a little time to sink in to a brain such as mine.  Once I got my head wrapped around the mocked object concept I was the proverbial hammer lover looking for nails to pound.  What this led to were long, serpentine, and very brittle tests.  These tests looked like a negative of the method they were testing, every nook and cranny of the method behavior was brought out, in each test.  I was happy since I was able to mock like there was no tomorrow, but something was not right.

Take the example method below.

Example Method To Test
Example Method To Test

What I have traditionally done is written a few tests that have names like ‘ProcessOrdersTest’ and run down one full logical path through the entire method.  It might have looked something like the below:

Long Brittle Test
Long Brittle Test

The problem with the above is that if anything changes in the method the test breaks.  This is good, since I want the test to break, but I don’t know what caused the test to break, since the test is testing so many things.  Also, if I have two or three methods like the above to test all code paths then one change can break all the tests.  I’ll have perhaps three broken tests without any idea what is breaking them.

What I’ve started to do to mitigate this is to write tests that test one particular thing in a method and ignore everything else.  Instead of testing a whole code path what I’ve started doing is making sure my test name states one condition to test, and then I try and test that one condition and relying on as little else in the method staying the same.  What that leads to is something like the below, and it seems to be working much better.  When a test breaks I have more of an idea as to what has gone wrong, and when I purposefully change things I have fewer tests to update.

ShortTest
Short One Condition Test

Leave a Reply

Your email address will not be published. Required fields are marked *