views:

84

answers:

1

In the context of the Microsoft .Net Framework, I'm really curious about how mocking frameworks (Rhino Mocks, Moq, NMock, etc.) actually create the mock objects from a given type.

I'm interested in either the specific mechanics of one method or, if they use different methods perhaps some overview of the different ways. Alternatively, if anyone could point me at some articles, that'd be great too.

+10  A: 

There are different techniques out there for mocking.

Some mocking libaries like Moq and RhinoMocks use Castle Dynamic proxies. Essentially, they use reflection and runtime code generation (CodeDom) to dynamically generate classes that either implement an interface being mocked, or derive from a non-sealed class that's being mocked.

TypeMock is a bit different - it uses the Profiler APIs to intercept and redirect calls to any method on any type. This makes it capable of mocking sealed types, system classes, and even intercept and divert calls to non-virtual methods of concrete types.

UPDATE: From the TypeMock website:

Typemock Isolator uses an Aspect- Oriented programming design that creates a mock aspect. Internally, it uses the .NET framework profiler API to monitor an application's execution. When a method is called, the CLR notifies Typemock Isolator. The framework can then return mocked values and override the original code completely.

LBushkin
Does JustMock also use Debugger API? (BTW, I thought it was the Profiler API?)
Russ Cam
Link to profiling API - http://msdn.microsoft.com/en-us/magazine/cc301725.aspx
Russ Cam
@Russ Cam: I read up on it at one point, and I seem to recall it used the debugging APIs to intercept object creation and finalization. It may use the profiler APIs as well, since they are well suited to the kind of things it does. I'm not 100% certain, however, and I can't find the related doc at the moment.
LBushkin
@Russ Cam: I found the relevent info on the TypeMock website, it does look like it uses the profile API - and there's no mention of the debugger APIs, so I can't confirm if it uses that as well.
LBushkin
@LBushkin - +1 - thanks!
Russ Cam
Thanks! Food for thought.
Matt