12

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

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

提前致谢

4

2 回答 2

14

我来自 Typemock,我不会谈论“太强大”的评论(尽管我无法理解为什么人们不想使用最好的工具来完成这项工作)。

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

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

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

我很乐意回答您可能有的任何其他问题。

于 2009-07-03T14:11:20.577 回答
7

According to the website it uses AOP to redirect calls:

Typemock Isolator uses aspect-oriented technology to redirect calls from the real code. This enables developers to define the behavior of the external component required for a tested scenario. For example, you can simulate that the disk is full when writing to a database by instructing Typemock Isolator to throw an OutOfDiskSpaceException when writing to the database. This is a scenario that will be nearly impossible to test without Typemock Isolator. The developer defines the behavior in the actual unit test and Typemock Isolator automatically isolates all required components.

This technique requires you to set up a special environment before you can run the test or use a VS plugin.

Some people think that the ability to mock everything makes Typemock too powerful, since you don't have to think so much about good design. A quote from Ayende:

The main weakness of Type Mock is its power, it allow me to take shortcuts that I don't want to take, I want to get a system with low coupling and high cohesion.

But of course since he is the creater of Rhino Mock he is not objective :)

I would think you are in for a great deal of work if you want to create a mocking framework with this functionality, so I would recommend to either purchase Typemock, or learn to code without it :)

于 2009-07-02T11:00:52.970 回答