I am performing unit tests in C# using Moq. One test in particular I have created an interface wrapper over System.Net.Mail.SmtpClient
so that it can be mocked.
public class SmtpClient : ISmtpClient
{
public string Host { get; set; }
public int Port { get; set; }
public ICredentialsByHost Credentials { get; set; }
public bool EnableSsl { get; set; }
public void Send(MailMessage mail)
{
var smtpClient = new System.Net.Mail.SmtpClient
{
Host = Host,
Port = Port,
Credentials = Credentials,
EnableSsl = EnableSsl
};
smtpClient.Send(mail);
}
}
In my tests of this wrapper, to ensure that the method Send()
is called, I have mocked the interface, and in setting up the mock, I'm using the Setup()
to assign values to the properties of that object. In all documentation, I see that the .Return()
of those setups are returning a specific value of the type that these methods are expecting. However, before I understood it further, I instead used It.IsAny<T>
in the returns.
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
_smtpClientMock = new Mock<ISmtpClient>(MockBehavior.Strict);
_smtpClientMock.Setup(x => x.Port).Returns(8080);
_smtpClientMock.Setup(x => x.EnableSsl).Returns(false);
_smtpClientMock.Setup(x => x.Host).Returns("host");
_smtpClientMock.Setup(x => x.Credentials).Returns(It.IsAny<NetworkCredential>());
_smtpClientMock.Setup(mockSend => mockSend.Send(It.IsAny<MailMessage>()));
}
[TestMethod]
public void WithValidMailMessageObject_WhenSendIsCalled_EmailClientCallsSmptClientToSendEmail()
{
//Arrange
//Act
_smtpClientMock.Object.Send(new MailMessage());
//Assert
_smtpClientMock.Verify(checkMethodIsCalled => checkMethodIsCalled.Send(It.IsAny<MailMessage>()), Times.Once);
}
What I've noticed is that the tests passed. Since I haven't seen this elsewhere, I understand that this is not best practice. What I'm asking, is why is this not used, and what problems can come up with using It.IsAny<T>()
inside the Return
of a Moq's Setup()
or a mocked object?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…