Mocking non-virtual methods in C#

2019-02-06 10:08发布

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).

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.

Thanks in advance

2条回答
祖国的老花朵
2楼-- · 2019-02-06 10:29

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 :)

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-06 10:48

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).

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.

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 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.

查看更多
登录 后发表回答