Friday, March 30, 2012

Detouring methods on base type and implementing type with Moles

I have been using the Moles framework recently in order to stub out dependencies on a third party library where the classes to be stubbed had some or all of the following characteristics:

  • No public constructor.
  • Methods to be stubbed are not virtual.
  • Methods to be stubbed are static.

The Moles framework is capable of handling all of the above and I won’t reprise the documentation here.

However, I did hit a quirk with this which is that when you generate the Moled type and set the detours for its methods, you can only detour the methods on that type and not the base type. Consider the following two classes.

public abstract class A
{
  protected string _type;
  /*
  This will be detoured in test
  */
  public string Type 
  {
  get 
  {
  return _type;
  }
  }
}
/*
Class to be moled. We want to detour both Type and Level
*/
public class B:A
{
  int _level =  1;
  internal B()
  {
    _type = "B";
  }
  
  public int Level
  {
    get
    {
      return _level;
    }
  }
}


The following code shows how to detour properties on both A and B:



public MA Build()
{
  //We want to return an instance of the sub type as the base type, detouring methods
  //on both the subtype and the base type (A)
  var moledB = new MB();
  //Detour method on subtype
  moledB.LevelGet = () => _level;
  //Create using instance of Moled Subtype
  var moledA = new MA(moledB);
  //Detour methods on base type
  moledA.TypeGet = () => _type;
  //return Moled basetype. As this was created using the constructor that took  an instance, we will
  //be able to cast this to A
  return moledA;
}