Search code examples
c#unit-testingmicrosoft-fakes

How to shim virtual method?


How to cope with situation, when type got virtual method and I need to provide a Shim instead?

I have data contract, with code:

public class ServiceResponse
{
    ...
    public virtual string Serialize() {...}
    ...
}

In my code there is call to response.Serialize(), where response is type of ServiceResponse.

In my unit test I would like to do something like this:

ShimServiceResponse.Serialize = () => { return "serialized response"; };

But while the Serialize method is virtual, type ShimServiceResponse does not provide Serialize method to be "Shimmed".

What is the best way to solve this situation? Thanks.

I am using Microsoft Fakes Framework, .NET 4.5.2 and VS 2015.


Solution

  • Managed to work it out by creating child class and overriding Serialize method.

    class ServiceResponseChild : ServiceResponse
    {
        public override string Serialize()
        {
            return "orgUnitsResponse serialized";
        }
    }
    

    Later in my tests I am using this child class.

    ...
    ServiceResponse response = new ServiceResponseChild();
    target.SaveResponseAsXml(response);
    ...
    

    Although this is works for me, would be interested in other solutions utilizing the MS Fakes capabilities (if possible).