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

Pex And Dynamic Test Methods

Pex as covered in past posts is a pretty great white box testing tool. But let’s assume that you want to have a “factory” in the sense that test methods can be automagically built out. An example of this is you have a list of some acceptable data type, and you want harness a test case for each one, and avoid the use of haphazard data keeping in mind that Pex will only use varying values.

In this case, you must push Pex to use parameterized unit tests since you will essentially be targeting a value from a list of values. In the below, I am assuming an array of integers is being populated by the void PopulateIntArray() method. Following, the Test method is defined which has the method decoration of PexMethod which implies it is Pex parameterized unit test. In the method, we are leveraging the PexAssume.IsTrue which means the test case fails if the condition evaluates to false.

[csharp]
static int[] intArray = PopulateIntArray();
[PexMethod]
public void Test(int index)
{
PexAssume.IsTrue(index >= 0 && index < intArray.Length); int x = intArray[index]; ... } [/csharp] EDIT: As Peli points out in the comments, you can use the PexArguments decoration to pass in values as well.

Share