Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best method to test the serialization?

using System;
using System.Xml.Serialization;
using System.IO;

namespace Mailer {
    public class ClientConfiguration {

        public virtual bool Save(string fileName) {
            XmlSerializer serializer = new XmlSerializer(typeof(ClientConfiguration));
            using (StreamWriter writer = new StreamWriter(fileName)) {
                serializer.Serialize(writer, this);
            }
            return true;
        }
    }
}

In the above code I would like to stub/mock the serializer.Serialize method to ensure that the method is called. I've tried so many way with moq and NMock but failed.

Please help me in stub/mocking the calls to the serializer.

like image 687
Krishnaswamy Subramanian Avatar asked Apr 23 '11 05:04

Krishnaswamy Subramanian


1 Answers

Unless you use Typemock Isolator or Moles, you can't replace anything which is internally created with the new keyword.

You'll need to first extract an interface from the XmlSerializer and then inject that into the class.

As an example, you might introduce this interface:

public interface IXmlSerializer
{
    public void Serialize(Stream stream, object o);
}

Inject that into your Mailer class like this:

public class ClientConfiguration
{
    private readonly IXmlSerializer serializer;

    public ClientConfiguration(IXmlSerializer serializer)
    {
        if (serializer == null)
        {
            throw new ArgumentNullException("serializer");
        }
        this.serializer = serializer;
    }

    public virtual bool Save(string fileName)
    {
        using (StreamWriter writer = new StreamWriter(fileName))
        {
            this.serializer.Serialize(writer, this);
        }
        return true;
    }
}

Now you can inject the mock into the class:

var mock = new Mock<IXmlSerializer>();
var sut = new ClientConfiguration(mock.Object);

The above example uses Moq.

like image 90
Mark Seemann Avatar answered Sep 20 '22 00:09

Mark Seemann