ASP.NET 系列:單元測試之SmtpClient

剛哥521發表於2016-02-04

使用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();
    }
}

執行結果:

相關文章