Say you have this method to fetch all names of people from a file:
string[] GetNamesFrom(string path) { }
To test this method you would have to supply a path name of an existing file, which requires some setup.
Compare that to this method:
string[] GetNamesFrom(IFile file)
If IFile
contains a GetContents()
method, then your "real" implementation of this interface could access the file system, and your mock class could simply return your test input data.
Using a mock library like moq (http://code.google.com/p/moq/) this becomes really 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 prior to testing might not sound like alot of setup, but if you're running alot of tests, it becomes a mess. By using interfaces and mocking, all setup happens within your test method.