模拟非接口类

发布于 2024-09-10 16:04:48 字数 206 浏览 1 评论 0原文

一般的模拟框架和特定的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无语# 2024-09-17 16:04:48

这种限制是存在的,因为模拟框架无法在没有虚拟或接口的情况下更改 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.

弃爱 2024-09-17 16:04:48

我不确定你如何模拟一个没有实现接口或没有虚拟方法的类。如果某些代码需要 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.

∞梦里开花 2024-09-17 16:04:48

Typemock 是您最好的选择。

http://site.typemock.com/

Typemock is your best bet.

http://site.typemock.com/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文