How do I make a mockup of System.Net.Mail MailMessage?

前端 未结 4 458
庸人自扰
庸人自扰 2021-02-04 02:47

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 met

相关标签:
4条回答
  • 2021-02-04 03:18

    You will end up mocking several different classes here (at least two). First, you need a wrapper around the MailMessage class. I would create an interface for the wrapper, then have the wrapper implement the interface. In your test, you will mock up the interface. Second, you'll provide a mock implementation as an expectation to the mocked interface for the MailAddressCollection. Since MailAddressCollection implements Collection<MailAddress>, this should be fairly straight-forward. If mocking the MailAddressCollection is problematic due to additional properties (I didn't check), you could have your wrapper return it as an IList<MailAddress>, which as an interface should be easy to mock.

    public interface IMailMessageWrapper
    {
        MailAddressCollection To { get; }
    }
    
    public class MailMessageWrapper
    {
        private MailMessage Message { get; set; }
    
        public MailMessageWrapper( MailMessage message )
        {
            this.Message = message;
        }
    
        public MailAddressCollection To
        {
            get { return this.Message.To; }
        }
    }
    
    // RhinoMock syntax, sorry -- but I don't use Moq
    public void MessageToTest()
    {
         var message = MockRepository.GenerateMock<IMailMessageWrapper>()
         var to = MockRepository.GenerateMock<MailAddressCollection>();
    
         var expectedAddress = "test@example.com";
    
         message.Expect( m => m.To ).Return( to ).Repeat.Any();
         to.Expect( t => t.Add( expectedAddress ) );
         ...
    }
    
    0 讨论(0)
  • 2021-02-04 03:32

    disclaimer: I work at Typemock Instead of finding some hack you can use Typemock Isolator to simply fake that class in only one line of code:

    var fakeMailMessage = Isolate.Fake.Instance<MailMessage>();
    

    Then you can set behavior on it using Isolate.WhenCalled

    0 讨论(0)
  • 2021-02-04 03:36

    In .NET 4.0 you can use the "duck-typing" to pass another class instead of "System.Net.Mail". But in earlier version, I'm afraid there is no another way, than create wrapper around "System.Net.Mail" nad the mock class.

    If is another (better) way, I would like to learn it :).

    EDIT:

    public interface IMailWrapper {
        /* members used from System.Net.Mail class */
    }
    
    public class MailWrapper {
        private System.Net.Mail original;
        public MailWrapper( System.Net.Mail original ) {
            this.original = original;
        }
    
        /* members used from System.Net.Mail class delegated to "original" */
    }
    
    public class MockMailWrapper {
       /* mocked members used from System.Net.Mail class */
    }
    
    
    void YourMethodUsingMail( IMailWrapper mail ) {
        /* do something */
    }
    
    0 讨论(0)
  • 2021-02-04 03:42

    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 讨论(0)
提交回复
热议问题