Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a method that sends e-mail without sending the mail

I have a method like

public abstract class Base
{
    public void MethodUnderTest();
}

public class ClassUnderTest : Base
{
    public override MethodUnderTest()
    {
        if(condition)
        {
            IMail mail = new Mail() { /* ... */ };
            IMailer mailer = new Mailer() { /* ... */ }

            mailer.Send(mail);
        }
        else
        {
            /* ... */
        }
    }
}

I have unit tests for this method, and the mail gets sent to myself, so it's not terrible (better than no test) but I'd prefer not to send the mail.

  • The problem I have is that I don't want test specific code in the class (ie. if (testMode) return; instead of sending the mail)
  • I don't know lots about DI, but I considered passing a mock IMailer into MethodUnderTest except that it overrides the base class, and no other class that derives from Base needs an IMailer object (I don't want to force implementers of Base to take an unnecessary IMailer in MethodUnderTest)

What else can I do?

(note: IMail and IMailer are part of an external library for sending e-mail. It's written in house, so I can modify it all I like if necessary, though I can't see a need to in this situation)

like image 787
Steven Evers Avatar asked Oct 19 '25 01:10

Steven Evers


2 Answers

A standard approach using dependency injection would be to require an IMailer in ClassUnderTests's constructor. If you do that, you pass a mock mailer into your tests, and the base class doesn't need to know anything about mailing or mailers.

If that's undesirable for some reason (this is pretty rare, it's usually only relevant when you don't control the underlying classes), you can use setter injection ("property injection").

like image 150
Jeff Sternal Avatar answered Oct 21 '25 14:10

Jeff Sternal


You (may) can use a pickup directory and set it to a directory that is not configured to send:

http://www.singular.co.nz/blog/archive/2007/11.aspx

http://www.singular.co.nz/blog/archive/2007/12/19/programmatically-setting-the-smtpclient-pickup-directory-location-at-runtime.aspx

http://forum.discountasp.net/showthread.php?t=4593

like image 33
Curtis White Avatar answered Oct 21 '25 13:10

Curtis White



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!