To mock an object, does it have to be either implementing an interface or marked virtual?

or can the class be implementing an abstract class also?


To mock a type, it must either be an interface (this is also called being pure virtual) or have virtual members (abstract members are also virtual).

By this definition, you can mock everything which is virtual.

Essentially, dynamic mocks don't do anything you couldn't do by hand.

Let's say you are programming against an interface such as this one:

public interface IMyInterface
{
    string Foo(string s);
}

You could manually create a test-specific implementation of IMyInterface that ignores the input parameter and always returns the same output:

public class MyClass : IMyInterface
{
    public string Foo(string s)
    {
        return "Bar";
    }
}

However, that becomes repetitive really fast if you want to test how the consumer responds to different return values, so instead of coding up your Test Doubles by hand, you can have a framework dynamically create them for you.

Imagine that dynamic mocks really write code similar to the MyClass implementation above (they don't actually write the code, they dynamically emit the types, but it's an accurate enough analogy).

Here's how you could define the same behavior as MyClass with Moq:

var mock = new Mock<IMyInterface>();
mock.Setup(x => x.Foo(It.IsAny<string>())).Returns("Bar");

In both cases, the construcor of the created class will be called when the object is created. As an interface has no constructor, this will normally be the default constructor (of MyClass and the dynamically emitted class, respectively).

You can do the same with concrete types such as this one:

public class MyBase
{
    public virtual string Ploeh()
    {
        return "Fnaah";
    }
}

By hand, you would be able to derive from MyBase and override the Ploeh method because it's virtual:

public class TestSpecificChild : MyBase
{
    public override string Ploeh()
    {
        return "Ndøh";
    }
}

A dynamic mock library can do the same, and the same is true for abstract methods.

However, you can't write code that overrides a non-virtual or internal member, and neither can dynamic mocks. They can only do what you can do by hand.

Caveat: The above description is true for most dynamic mocks with the exception of TypeMock, which is different and... scary.


From Stephen Walther's blog:

You can use Moq to create mocks from both interfaces and existing classes. There are some requirements on the classes. The class can’t be sealed. Furthermore, the method being mocked must be marked as virtual. You cannot mock static methods (use the adaptor pattern to mock a static method).