Runtime Instance From Mole Types

This is more of a quick tip than anything in regards to moles. When using moles, sometimes you might be find yourself executing a safe cast, or trying to, between your Mole and runtime instance type. Why would this happen? Well consider the following simple code:

[csharp]
TypeX x = ReturnAType() as TypeX;
[/csharp]

Now this is a problem with moles, because the typecast will fail resulting in x being null. However, the solution is just to stick with variant types when using Moled types, each moled type will have a property representing the Instance (the property is actually the MoledType.Instance property) which will expose the runtime instance. The cool part is the case is built automagically by the compiler :-)

Share

Moles On Base Classes

This one took me a little bit to understand. Sometimes the Moles exception handling is so aggressive that it becomes a little tricky to understand exactly what is bubbling up.
Assume MethodX() is a member of base class ConcreteX. Requirements state that you need to have moles for MethodX() in order to support data mocking. It is important to remember for this particular requirement that base member access is achieved by allocating the mole type of ConcreteX and passing the instance in the constructor. This looks like the following:
[csharp]
ConcreteX x = new ConcreteX();
new MObjectContenxt(x).
[/csharp]
Now, if it isn’t done in this fashion MethodX() will not be moled, however you can still mole the entire assembly I suppose. However, doing it in the above fashion avoids using a wrapper in partial classes and a lot of rework based on class hierarchy.

Share