Question

I'd like to do an override with MS Fakes that would call the base code and I can't find how to do it. Here's an example

Given

public class Potato
{
   public virtual string Peel(PeelingMethod peelingMethod)
   {
      return "potato peeled";
   }
}

When I create my Stub

new StubPotato()
{
    PeelPeelingMethod = (p) =>
    {
       //Doesn't compile!
       base.Peel(p);
       Console.WriteLine("Hello world");
    }
}

How can I achieve this, I am pretty new to the MS Fakes framework so maybee there is something i don't know about it.

Was it helpful?

Solution

I found a solution, it is pretty disgusting but it works. I'll put it here if someone needs. I'll reuse my example (that I edited because I didn't test this answer with a method that returns void)

var stubPotato = new StubPotato()
{
    PeelPeelingMethod = (p) =>
    {
        //Base method call
        MethodInfo methodInfo = typeof(Potato).GetMethod("Peel", BindingFlags.Instance | BindingFlags.Public);
        var methodPtr = methodInfo.MethodHandle.GetFunctionPointer();
        var baseMethod = (Func<PeelingMethod,string>)Activator.CreateInstance(typeof(Func<PeelingMethod,string>), stubPotato , methodPtr);
        string baseResult = baseMethod(p);

        //Code for the "override"
        Console.WriteLine("Hello world");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top