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; } } }
在上面的代码中,我想存根/模拟serializer.Serialize方法以确保调用该方法.我用moq和NMock尝试了很多方法但是失败了.
请帮助我存根/模拟对序列化程序的调用.
解决方法
除非您使用Typemock Isolator或Moles,否则不能替换使用new关键字在内部创建的任何内容.
您需要首先从XmlSerializer中提取接口,然后将其注入到类中.
例如,您可以介绍此接口:
public interface IXmlSerializer { public void Serialize(Stream stream,object o); }
将它注入您的Mailer类中,如下所示:
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; } }
现在您可以将模拟注入到类中:
var mock = new Mock<IXmlSerializer>(); var sut = new ClientConfiguration(mock.Object);
上面的例子使用Moq.