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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With