模拟非接口类
一般的模拟框架和特定的Rhino模拟是否只模拟具有虚方法的接口和类?例如,我可以模拟以下简单的类:
public class MyClass
{
void method1()
{
//some code goes here
}
}
如果答案是正确的,为什么存在这样的限制?有什么解决方法吗?
Is it true that mocking frameworks in general and Rhino mocking in specific only mocks interfaces and classes that have virtual method? For example can I mock following simple class:
public class MyClass
{
void method1()
{
//some code goes here
}
}
If the answer is true, why such a limitation exists? Is there any work-around?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这种限制是存在的,因为模拟框架无法在没有虚拟或接口的情况下更改
method1
。这是一个合理的限制,因为接口允许您解耦依赖关系,并且是良好代码的共同特征(IMO)。不幸的是,大多数 .Net 框架没有虚拟方法或接口...这需要丑陋的包装才能创建接口。如果您真的不喜欢它,可以使用一种模拟框架选项,通过使用一些疯狂的魔法 foo 连接 CLR 来突破限制。该著名作品称为 TypeMock Isolator。
The limitation exists, because the mocking frameworks cannot change
method1
without it being virtual or an interface. It is a reasonable limitation, since interfaces allow you to decouple your dependencies and is a common trait of good code, IMO. Unfortunately, most of the .Net framework does not have virtual methods or interfaces... which requires ugly wrapping in order to create interfaces.If you really don't like it, one mocking framework option out there that gets past the limitation by hooking the CLR with some crazy magic foo. That famework is called TypeMock Isolator.
我不确定你如何模拟一个没有实现接口或没有虚拟方法的类。如果某些代码需要 MyClass 的实例,并且您向其传递 MyDerivedMockClass 的实例,则将访问 MyClass 成员而不是 MyDerivedMockClass 成员,因为它们不是重写的虚拟成员。
I am not sure how you would mock a class that did not implement an interface or have virtual methods. If some code is expecting an instance of MyClass and you pass it an instance of MyDerivedMockClass, then the MyClass members will be accessed not MyDerivedMockClass members because they are not overridden virtual members.
Typemock 是您最好的选择。
http://site.typemock.com/
Typemock is your best bet.
http://site.typemock.com/