I have a void function, which sends email. I need to write tests for this function. How can this be done?
public void SendAdminMail(string subject, string body, string adminAddress)
{
var email = Email.
From(ConfigurationManager.AppSettings["Mail.NoReply.Address"].ToString(CultureInfo.InvariantCulture)).
To(adminAddress).
Subject(subject).
Body(body).
UsingClient(GetOfficeClient());
email.Message.SubjectEncoding = Encoding.UTF8;
email.Message.BodyEncoding = Encoding.UTF8;
email.Send();
}
In this context it would be very hard - unless you'll be able to switch Email somehow through reflection (as interestingly pointed out by juhan_h in his answer, maybe not that hard nowadays ;) ).
Typical solution is to provide an interface for your class, for example interface EmailFactory. Then you'd have:
private EmailFactory emailFactory;
public void SendAdminMail(string subject, string body, string adminAddress)
{
var email = emailFactory
.From(ConfigurationManager
.AppSettings["Mail.NoReply.Address"]
.ToString(CultureInfo.InvariantCulture))
.To(adminAddress)
.Subject(subject)
.Body(body)
.UsingClient(GetOfficeClient());
email.Message.SubjectEncoding = Encoding.UTF8;
email.Message.BodyEncoding = Encoding.UTF8;
email.Send();
}
And then you could provide a stub of this factory to your class, which would create email mocks on which you could verify the correct behavior.
I am starting to think that unit tests should work when the network cable is unplugged.
What do you actually want to test?
You could use a mock or fake and verify that you have called methods as expected.
It might prove to be more useful to be able to stub out this class and use the stub elsewhere to make sure the rest of your tests don't send emails every time they are run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With