Say that you have this method to extract all the names of people from a file:
string[] GetNamesFrom(string path) { }
To test this method, you need to specify the path name to an existing file that needs some configuration.
Compare this with this method:
string[] GetNamesFrom(IFile file)
If the IFile contains the GetContents() method, then your "real" implementation of this interface can access the file system, and your mock class can simply return your test input.
Using a mock library such as moq ( http://code.google.com/p/moq/ ) becomes very simple:
var fileMock = new Mock<IFile>(); fileMock.Setup(f => f.GetContents()).Returns(testFileContents)); Assert.Equals(expectedNameArray, GetNamesFrom(fileMock.Object));
Writing a file to the file system before testing may not seem like many settings, but if you use many tests, it becomes a mess. Using interfaces and taunting, all settings occur in your test method.
source share