Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 255567
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T21:56:29+00:00 2026-05-11T21:56:29+00:00

So I have some SMTP stuff in my code and I am trying to

  • 0

So I have some SMTP stuff in my code and I am trying to unit test that method.

So I been trying to Mockup MailMessage but it never seems to work. I think none of the methods are virtual or abstract so I can’t use moq to mock it up :(.

So I guess I have to do it by hand and that’s where I am stuck.

*by hand I mean witting the interface and the wrapper but letting moq still mockup the interface.

I don’t know how to write my Interface and my Wrapper(a class that will implement the interface that will have the actual MailMessage code so when my real code runs it actually does the stuff it needs to do).

So first I am not sure how to setup my Interface. Lets take a look at one of the fields that I have to mockup.

MailMessage mail = new MailMessage();

mail.To.Add("test@hotmail.com");

so this is the first thing that I have to fake.

so looking at it I know that “To” is a property by hitting F12 over “To” it takes me to this line:

public MailAddressCollection To { get; }

So it is MailAddressCollection Property. But some how I am allowed to go further and do “Add”.

So now my question is in my interface what do I make?

do I make a property? Should this Property be MailAddressCollection?

Or should I have a method like?

void MailAddressCollection To(string email);

or 

void string To.Add(string email);

Then how would my wrapper look?

So as you can see I am very confused. Since there is so many of them. I am guessing I just mockup the ones I am using.

edit code

I guess in in a true sense I would only have to test more the exceptions but I want to test to make sure if everything gets sent then it will get to response = success.

string response = null;
            try
            {

                MembershipUser userName = Membership.GetUser(user);

                string newPassword = userName.ResetPassword(securityAnswer);

                MailMessage mail = new MailMessage();

                mail.To.Add(userName.Email);

                mail.From = new MailAddress(ConfigurationManager.AppSettings["FROMEMAIL"]);
                mail.Subject = "Password Reset";

                string body = userName + " Your Password has been reset. Your new temporary password is: " + newPassword;

                mail.Body = body;
                mail.IsBodyHtml = false;


                SmtpClient smtp = new SmtpClient();

                smtp.Host = ConfigurationManager.AppSettings["SMTP"];
                smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["FROMEMAIL"], ConfigurationManager.AppSettings["FROMPWD"]);

                smtp.EnableSsl = true;

                smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["FROMPORT"]);

                smtp.Send(mail);

                response = "Success";
            }
            catch (ArgumentNullException ex)
            {
                response = ex.Message;

            }
            catch (ArgumentException ex)
            {
                response = ex.Message;

            }
            catch (ConfigurationErrorsException ex)
            {
                response = ex.Message;
            }
            catch (ObjectDisposedException ex)
            {
                response = ex.Message;
            }
            catch (InvalidOperationException ex)
            {
                response = ex.Message;
            }
            catch (SmtpFailedRecipientException ex)
            {
                response = ex.Message;
            }
            catch (SmtpException ex)
            {
                response = ex.Message;
            }



            return response;

        } 

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T21:56:29+00:00Added an answer on May 11, 2026 at 9:56 pm

    Why mock the MailMessage? The SmtpClient receives MailMessages and sends them out; that’s the class I’d want to wrap for testing purposes. So, if you’re writing some type of system that places Orders, if you’re trying to test that your OrderService always emails when an order is placed, you’d have a class similar to the following:

    class OrderService : IOrderSerivce 
    {
        private IEmailService _mailer;
        public OrderService(IEmailService mailSvc) 
        {
            this. _mailer = mailSvc;
        }
    
        public void SubmitOrder(Order order) 
        {
            // other order-related code here
    
            System.Net.Mail.MailMessage confirmationEmail = ... // create the confirmation email
            _mailer.SendEmail(confirmationEmail);
        } 
    
    }
    

    With the default implementation of IEmailService wrapping SmtpClient:

    This way, when you go to write your unit test, you test the behavior of the code that uses the SmtpClient/EmailMessage classes, not the behavior of the SmtpClient/EmailMessage classes themselves:

    public Class When_an_order_is_placed
    {
        [Setup]
        public void TestSetup() {
            Order o = CreateTestOrder();
            mockedEmailService = CreateTestEmailService(); // this is what you want to mock
            IOrderService orderService = CreateTestOrderService(mockedEmailService);
            orderService.SubmitOrder(o);
        } 
    
        [Test]
        public void A_confirmation_email_should_be_sent() {
            Assert.IsTrue(mockedEmailService.SentMailMessage != null);
        }
    
    
        [Test]
        public void The_email_should_go_to_the_customer() {
            Assert.IsTrue(mockedEmailService.SentMailMessage.To.Contains("test@hotmail.com"));
        }
    
    }
    

    Edit: to address your comments below, you’d want two separate implementations of EmailService – only one would use SmtpClient, which you’d use in your application code:

    class EmailService : IEmailService {
        private SmtpClient client;
    
        public EmailService() {
            client = new SmtpClient();
            object settings = ConfigurationManager.AppSettings["SMTP"];
            // assign settings to SmtpClient, and set any other behavior you 
            // from SmtpClient in your application, such as ssl, host, credentials, 
            // delivery method, etc
        }
    
        public void SendEmail(MailMessage message) {
            client.Send(message);
        }
    
    }
    

    Your mocked/faked email service (you don’t need a mocking framework for this, but it helps) wouldn’t touch SmtpClient or SmtpSettings; it’d only record the fact that, at some point, an email was passed to it via SendEmail. You can then use this to test whether or not SendEmail was called, and with which parameters:

    class MockEmailService : IEmailService {
        private EmailMessage sentMessage;;
    
        public SentMailMessage { get { return sentMessage; } }
    
        public void SendEmail(MailMessage message) {
            sentMessage = message;
        }
    
    }
    

    The actual testing of whether or not the email was sent to the SMTP Server and delivered should fall outside the bounds of your unit testing. You need to know whether this works, and you can set up a second set of tests to specifically test this (typically called Integration Tests), but these are distinct tests separate from the code that tests the core behavior of your application.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 140k
  • Answers 140k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The y method is a handy way to get some… May 12, 2026 at 7:56 am
  • Editorial Team
    Editorial Team added an answer This is just a personal opinion (no hard data to… May 12, 2026 at 7:56 am
  • Editorial Team
    Editorial Team added an answer The section of code that fires if the element is… May 12, 2026 at 7:56 am

Related Questions

I have searched for other posts, as I felt this is a rather common
I'd like my program to be able to email me error reports. How can
I have a php script that does some processing (creates remittance advice PDFs, self-billing
I have some cross platform DNS client code that I use for doing end

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.