你可以嘲笑实现接口和抽象类的对象? [英] Can you mock an object that implements an interface AND an abstract class?
问题描述
是否有可能使用起订量嘲笑实现接口和抽象类的对象?
Is it possible to use Moq to mock an object that implements an interface and abstract class?
即:
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<IMyClass>();
var aMock = new Mock<SomeAbstractClass>();
如果该成员SomeAbstractClass继承是不是密封的,还可以模拟MyClass的:
If the members inherited from SomeAbstractClass aren't sealed, you can also mock MyClass:
var mcMock = new Mock<MyClass>();
这是否有道理与否取决于MyClass的实施。比方说,SomeAbstractClass是这样定义的:
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();
}
如果MyClass中的GetStuff方法是这样实现的,你仍然可以覆盖它
If the GetStuff method in MyClass is implemented like this, you can still override it:
public override string GetStuff()
{
return "Foo";
}
这将使你写:
mcMock.Setup(x => x.GetStuff()).Returns("Bar");
因为除非明确地密封,GetStuff依然是虚拟的。不过,有了你写GetStuff是这样的:
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
).
这篇关于你可以嘲笑实现接口和抽象类的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!