Testing a method that sends email without sending 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 is sent to me, so it is not terrible (better than without the test), but I would prefer not to send mail.

  • The problem is that I do not want the test code in the class (i.e. if (testMode) to return instead of sending mail)
  • I don’t know much about DI, but I considered passing a false IMailer to MethodUnderTest, except that it overrides the base class, and no other class obtained from Base needs an IMailer object (I do not want to force base executors to accept unnecessary IMailer in MethodUnderTest)

What else can I do?

(: IMail IMailer . , , , , )

+3
6

IMailer in ClassUnderTests. , , .

- ( , , ), setter ( " " ).

+7

SMTP-, , , .

+2

- (, DI):

public class ClassUnderTest : Base
{
    private IMail mail;
    private IMailer mailer

    public ClassUnderTest()
    {
        mail = new Mail() { /* ... */ };
        mailer = new Mailer() { /* ... */ }
    }
    public ClassUnderTest(IMail mail, IMailer mailer)
    {
        this.mail = mail;
        this.mailer = mailer;
    }

    public override MethodUnderTest()
    {
        if(condition)
        {
            mailer.Send(mail);
        }
        else
        {
            /* ... */
        }
    }
}

, .

+1

( #)

- Java. , , , , . .

0

, - .

:

  • .

  • , , .

  • . , ( 14 , , , , ).

  • IMailer imailer.dll IMailer , siply SendMail.

  • SendMail() unit test.

  • SendMail() ClassUnderTest, , SendMail() .

  • /, SendMail

  • , , .

  • The class is completely redesigned so that it has SendReport (), and the report can be sent by email, TCP / IP, log file, etc.

  • and etc.

The best approaches, of course, do not require changes to the actual test method. Choose which one is best for your situation, and other unit tests that you need to add for this class.

0
source

Source: https://habr.com/ru/post/1745166/


All Articles