I've recently started adding the following interface to most of my web applications in which a requirement is to send automated email notifications.
using System.Net.Mail;
namespace MyApp.Core.Service
{
public interface ISmtpService
{
void Send(MailMessage message);
}
}
And the code implementation is very basic:
using System.Net.Mail;
using MyApp.Core.Service;
namespace MyApp.Service
{
public class SmtpService : ISmtpService
{
public void Send(MailMessage message)
{
using (var client = new SmtpClient())
{
client.Send(message);
}
}
}
}
At first glace, it may be tempted to ask, "Why bother?" Implementing the interface and service takes twice as many lines as just the send and the code isn't complicated in the first place.
Once I've got the basic structure of a project fleshed out, I do my best to adhere to a test-driven mentality. Early on in one project, I found my code littered with if-else statements and breakpoints to prevent email from flooding the inbox of an intended recipient while also ensuring the message received was formatted as intended. It became obvious to me that this was a terrible solution. Not only does it just take too long to test, but anyone new on the project would also need to set breakpoints.
I've been using Moq to test my code for some time. Moq will allow me to attach a mocked ISmtpService in my code with a callback to record the message/recipient etc so I can easily see who the system is mailing as well as what is being mailed, I don't have to inspect the message manually, and the whole process is accomplished quickly.
Software Development Nerd