如何嘲笑在的UnitTest /假SmtpClient? [英] How to mock/fake SmtpClient in a UnitTest?
本文介绍了如何嘲笑在的UnitTest /假SmtpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用它来在MS-测试的UnitTest假 System.Net.Mail.SmtpClient
。为此我添加System.dll中的假货Assembmly。然后,我创建一个 ShimsContext
和 StubSmtpClient
。
I want to use it to fake System.Net.Mail.SmtpClient
in a MS-Test UnitTest. Therefor I added a Fakes Assembmly of System.dll. Then I create a ShimsContext
and a StubSmtpClient
.
using (ShimsContext.Create())
{
StubSmtpClient client = new StubSmtpClient();
}
不过,我该怎么办呢?
的最终目标将是写一个预计发送方法被调用 MAILMESSAGE
的对象的测试。
推荐答案
您可以创建一个将暴露将从SmtpClient
You can create an interface which will expose functions that will be used from SmtpClient
public interface ISmtpClient
{
void Send(MailMessage mailMessage);
}
然后创建具体的类,将做实的工作。
Then create your Concrete class which will do real job.
public class SmtpClientWrapper : ISmtpClient
{
public SmtpClient SmtpClient { get; set; }
public SmtpClientWrapper(string host, int port)
{
SmtpClient = new SmtpClient(host, port);
}
public void Send(MailMessage mailMessage)
{
SmtpClient.Send(mailMessage);
}
}
在您的测试方法,现在你可以嘲笑它和使用等;
In your test method now you can mock it and use like;
[TestMethod()]
public void SendTest()
{
Mock<ISmtpClient> smtpClient = new Mock<ISmtpClient>();
SmtpProvider smtpProvider = new SmtpProvider(smtpClient.Object);
string @from = "from@from.com";
string to = "to@to.com";
bool send = smtpProvider.Send(@from, to);
Assert.IsTrue(send);
}
这篇关于如何嘲笑在的UnitTest /假SmtpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文