是否可以将基于接口的模拟转换为对象?
事实上我有一个基于接口的模拟对象。我想将他转换为真实的对象。
var BM = new Mock<DAL.INTERFACES.IMYCLASS>();
是否可以转换模拟来检索 MYCLASS 对象?
谢谢各位的回复..
in fact I have a mock object based on the interface. I would like to cast him into the real object..
var BM = new Mock<DAL.INTERFACES.IMYCLASS>();
Is it possible to cast the mock to retrieve a MYCLASS object?
Thanks for responses..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这不是大多数模拟库的工作方式。
他们所做的是创建一个全新的对象,实现您要求的接口。
因此,底层对象根本不是 MYCLASS 对象,而是完全不同的东西。
如果您需要模拟具体的类,请使用可以模拟类的模拟库,并将代码更改为(类似于):
No, that's not how most mocking libraries work.
What they do is create a whole new object, implementing the interface you ask for.
As such, the underlying object is not a MYCLASS object at all, it's something else altogether.
If you need to mock a concrete class, use a mocking library that can mock classes, and change your code to be (similar to):
使用起订量允许您测试依赖于其他类/接口的类,而无需实例化它们。
如果您想要一个实现您的接口的对象实例,您可以简单地在您的成员上调用
Object
:不要忘记设置您的测试类所依赖的所需方法。如需了解更多信息,请参阅 快速入门指南 ://code.google.com/p/moq/" rel="nofollow">起订量主页。
Using moq allows you to test your class, which relies on other classes/interfaces, without needing to instantiate them.
If you want an instance of an object which implements your interface, you can simply call
Object
on your member:Don't forget to setup the required methods your testclass relies on. Further information can be found on the QuickStart guide on the moq homepage.
仅供参考,模拟库在幕后对目标类型进行子类化。
因此,当您请求
Mock()
时,您会得到该接口的实现,在 rubtime 时创建,如下所示:您最初想要实现的目标实际上是不可能的,因为您的
实现当 Moq 为您创建代理时,IInterface
是无处可见的。FYI, the mocking libraries subclass the target type behind the scenes.
So when you ask for
Mock<IInterface>()
, you get an implementation of that interface, creates at rubtime like so:What you originally wanted to achieve is not actually possible because your implementation of
IInterface
is nowhere to be seen when Moq creates a proxy for you.