I have a business layer class that uses System.IO.File to read information from various files. In order to unit test this class I’ve chosen to replace the dependency on the File class with an injected dependency like so:
using System.IO;
public interface IFileWrapper
{
bool FileExists( string pathToFile );
Stream Open( string pathToFile );
}
Now I can test my class using a Mock and all is right with the world. Separately, I need a concrete implementation. I have the following:
using System;
using System.IO;
public class FileWrapper : IFileWrapper
{
public bool FileExists( string pathToFile )
{
return File.Exists( pathToFile );
}
public Stream Open( string pathToFile )
{
return File.Open( pathToFile, FileMode.Open, FileAccess.Read, FileShare.Read );
}
}
Now my business class is no longer dependent on the System.IO.File class and can be tested using a Mock of IFileWrapper. I see no need to test the System.IO.File class as I assume this has been thoroughly tested by Microsoft and proven in countless uses.
How do I test the concrete FileWrapper class? Though this is a simple class (low risk), I have larger examples that follow the same approach. I cannot approach 100% code coverage (assuming this is important) without completing this.
The larger question here I suppose is, how to bridge the gap between unit testing and integration testing? Is it necessary to test this class, or is there some attribute to decorate this class to exlcude this from code coverage calculation.
As a rule of thumb you should unit test all production code you write. However, due to the nature of how .NET is designed, there will always be classes like your Adapter class above that can’t be properly unit tested.
My personal rule of thumb is that if you can reduce each member in the Adapter to a cyclomatic complexity of 1 it’s okay to declare it a Humble Object.
AFAIK there are no ways to exclude code from coverage reports, but you can implement your Humble Objects in separate assemblies which are exempt from coverage reporting.