[英]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. 在上面的代码中,我想存根/模拟serializer.Serialize方法以确保调用该方法。 I've tried so many way with moq and NMock but failed. 我用moq和NMock尝试了很多方法但是失败了。
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. 除非使用Typemock Isolator或Moles,否则不能替换使用new
关键字在内部创建的任何内容。
You'll need to first extract an interface from the XmlSerializer and then inject that into the class. 您需要首先从XmlSerializer中提取接口,然后将其注入到类中。
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: 将它注入您的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;
}
}
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. 上面的例子使用Moq。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.