4.4. Code Coverage Is High

Code coverage should be 90% or better by line. Yes, that is a tall order. Frankly, it's hard. It can take a lot of careful planning and work to get your coverage that high. But it is absolutely worth it. If you strive for such a large percentage of code coverage, you will be constantly thinking about how to make your own code more testable. The more testable code you write, the easier it will get. Once you have gotten used to writing highly testable code and good tests that exercise it, you will be turning out much higher-quality code than you did before and spending less time dealing with defects.

Getting to 90% coverage will also teach you things about your code and your coding style that you didn't know before. If you are consistently having difficulty testing all of your error handling code for instance, maybe you should change the way you are dealing with errors, or how you deal with dependencies. You should be able to generate all the errors that you intend to handle with your test code. If you can't, maybe you shouldn't be catching those exceptions.

If you have some file-handling code that catches file IO exceptions like the example below:

public class ErrorHandling
{
    public string ReadFile(string path)
    {
        if(File.Exists(path))
        {
try
               {
                   StreamReader reader = File.OpenText(path);
                   return reader.ReadToEnd();
               }
               catch(UnauthorizedAccessException)
               {
                   return null;
               }
           }
           else
           {
               throw new ArgumentException("You must pass a valid file  path.","path"); } } } ...

Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.