c# - Moq - 在设置的返回中使用 It.IsAny 时会发生什么?

标签 c# unit-testing moq

我正在使用 Moq 在 C# 中执行单元测试。特别是一个测试,我在 System.Net.Mail.SmtpClient 上创建了一个接口(interface)包装器以便它可以被 mock 。

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);
    }
}

在我对这个包装器的测试中,确保方法 Send()被调用,我模拟了界面,在设置模拟时,我使用了 Setup()为该对象的属性赋值。在所有文档中,我看到 .Return()这些设置中的一些正在返回这些方法所期望的类型的特定值。然而,在我进一步理解之前,我改为使用 It.IsAny<T>在返回中。

[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);
}

我注意到测试通过了。由于我没有在其他地方看到过,所以我知道这不是最佳做法。我要问的是,为什么不使用它,使用 It.IsAny<T>() 会带来什么问题?在Return里面最小起订量的 Setup()还是模拟对象?

最佳答案

It旨在用于过滤和匹配参数的 Moq 表达式。

Allows the specification of a matching condition for an argument in a method invocation, rather than a specific argument value. "It" refers to the argument being matched.

It.IsAny<T>()通常在方法调用的实际参数值不相关时使用。当作为 Setup 之外的值传递时或 Verify表达式 It.IsAny<T>()传递通用参数的默认值。因此对于引用类型,它将传递 null 等等。

虽然在您的场景中它不会失败,但通常建议不要使用 It除了传递给模拟依赖项的匹配参数之外的任何类。

通常使用 Returns在进行测试时返回使用值。如果被测对象在调用模拟时期望一个值,而模拟是 Setup返回 It.IsAny<T>() ,那么测试将以意想不到的方式运行。

给定以下简单示例

public interface IDependency {
    string SomeMethod();
}

public MyClass {
    public bool MyMethod(IDependency input) {            
        var value = input.SomeMethod();

        var result = "Output" + value.ToUpper(); //<-- value should not be null

        return result != null;
    }
}

以下测试将失败并返回 NullReferenceException因为使用不当It.IsAny<T>()

[TestMethod]
public void MyMethod_Should_Return_True() {
    //Arrange
    var mock = new Mock<IDependency>();
    mock.Setup(_ => _.SomeMethod()).Returns(It.IsAny<string>());
    var subject = new MyClass();
    var expected = true;

    //Act
    var actual = subject.MyMethod(mock.Object);

    //Assert
    Assert.AreEqual(expected, actual);
}

关于c# - Moq - 在设置的返回中使用 It.IsAny 时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49761943/

相关文章:

c# - 关于 C# 泛型集合的问题

c# - 将 C#dll 加载到 C# exe 中

c# - 如何在c#中查看groupbox内的所有项目

c# - 如何在 C# 中写入运行时生成的 .dll 文件?

ios - 做OCUnit,将test after build设置为yes,项目无法build成功

javascript - 是否可以使用 Sinon.JS 检查函数参数是否正确绑定(bind)

c# - 如果使用设置,Moq 模拟调用将返回 null

c# - 如何将单元测试方法标记为过时,或者我应该保留该方法?

c# - 无法让模拟方法返回 null

c# - 如何使用 It.IsAny 作为参数?