gpt4 book ai didi

c# - 如何模拟在单元测试函数中使用的 SmtpClient 对象

转载 作者:行者123 更新时间:2023-12-02 17:14:18 24 4
gpt4 key购买 nike

我想为 BatchProcess 中存在的 SendMail 方法编写 Nunit 或单元测试而不发送邮件。

如何模拟存在于另一个方法中的 SmtpClient。请帮忙。

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//Assuming we are populating the emails from the data from database
List<EmailEntity> emails = new List<EmailEntity>();
BatchProcess.SendMail(emails);
}
}

public class EmailEntity
{
public string ToAddress { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}

public class BatchProcess
{
public static void SendMail(List<EmailEntity> emails)
{
foreach (EmailEntity email in emails)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("sampleSmtp.sampleTest.com");
mail.From = new MailAddress("your_email_address@gmail.com");
mail.To.Add(email.ToAddress);
mail.Subject = email.Subject;
mail.Body = email.Body;
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
}
}
}

最佳答案

这就是您应该使用 Dependency Injection 的原因之一.

重点是您不应该在 SendMail() 中创建 SmtpClient 的实例。最好在实现 ISmtpClient 接口(interface)的 SmtpClient 上定义包装器,并将该接口(interface)传递给 BatchProcess 的构造函数,以便您可以在测试中模拟它:

public interface ISmtpClient
{
int Port { get; set; }

ICredentialsByHost Credentials { get; set; }

bool EnableSsl { get; set; }

void Send(MailMessage mail);
}

public class SmtpClientWrapper : SmtpClient, ISmtpClient
{
}

public class BatchProcess
{
private readonly ISmtpClient smtpClient;

BatchProcess(ISmtpClient smtpClient)
{
this.smtpClient = smtpClient;
}

public void SendMail(List<EmailEntity> emails)
{
foreach (EmailEntity email in emails)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("your_email_address@gmail.com");
mail.To.Add(email.ToAddress);
mail.Subject = email.Subject;
mail.Body = email.Body;

// You could leave this configuration here but it's far better to have it configured in SmtpClientWrapper constructor
// or at least outside the loop
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential("username", "password");
smtpClient.EnableSsl = true;

smtpClient.Send(mail);
}
}
}

关于c# - 如何模拟在单元测试函数中使用的 SmtpClient 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47321246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com