[英]Can you mock an object that implements an interface AND an abstract class?
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: 如果没有密封从SomeAbstractClass继承的成员,则还可以模拟MyClass:
var mcMock = new Mock<MyClass>();
Whether this makes sense or not depends on the implementation of MyClass. 这是否有意义取决于MyClass的实现。 Let's say that SomeAbstractClass is defined like this:
假设SomeAbstractClass的定义如下:
public abstract class SomeAbstractClass
{
public abstract string GetStuff();
}
If the GetStuff method in MyClass is implemented like this, you can still override it: 如果MyClass中的GetStuff方法是这样实现的,您仍然可以覆盖它:
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. 因为除非明确密封,否则GetStuff仍然是虚拟的。 However, had you written GetStuff like this:
但是,您是否像这样编写了GetStuff:
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
). 在这种情况下,您会从Moq处获得一个异常,指出它是对非虚拟成员的无效替代(因为它已经被
sealed
)。
Your question does not really make sense. 您的问题没有任何意义。 Moq can be used to mock abstract classes and interfaces.
Moq可用于模拟抽象类和接口。 Since
MyClass
is neither then you cannot create a mock of it. 由于
MyClass
都不是,因此您无法创建它的模拟。 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. 我认为这不是问题,因为MyClass实例的使用者可能期望使用
SomeAbstractClass
或IMyClass
实例,而不是MyClass
实例。 If indeed they expect a MyClass
instance, then you need to make some abstraction on top of it. 如果确实希望使用
MyClass
实例,则需要在其之上进行一些抽象。 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
. 这可以通过使
SomeAbstractClass
实现IMyClass
接口或通过使IMyClass
接口公开IMyClass
的方法和属性来SomeAbstractClass
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.