码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET 系列:单元测试之SmtpClient

时间:2016-02-04 11:34:32      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

使用SmtpClient发送Email时,我们可以创建ISmtpClient接口和SmtpClientWrapper适配类,在单元测试中对ISmtpClient进行Mock或自定义FackeSmtpClient,但nDumbster的Facke SMTP Server给我们提供了更直观更简单的方式进行单元测试。可以通过Nuget搜索nDumbster,这里使用的是netDumbster

1.IEmailSender接口

public interface IEmailSender
{
    void SendMail(string from, string to, string subject, string body);
}

2.SMTPAdapter实现类

public interfacepublic class SMTPAdapter : IEmailSender
{
    public void SendMail(string from, string to, string subject, string body)
    {
        var message = new MailMessage();
        message.IsBodyHtml = true;
        message.From = new MailAddress(from);
        message.To.Add(new MailAddress(to));
        message.Subject = subject;
        message.Body = body;
        using (var smtpClient = new SmtpClient())
        {
            if (smtpClient.Host == null)
            {
                smtpClient.Host = "localhost";
            }
            smtpClient.Send(message);
        }
    }
}

3.使用nDumbster单元测试

public class SMTPAdapterTest
{
    [Fact]
    public void SendMailTest()
    {
        SimpleSmtpServer server = SimpleSmtpServer.Start(25);
        IEmailSender sender = new SMTPAdapter();
        sender.SendMail("sender@here.com", "receiver@there.com", "subject", "body");
        Assert.Equal(1, server.ReceivedEmailCount);
        SmtpMessage mail = (SmtpMessage)server.ReceivedEmail[0];
        Assert.Equal("sender@here.com", mail.Headers["From"]);
        Assert.Equal("receiver@there.com", mail.Headers["To"]);
        Assert.Equal("subject", mail.Headers["Subject"]);
        Assert.Equal("body", mail.MessageParts[0].BodyData);
        server.Stop();
    }
}

ASP.NET 系列:单元测试之SmtpClient

标签:

原文地址:http://www.cnblogs.com/easygame/p/5181160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!