在 C# 中模拟非虚方法 [英] Mocking non-virtual methods in C#

查看:25
本文介绍了在 C# 中模拟非虚方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试我使用 mocks 制作的一些类,但我发现 c# 中的所有免费 mocking 框架都无法模拟非虚拟方法(如果它不在接口中).

I'm trying to test some classes I've made using mocks, but I've seen all free mocking frameworks in c# aren't able to mock non-virtual methods (if it is not in an interface).

但是,有 TypeMock 可以做到这一点,所以这是可能的.任何人都可以展示如何做到这一点?如果我能完成这项工作,我什至可能会尝试为开源框架做出贡献.

But, there's TypeMock who can do this, so it is possible. Can anyone show how to do it? I may even try to contribute to an open source framework if I can get this done.

提前致谢

推荐答案

我来自 Typemock,我不会解决太强大"的评论(尽管我无法理解为什么人们不想使用最好的工具工作).

I am from Typemock, and I won't address the "Too Powerful" comments (although it's beyond me why people wouldn't want to use the best tool for the job).

Typemock 隔离器的工作原理如下.你用过性能分析器吗?隔离器是一个分析器.它与 CLR 挂钩,并在测试运行时间内更改方法.当一个方法被 JITted 时,它会改变它,所以当方法运行时,在执行原始代码之前,它会问:我是否应该按照最初的预期运行它,如果不是,我应该怎么做?并且由于这种特定的技术,它可以模拟任何 .Net 方法和技术.就是这样.

Here's how Typemock Isolator works. Have you ever used a performance profiler? Isolator is a profiler. It hooks into the CLR and within the test run time, it changes methods. When a method gets JITted, it changes it, so when the method runs, before executing the original code, it asks: should I run it as originally intended, and if not, what should I do? And because of this specific technology, it can mock any .Net method and technology. That's it.

当您使用 API 设置行为时,问题的答案现在变得有趣,并在该方法的运行时改变行为.很简单,但在幕后需要做很多工作:)

When you set a behavior using the API, the answer to the questions now becomes intersting, and changes the behavior at runtime of that method. Simple, but under the covers it's a lot of work:)

Isolator 带有一个 VS 插件,可以在 VS 中无缝运行测试,并带有一个命令行工具和 MSBuild 或 NAnt 任务,以便在构建服务器中使用.

Isolator comes with a VS AddIn to make running the tests seamlessly within VS, and with a command line tool and MSBuild or NAnt tasks for usage in a build server.

我很乐意回答您的任何其他问题.

I'll be happy to answer any other questions you may have.

这篇关于在 C# 中模拟非虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆