4

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

Community
  • 1
  • 1
GilliVilla
  • 4,804
  • 11
  • 54
  • 93

2 Answers2

3

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.

C.Evenhuis
  • 25,310
  • 2
  • 59
  • 70
0

Mocking classes can get ugly if you're refactoring existing code. Imagine a class:

public class A
{
    private B _instanceOfB;

    public void DoSomethingWithInstanceOfB()
    {
        // do something with _instanceOfB
    }
}

If you want to mock A, not only do you need to extract the interface and refactor throughout your code -- but you might well need to start mocking B as well. And so on, potentially ad infinitum, in an enterprise setting. A concrete example might be if B were a class that manages access to a resource like a database.

Tim Barrass
  • 4,636
  • 2
  • 23
  • 49