Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do mocking frameworks (in .Net) create mock objects?

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.

like image 492
Matt Avatar asked Aug 27 '10 18:08

Matt


People also ask

Which framework is used to create mocked objects?

Creating mock objects manually is very difficult and time-consuming. So, to increase your productivity, you can go for the automatic generation of mock objects by using a Mocking Framework. A developer can build his/her unit test by using any of the NUnit, MbUnit, MSTest, xUnit etc.

How do mock objects work?

A object that you want to test may have dependencies on other complex objects. To isolate the behavior of the object you want to test you replace the other objects by mocks that simulate the behavior of the real objects. So in simple words, mocking is creating objects that simulate the behavior of real objects.

What is mocking framework C#?

Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.


1 Answers

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.

like image 146
LBushkin Avatar answered Sep 30 '22 20:09

LBushkin