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尝试过很多但是失败了。
请帮我修改/模拟对序列化程序的调用。
答案 0 :(得分:8)
除非您使用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。