如何使用Xunit在C#中模拟发送电子邮件

如何使用Xunit在C#中模拟发送电子邮件,c#,.net,xunit,xunit.net,C#,.net,Xunit,Xunit.net,我有一个发送电子邮件的方法,最初它设置了所有必需的配置参数,然后发送电子邮件。成功发送电子邮件后,该方法将返回true else false。我想在不发送电子邮件的情况下测试此方法 单元测试1:返回true, 单元测试2:返回false, 单元测试3:异常 下面是方法代码 public class SMTPEmailSender : IEmailSender { private IPDFCreater _pdfCreater; private ILogg

我有一个发送电子邮件的方法,最初它设置了所有必需的配置参数,然后发送电子邮件。成功发送电子邮件后,该方法将返回true else false。我想在不发送电子邮件的情况下测试此方法

单元测试1:返回true, 单元测试2:返回false, 单元测试3:异常

下面是方法代码

 public class SMTPEmailSender : IEmailSender
    {
        private IPDFCreater _pdfCreater;
        private ILogger _log;

        public SMTPEmailSender(IPDFCreater pdfCreater, ILogger log)
        {
            _pdfCreater = pdfCreater;
            _log = log;
        }

     public bool SendEmail(Email email)
        {

            bool isEmailSentSucessfully = false;
            SmtpClient client = null;
            MailMessage message = null;
            Attachment Attachment = null;

            try
            {
                client = new SmtpClient(email.SMTPServerUrl);

                // Specify the email sender.
                MailAddress from = new MailAddress(email.FromAddress, email.FromAddressDisplayName, email.Encoding);

                // Set destinations for the email message.
                MailAddress to = new MailAddress(email.ToAddress, email.ToAddressDisplayName, email.Encoding);

                // Specify the message content.
                message = new MailMessage(from, to)
                {
                    Body = email.Body,
                    BodyEncoding = email.Encoding,
                    Subject = email.Subject,
                    SubjectEncoding = email.Encoding
                };

                // Specify the Attachment
                Attachment = new Attachment(email.ContentStream, email.AttachmentName, MediaTypeNames.Application.Pdf);
                message.Attachments.Add(Attachment);
            }
            catch (Exception ex)
            {
                _log.Error(ex, ex.Message);
            }

            try
            {
                if (Attachment != null)
                {
                    client.Send(message);// This line of code sends email which should be mocked
                    isEmailSentSucessfully = true;
                }

            }
            catch (Exception ex)
            {
                _log.Error(ex, ex.Message);
                return isEmailSentSucessfully;
            }
            finally
            {
                message?.Dispose();
                client?.Dispose();
            }

            return isEmailSentSucessfully;
        }

}
我写了下面的代码,但这发送电子邮件

 [Theory]
        [MemberData(nameof(EmailObject))]
        public void SendEmail_ReturnTrue(Email email)
        {
            
            var result = _smtpEmailSender.SendEmail(email);
            Assert.True(result)
        }

虽然它更多的是集成测试而不是单元测试,但SMTP4DEV之类的实用工具是实现这类功能的便捷工具。它将充当本地主机上的邮件服务器,永远不会发送邮件。您可以阅读邮件,但无论邮件的收件人是谁,它们都会留在服务器中。