ASP. NET series: SmtpClient and asp. netsmtpclient for unit testing

Source: Internet
Author: User
Tags smtpclient

ASP. NET series: SmtpClient and asp. netsmtpclient for unit testing

When SmtpClient is used to send an Email, we can create an ISmtpClient interface and a SmtpClientWrapper adaptation class. In the unit test, we can perform Mock or custom FackeSmtpClient for ISmtpClient, however, the Facke SMTP Server of nDumbster provides us with a more intuitive and simple way to perform unit tests. You can search for nDumbster through Nuget. Here netDumbster is used.

1. IEmailSender Interface
public interface IEmailSender{    void SendMail(string from, string to, string subject, string body);}
2. Implementation class of 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. Use nDumbster for unit testing
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();    }}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.