Can you mock an object that implements an interface AND an abstract class?

微笑、不失礼 提交于 2019-12-12 08:29:57

问题


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.



来源:https://stackoverflow.com/questions/1969497/can-you-mock-an-object-that-implements-an-interface-and-an-abstract-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!