要模拟一个对象,它是否必须实现接口或标记为虚拟?
或者该类也可以实现抽象类吗?
or can the class be implementing an abstract class also?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
或者该类也可以实现抽象类吗?
or can the class be implementing an abstract class also?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(2)
要模拟类型,它必须是一个接口(这也称为纯虚拟)或具有虚拟成员(抽象成员也是虚拟的)。
根据这个定义,您可以模拟所有虚拟的东西。
本质上,动态模拟不会做任何你无法手动完成的事情。
假设您正在针对这样的接口进行编程:
您可以手动创建 IMyInterface 的特定于测试的实现,该实现会忽略输入参数并始终返回相同的输出:
但是,如果您想测试消费者响应不同的返回值,因此您可以让一个框架为您动态创建它们,而不是手动编写测试替身。
想象一下,动态模拟确实编写了与上面的 MyClass 实现类似的代码(它们实际上并不编写代码,而是动态发出类型,但这是一个足够准确的类比)。
以下是如何使用 Moq 定义与 MyClass 相同的行为:
在这两种情况下,创建对象时都会调用所创建类的构造函数。由于接口没有构造函数,因此这通常是默认构造函数(分别是 MyClass 和动态发出的类的)。
您可以对像这样的具体类型执行相同的操作:
您可以手动从 MyBase 派生并重写 Ploeh 方法,因为它是虚拟的:
动态模拟库可以执行相同的操作,对于抽象方法也是如此。
但是,您无法编写覆盖非虚拟或内部成员的代码,动态模拟也不能。他们只能做你手工能做的事情。
警告:上面的描述对于大多数动态模拟都是正确的,但 TypeMock 除外,它是不同的并且......可怕。
To mock a type, it must either be an interface (this is also called being pure virtual) or have virtual members (abstract members are also virtual).
By this definition, you can mock everything which is virtual.
Essentially, dynamic mocks don't do anything you couldn't do by hand.
Let's say you are programming against an interface such as this one:
You could manually create a test-specific implementation of IMyInterface that ignores the input parameter and always returns the same output:
However, that becomes repetitive really fast if you want to test how the consumer responds to different return values, so instead of coding up your Test Doubles by hand, you can have a framework dynamically create them for you.
Imagine that dynamic mocks really write code similar to the MyClass implementation above (they don't actually write the code, they dynamically emit the types, but it's an accurate enough analogy).
Here's how you could define the same behavior as MyClass with Moq:
In both cases, the construcor of the created class will be called when the object is created. As an interface has no constructor, this will normally be the default constructor (of MyClass and the dynamically emitted class, respectively).
You can do the same with concrete types such as this one:
By hand, you would be able to derive from MyBase and override the Ploeh method because it's virtual:
A dynamic mock library can do the same, and the same is true for abstract methods.
However, you can't write code that overrides a non-virtual or internal member, and neither can dynamic mocks. They can only do what you can do by hand.
Caveat: The above description is true for most dynamic mocks with the exception of TypeMock, which is different and... scary.
来自 Stephen Walther 的博客:
From Stephen Walther's blog: