Skip to main content
3 of 8
formatting
dfhwze
  • 13.9k
  • 3
  • 38
  • 101

am I using the Factory pattern right in my code & how I can test it?

In my application I have an Interface IEmailNotification that represents an Email and the concrete implementations have nothing to do with MailMessage class so to be able to send it through SmtpClient I used an adapter to let the communication between SmtpClient and IEmailNotification possible and the job of this adapter is simply delegate the Send call to SmtpClient but after converting from EmailNotification to MailMessage using an abstract Factory which in fact only copying the values from one object to the new created MailMessage object.

The first question is: my factory method takes a parameter of type IEmailNotification, does that violates the main Job of a Factory which is only creating objects?

public override MailMessage CreateMailMessage(IEmailNotification emailNotification)
{
    var mailMessage = new MailMessage();

    mailMessage.From = new MailAddress(emailNotification.From);
    mailMessage.To.Add(_redirectToEmail);
    mailMessage.Subject = emailNotification.Subject;
    mailMessage.Body = emailNotification.Body;
    mailMessage.IsBodyHtml = emailNotification.IsBodyHtml;

    if (emailNotification.To.ToLower().Contains("shopfehler"))
        mailMessage.Bcc.Add(new MailAddress(_backupBccEmail));

    if (!string.IsNullOrEmpty(emailNotification.ReplyToList))
        mailMessage.ReplyToList.Add(emailNotification.ReplyToList);

    if (emailNotification.AttachmentsPaths.Count > 0)
    {
        foreach (var path in emailNotification.AttachmentsPaths)
        {
            mailMessage.Attachments.Add(new Attachment(path));
        }
    }

    return mailMessage;
}

The second question is: When I tried to test the logic of this method It failed because it uses an external resource at the line of adding new attachments where it cannot find the related paths on the Hard Drive, what do you people think about it?

thanks in advance

sam
  • 23
  • 2