0

Is there any way to mock Send(System.Net.Mail.MailMessage message) method to do nothing when called? I'm creating SmtpClient using 2 parameters constructor and sending a message like

using(var client = new SmtpClient(host, port)){
client.Send(message);
}

I don't really need to test it, just want to skip it and move on. For testing, I'm using XUnit and Moq.

lukaszgo3
  • 149
  • 3
  • 15
  • Tight coupling makes testing this code in isolation difficult. Consider decoupling your code using SOLID principles. – Nkosi Feb 10 '21 at 22:27
  • Does this answer your question? [How to mock/fake SmtpClient in a UnitTest?](https://stackoverflow.com/questions/19971364/how-to-mock-fake-smtpclient-in-a-unittest) – maxisam Nov 23 '22 at 00:14

1 Answers1

0

It looks like you need to implement any wrapper that implements the same methods.
For example:

public interface ISmtpClientWrapper
{
    void Send(MailMessage message);
}

public class SmtpClientWrapper : ISmtpClientWrapper
{
    private readonly SmtpClient _smtpClient;
    public SmtpClientWrapper()
    {
        _smtpClient = new SmtpClient("xxx", 25);
    }

    public void Send(MailMessage message)
    {
        _smtpClient.Send(message);
    }
}

And then pass it as parameter in constructor in the main class.

In this case you can use any mock framwork you want.

Roman Patutin
  • 2,171
  • 4
  • 23
  • 27