Tuesday, December 9, 2008

Visual Studio Unit Testing – Reducing Redundant Tests

When I first started unit testing, I tested as many methods as I could.  These included public and private ones.  A bit of searching on the web about public versus private method testing will yield mixed results.  I personally test both since I aim for at least 70% code coverage.  Visual Studio creates Accessor classes for private methods and properties for you so testing private methods is easy.

I used to write at least one test per method (some require more than one to test conditional code paths), but this can get redundant.  The steps I take to reduce redundancy today are as follows.  First, I turn on code coverage.  This will give a visual indicator of what has been covered in my classes. 

SetCodeCoverage

SetCodeCoverage2

When I run my tests, code that has been covered is in blue and the code that hasn’t been covered is in red.

bluered

I test my constructors first, then public methods, and finally private methods.  Doing it in this order gives me a better idea of what private methods need to be tested.  Most of the time public methods will call private methods so writing a single test will cover those methods as well.  I collapse whatever has been covered each time I create and run a test.  Doing my tests this way has greatly reduced the number of redundant tests written and has kept the same amount of code coverage.