How to create an instance that cant be instantiated.

One of the questions that keep up popping every once in a while in our forums is how to “bypass” the creation phase of an object.

Actually here lies the true power of the Isolator framework. The Isolator can be used to “instantiate” an object of any given type. And I mean ANY,including types which cant be normally instantiated due to a “hidden” constructor.

This unique ability is what sets the Isolator apart from other mocking frameworks, and the understanding of this does require a small mental leap. To a new beginner this concept is kind of wierd and does not sit well with the simple understanding of how things work.

There are two options which were explained in this post:

The Typemock Insider Blog: Creation of Mocks – On the difference between Mock and MockObject

but to summerize one can create a “future mock” that will replace the next object which is created (using the Mock class) or one can instantiate a fake object to be passed to the executing code (using the MockObject class).

A lot of people refer to this as “Typemock Magic” and I’m sure that a quick glimpse under the hood would shed some light on the matter.

Unlike other frameworks around, the Isolator is based on interception principles. Using the CLR Profiling API we are able to “catch” ANY method being called and replace it with any logic we wish. In the scope of a mocking framework this allow us to just swap any call to any method with any other implementation the user specifies , for example we allow user to “swap” a void method with an empty implementation (i.e. just skip over it).

The nice thing about such an engine is that it works on constructors as well. When an object is created (using the new keyword) 2 things happen behind the scene:

1) The CLR allocate memory and create a reference that is used and returned as the created instance.

2) The appropriate constructor of the created instance is activated.

In short the actual constructor activation is the like any other method call which allows it to be intercepted.

To summarize, in order to bypass the creation phase of an instance, just creates a mock controller (either a future mock or not), by default this will instruct the framework to skip the constructor execution (we term we use for this is Constructor Mocking). and the good thing that the same technique can be used for ANY type including those that cant be instantiated.

TOP