测试序列化的最佳方法是什么?
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 的方法,但都失败了。
请帮助我存根/模拟对序列化器的调用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非您使用 Typemock Isolator 或 Moles,否则您无法替换使用
new
关键字内部创建的任何内容。您需要首先从 XmlSerializer 中提取接口,然后将其注入到类中。
例如,您可以引入此接口:
将其注入到您的 Mailer 类中,如下所示:
现在您可以将模拟注入到类中:
上面的示例使用 Moq。
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:
Inject that into your Mailer class like this:
Now you can inject the mock into the class:
The above example uses Moq.