-->

Can you mock an object that implements an interfac

2020-07-06 04:01发布

问题:

Is it possible to use Moq to mock an object that implements an interface and abstract class?

I.e.:

public class MyClass: SomeAbstractClass, IMyClass

Can you mock this?

回答1:

You can mock any interface, and any abstract or virtual members. That's basically it.

This means that the following are absolutely possible:

var imock = new Mock<IMyClass>();
var aMock = new Mock<SomeAbstractClass>();

If the members inherited from SomeAbstractClass aren't sealed, you can also mock MyClass:

var mcMock = new Mock<MyClass>();

Whether this makes sense or not depends on the implementation of MyClass. Let's say that SomeAbstractClass is defined like this:

public abstract class SomeAbstractClass
{
    public abstract string GetStuff();
}

If the GetStuff method in MyClass is implemented like this, you can still override it:

public override string GetStuff()
{
    return "Foo";
}

This would allow you to write:

mcMock.Setup(x => x.GetStuff()).Returns("Bar");

since unless explicitly sealed, GetStuff is still virtual. However, had you written GetStuff like this:

public override sealed string GetStuff()
{
    return "Baz";
}

You wouldn't be able to mock it. In that case, you would get an exception from Moq stating that it's an invalid override of a non-virtual member (since it's now sealed).



回答2:

Your question does not really make sense. Moq can be used to mock abstract classes and interfaces. Since MyClass is neither then you cannot create a mock of it. I don't think this is a problem though, since consumers of your MyClass instance will probably be expecting a SomeAbstractClass or an IMyClass instance and not a MyClass instance. If indeed they expect a MyClass instance, then you need to make some abstraction on top of it. This can be achieved by either having SomeAbstractClass implement the IMyClass interface, or by having the IMyClass interface expose the methods and properties of SomeAbstractClass.