2011-01-14 81 views
2

如何创建可模拟和单元测试的电子邮件发送通知服务类?如何为asp.net设置电子邮件或通知服务mvc

我的服务位于另一个图层类库中。我试图不导入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; } 

} 
+1

发送电子邮件实际上比它听起来要复杂得多,比应该的要复杂得多。 http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html – 2011-01-14 01:31:11

+1

你想在这里测试什么?你很少能在这门课上进行单元测试。测试它*实际上*发送电子邮件是一个集成测试。 – 2011-01-14 01:44:09

回答

1

如果你不想导入System.Net.Mail库,你将不得不使用一个接口。请注意,这并不能真正帮助很大了,虽然

public interface IEmailSender{ 
    void Send(EmailNotification emailNotification); 
} 

您的单元测试,然后在EmailNotificationService类,你可以在你的构造函数中添加以下属性或通过在IEmailSender

private IEmailSender emailSender; 

public IEmailSender EmailSender 
{ 
    get{ 
      if(this.emailSender == null){ 
       //Initialize new EmailSender using either 
       // a factory pattern or inject using IOC 
      } 
      return this.emailSender 
    } 
    set{ 
      this.emailSender = value; 
    } 
} 

您的通知方法将成为

public void Notify() 
{ 
    EmailSender.Send(_emailNotification); 
} 

那么你会创建一个实现IEmailSender接口的具体类

public class MyEmailSender: IEmailSender 
{ 
    public void Send(EmailNotification emailNotification) 
    { 
     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; 

      SmtpClient client = new SmtpClient(); 
      client.Send(mail); 
     } 
    } 
}