Mocking Frameworks, How'd They Do That?!
The largest mystery when trying to understand how a mocking framework works has always been just understanding where this object it creates comes from. I mean I give the mocking framework an interface and it comes back with an object that implements everything (at least in the case of a stub). The point of this post is to show that they aren't magical and to hopefully extend what you think is possible in your own problem solving with C#. I'll be assuming you're familiar with mock objects and how/why they're used.
- First we need to build our new type that will be implementing the interface we were given by the person using our code. We define this type as being public and as being a class. The null at line 25 tells the TypeBuilder that this class has no parent and line 26 tells the TypeBuilder that we're implementing the interface provided to us by the user.
- Next we need to get a list of all of the methods that we need to implement on our new type. To do this I needed to reflect into the interface type provided and grab all of the methods it declares. I do this on lines 28 and 29.
- If there aren't any methods we're done! Create that type and create a new instance of it! (lines 49 and 50).
- If there are methods things get trickier.
- First, if the method takes in parameters we need to generate a list of the types of those parameters so that we can write the corresponding IL. (Line 35)
- Each method needs to be built up according to whether or not it has a return value.
- Then just create our instance.
- First, I'm defining my method. I tell the TypeBuilder to define a method with the following properties:
- same name as the one on my interface
- that the method should be public and virtual,
- that the return type is void
- that it will take in the provided set of types as parameters.
- Then we're going to generate IL that does absolutely nothing with any of this. :)
- We just generate a single IL instruction that just returns.


Comments [0]