简体   繁体   English

为什么要使用非内联It.IsAny <T> 最小起订量不能正常工作?

[英]Why does using an non-inlined It.IsAny<T> in Moq not work correctly?

Assigning It.IsAny<T>() to a variable for use in a Setup on a mocked object does not work as expected: the test shown below fails. It.IsAny<T>()分配It.IsAny<T>()对象上的Setup使用的变量不能按预期方式工作:以下所示的测试失败。

However, if I inline the anyString variable the test passes. 但是,如果我内联anyString变量,则测试将通过。 What's going on here? 这里发生了什么?

public class MyService
{
    private readonly IDependency _dependency;

    public MyService(IDependency dependency)
    {
        _dependency = dependency;
    }

    public string UseTheDependency(string input)
    {
        return _dependency.GetValue(input);
    }
}

public interface IDependency
{
    string GetValue(string input);
}

public class Tests
{
    [Test]
    public void TestTheTestClass()
    {
        var mockDependency = new Mock<IDependency>();
        var anyString = It.IsAny<string>();
        mockDependency.Setup(x => x.GetValue(anyString)).Returns("expected value");
        var service = new MyService(mockDependency.Object);
        var result = service.UseTheDependency("something random");
        Assert.That(result, Is.EqualTo("expected value"));
    }
}

This is because the Setup method takes a Linq Expression ( Expression<Func<IDependency, string>> ) as a parameter, not a delegate ( Func<IDependency, string> ). 这是因为Setup方法将Linq表达式( Expression<Func<IDependency, string>> )作为参数,而不是委托( Func<IDependency, string> )作为参数。 It allows Moq to inspect the abstract syntax tree to know what call is being configured. 它使Moq可以检查抽象语法树,以了解正在配置的调用。 If you use a variable declared outside the expression, Moq doesn't know that you used It.IsAny , it just sees a null (technically, it sees an access to the field anyString of the object that encapsulates the captured local variables, and that field just contains null ). 如果您使用在表达式外部声明的变量,则Moq不会知道您使用了It.IsAny ,它只会看到一个null (从技术上讲,它将看到对封装捕获的局部变量的对象的anyString字段的访问,并且字段仅包含null )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM