2011-01-14 82 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); 
     } 
    } 
}