Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit test for Void function (Sending Email)

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();
    }
like image 767
Geray Suinov Avatar asked Aug 20 '26 14:08

Geray Suinov


2 Answers

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.

like image 192
BartoszKP Avatar answered Aug 22 '26 04:08

BartoszKP


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.

like image 31
doctorlove Avatar answered Aug 22 '26 04:08

doctorlove



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!