In answer to this question here Jon Skeet answered :>>
You can test via mocking really easily (without having to mock classes, which gets ugly)
I would like a better understanding through a standalone example elaborating this aspect …both the before (ugly) and the after (interface-based) scenarios in C#.
And also, in addition, if there is an example within the .NET Framework BCL itself that would be great
Say you have this method to fetch all names of people from a file:
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:
If
IFilecontains aGetContents()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:
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.