How to mock/fake SmtpClient in a UnitTest?

前端 未结 4 1622
野的像风
野的像风 2020-12-30 03:38

I want to use it to fake System.Net.Mail.SmtpClient in a MS-Test UnitTest. Therefor I added a Fakes Assembmly of System.dll. Then I create a ShimsContext<

4条回答
  •  不知归路
    2020-12-30 04:03

    You can create an interface which will expose functions that will be used from SmtpClient

    public interface ISmtpClient   
        {
            void Send(MailMessage mailMessage);
        }
    

    Then create your Concrete class which will do real job.

     public class SmtpClientWrapper : ISmtpClient
        {
            public SmtpClient SmtpClient { get; set; }
            public SmtpClientWrapper(string host, int port)
            {
                SmtpClient = new SmtpClient(host, port);
            }
            public void Send(MailMessage mailMessage)
            {
                SmtpClient.Send(mailMessage);
            }
        }
    

    In your test method now you can mock it and use like;

    [TestMethod()]
            public void SendTest()
            {
                Mock smtpClient = new Mock();
                SmtpProvider smtpProvider = new SmtpProvider(smtpClient.Object);
                string @from = "from@from.com";
                string to = "to@to.com";
                bool send = smtpProvider.Send(@from, to);
                Assert.IsTrue(send);
            }
    

提交回复
热议问题