Search code examples
c#virtualmoq

Moq: Facade for a class whose method are not virtual


I have a class that depends on XmlSerializer. I want to mock XmlSerializer to verify that its methods are being called correctly. However, because the Serialize() and Deserialize() methods aren't virtual, there is no way Moq can do that.

The only solution that I see as viable is to write a Facade of XmlSerializer with virtual methods. Something like :

public class CustomXmlSerializer
{
    private XmlSerializer serializer;

    public CustomXmlSerializer(XmlSerializer serializer)
    {
        this.serializer = serializer;
    }

    public virtual void Serialize(Stream stream, object o)
    {
        serializer.Serialize(stream, o);
    }

    public virtual object Deserialize(Stream stream)
    {
        return serializer.Deserialize(stream);
    }
}

I was wondering if this would be considered good practice. Also, is there any other way to do this?


Solution

  • Create an interface e.g.IMySerializable with the two methods (Serialize and Deserialize) and declare the CustomXmlSerializer like this:

     class CustomXmlSerializer : IMySerializable {
       ...
     }
    

    Than the Moq should not have a problem.

    Or you can other library which uses IL e.g. typemock (http://www.typemock.com/). The typemock is paid. Other alternative is http://www.telerik.com/freemocking.aspx .