Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a mocking framework work?

Most mocking frameworks only are capable of mocking interfaces, some can mock virtual methods of classes. Some Java mocking frameworks are even capable of mocking static classes.

E.g. Rhino mock:

var mock = MockRepository.GenerateMock<..>();

What 'magic' goes down in the generate mock method? Is there a reason why C# mocking frameworks do not allow mocking static classes? Or is that just a 'design choice'?

like image 360
bas Avatar asked Mar 18 '13 20:03

bas


1 Answers

It is actually very fun and fascinating to look into the source code of such frameworks and find the answer yourself. Rhino Mocks is open-source, as well as Moq and many others. I would definitely recommend diving into one of those.

As for internal implementation (from here):

However, the framework can't mock non-virtual methods, so we'd need to make TouchIron method virtual. The reason for that lies deep inside: Rhino Mocks uses Castle Dynamic Proxy to handle proxying the types it needs to mock, and Dynamic Proxy cannot intercept calls to non-virtual, non-abstract methods.

like image 92
Alexander Tsvetkov Avatar answered Oct 13 '22 08:10

Alexander Tsvetkov