Is it possible to use Moq to mock an object that implements an interface and abstract class?
I.e.:
public class MyClass: SomeAbstractClass, IMyClass
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();
var aMock = new Mock();
If the members inherited from SomeAbstractClass aren't sealed, you can also mock MyClass:
var mcMock = new Mock();
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
).