【发布时间】:2011-01-14 01:10:49
【问题描述】:
如何创建可以模拟和单元测试的电子邮件发送通知服务类?
我的服务位于另一个层,即类库。我试图不导入 smtp 客户端,但如果这是不可避免的,那么它没有问题。这就是我现在拥有的:
public class EmailNotificationService : INotificationService
{
private readonly EmailNotification _emailNotification;
public EmailNotificationService(EmailNotification emailNotification)
{
_emailNotification = emailNotification;
}
public void Notify()
{
using (var mail = new MailMessage())
{
//If no replyto was passed in the notification, then make it null.
mail.ReplyTo = string.IsNullOrEmpty(_emailNotification.ReplyTo) ? null : new MailAddress(_emailNotification.ReplyTo);
mail.To.Add(_emailNotification.To);
mail.From = _emailNotification.From;
mail.Subject = _emailNotification.Subject;
mail.Body = _emailNotification.Body;
mail.IsBodyHtml = true;
//this doesn't seem right.
SmtpClient client = new SmtpClient();
client.Send(mail);
}
}
}
public class EmailNotification
{
public EmailNotification()
{
To = "";
ReplyTo = "";
Subject = "";
Body = "";
}
public string To { get; set; }
public string ReplyTo { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
【问题讨论】:
-
发送电子邮件实际上比听起来和应该的要复杂得多。 codinghorror.com/blog/2010/04/…
-
你想在这里测试什么?在这门课中你可以进行单元测试的内容很少。测试它实际上发送电子邮件是一个集成测试。
-
您希望 EmailNotificationService 做什么?当然是发送电子邮件......我认为你的设计过于复杂
-
您所面临的单元测试是否存在一个特定问题,即此类正在抛出?这门课看起来不错,我怀疑你的测试才是真正的问题所在。
标签: asp.net-mvc design-patterns asp.net-mvc-3