是否可以使用 Moq 来模拟实现接口和抽象类的对象?
即:
public class MyClass: SomeAbstractClass, IMyClass
你能嘲笑这个吗?
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?
发布评论
评论(2)
您可以模拟任何接口以及任何抽象或虚拟成员。基本上就是这样。
这意味着以下情况是绝对可能的:
如果从 SomeAbstractClass 继承的成员没有被密封,您还可以模拟 MyClass:
这是否有意义取决于 MyClass 的实现。假设 SomeAbstractClass 是这样定义的:
如果 MyClass 中的 GetStuff 方法是这样实现的,您仍然可以重写它:
这将允许您编写:
因为除非显式密封,否则 GetStuff 仍然是虚拟的。但是,如果您像这样编写 GetStuff:
您将无法模拟它。在这种情况下,您会收到来自 Moq 的异常,指出它是对非虚拟成员的无效覆盖(因为它现在已
密封
)。You can mock any interface, and any abstract or virtual members. That's basically it.
This means that the following are absolutely possible:
If the members inherited from SomeAbstractClass aren't sealed, you can also mock MyClass:
Whether this makes sense or not depends on the implementation of MyClass. Let's say that SomeAbstractClass is defined like this:
If the GetStuff method in MyClass is implemented like this, you can still override it:
This would allow you to write:
since unless explicitly sealed, GetStuff is still virtual. However, had you written GetStuff like this:
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 可用于模拟抽象类和接口。由于
MyClass
都不是,因此您无法创建它的模拟。不过,我认为这不是问题,因为 MyClass 实例的使用者可能会期待
SomeAbstractClass
或IMyClass
实例,而不是MyClass 实例。如果他们确实需要一个 MyClass 实例,那么您需要在其之上进行一些抽象。这可以通过让
SomeAbstractClass
实现IMyClass
接口,或者让IMyClass
接口公开SomeAbstractClass 的方法和属性来实现
。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 anIMyClass
instance and not aMyClass
instance. If indeed they expect aMyClass
instance, then you need to make some abstraction on top of it. This can be achieved by either havingSomeAbstractClass
implement theIMyClass
interface, or by having theIMyClass
interface expose the methods and properties ofSomeAbstractClass
.