c# - 为什么是??运算符(operator)不在最小起订量设置方法中工作

标签 c# null moq

谁能给我解释一下,为什么这行不通?


builder.Setup(b => b.BuildCommand(query ?? It.IsAny<string>())).Returns(command);

如果querynull , BuildCommand将通过 null ,而不是 It.IsAny<string>()

相反,我必须这样做:

if(query == null)
    builder.Setup(b => b.BuildCommand(It.IsAny<string>())).Returns(command);
else
    builder.Setup(b => b.BuildCommand(query)).Returns(command);

和delegate有关系吗?


编辑 - 完整示例

public static void ReturnFromBuildCommand(this Mock<IQueryCommandBuilder> builder, IQueryCommand command, string query = null)
{
    if(query == null)
        builder.Setup(b => b.BuildCommand(It.IsAny<string>())).Returns(command);
    else
        builder.Setup(b => b.BuildCommand(query)).Returns(command);
}

然后我可以这样调用它

var command = new Mock<IQueryCommand>();
var builder = new Mock<IQueryCommandBuilder>();
builder.ReturnFromBuildCommand(command.Object);

或者

string query = "SELECT Name FROM Persons;";
builder.ReturnFromBuildCommand(command.Object, query);

取决于我是否关心参数。

最佳答案

Setup mock 的方法接受一个表达式,然后 Moq 框架解构该表达式以确定被调用的方法及其参数。然后它设置一个拦截器来匹配参数。

您可以在 Mock 中看到它来源:

    internal static MethodCallReturn<T, TResult> Setup<T, TResult>(
        Mock<T> mock,
        Expression<Func<T, TResult>> expression,
        Condition condition)
        where T : class
    {
        return PexProtector.Invoke(() =>
        {
            if (expression.IsProperty())
            {
                return SetupGet(mock, expression, condition);
            }

            var methodCall = expression.GetCallInfo(mock);
            var method = methodCall.Method;
            var args = methodCall.Arguments.ToArray();

            ThrowIfNotMember(expression, method);
            ThrowIfCantOverride(expression, method);
            var call = new MethodCallReturn<T, TResult>(mock, condition, expression, method, args);

            var targetInterceptor = GetInterceptor(methodCall.Object, mock);

            targetInterceptor.AddCall(call, SetupKind.Other);

            return call;
        });
    }

在这里args类型为 Expression[] .

(引用:https://github.com/moq/moq4/blob/master/Source/Mock.cs#L463)

args数组被传递到 Moq 类型的构造函数中 MethodCallReturn作为参数 arguments .该构造函数(通过基类 MethodCall )使用 MatcherFactory.Create 生成参数匹配器. (引用:https://github.com/moq/moq4/blob/master/Source/MethodCall.cs#L148)

事情开始变得有趣了! 在 MatcherFactory.Create 方法中,它试图通过查看 Expression.NodeType 来确定参数表达式的类型。和/或根据已知类型检查它,例如 MatchExpression (这就是 Is.Any<string>() 之类的东西)。 (引用:https://github.com/moq/moq4/blob/master/Source/MatcherFactory.cs#L54)

让我们退后一步。在您的具体情况下,代码 query ?? Is.Any<string>()被编译成一个表达式本身——就像这个丑陋的困惑(由 dotPeek 反编译器生成):

(Expression) Expression.Coalesce((Expression) Expression.Field((Expression) Expression.Constant((object) cDisplayClass00, typeof (Extension.\u003C\u003Ec__DisplayClass0_0)), 
 FieldInfo.GetFieldFromHandle(__fieldref (Extension.\u003C\u003Ec__DisplayClass0_0.query))), 
(Expression) Expression.Call((Expression) null, (MethodInfo) MethodBase.GetMethodFromHandle(__methodref (It.IsAny)), new Expression[0]))

这就是第一个参数的样子。您可以重写代码以更好地表达 Moq 看到的内容,如下所示:

    public static void ReturnFromBuildCommand(this Mock<IQueryCommandBuilder> builder, IQueryCommand command, string query = null)
    {
        Expression<Func<IQueryCommandBuilder, IQueryCommand>> expressOfFunc = commandBuilder => (commandBuilder.BuildCommand(query ?? It.IsAny<string>()));

        var methodCall = expressOfFunc.Body as MethodCallExpression;
        var args = methodCall.Arguments.ToArray();
        var nodeType = args[0].NodeType;

        builder.Setup(expressOfFunc)
            .Returns(command);

    }

如果下断点,可以看到nodeType的值是Coalesce .现在,返回并将其更改为仅使用 query , 和 nodeType变成 MemberAccess .使用 It.IsAny<string>() , 和 nodeTypeCall .

这解释了这三种方法之间的差异,以及为什么它不像您预期​​的那样起作用。至于为什么会触发null老实说,我不清楚,但是无论匹配器来自 MatcherFactory.CreateMatcher好像觉得null是您的模拟配置的有效值。

关于c# - 为什么是??运算符(operator)不在最小起订量设置方法中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44942162/

相关文章:

c++ - 我应该写 `0x0` 还是 `0` 而不是 NULL?

ios - 为什么这个变量是 "nil",即使我有一个 "if"语句检查它不是

c# - 使用最小起订量设置方法以返回对象列表但得到空值

c# - 使用 Moq 验证具有正确命令参数的 CommandHandler 方法调用

c# - Azure 云服务角色实例 - 自动缩放 - 更改事件未触发

C# DependencyProperty - 对复杂类型使用默认属性

php - protected $var = null;与 protected $var;

c# - 模拟对象在单元测试中为空

c# - 在 GitHub 页面中使用 ASP.NET

c# - 无论 .NET 版本如何,使用相同种子第 n 次调用 Random.Next() 是否总是产生相同的数字?