How does a mocking framework work?

c#, implementation, mocking

Solution

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.

Problem

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'?

Original source