起订量It.Is<>不匹配 [英] Moq It.Is<> not matching

查看:178
本文介绍了起订量It.Is<>不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

hub.MockedUserRepository.Setup(r => r.Update(It.IsAny<ControllUser>()))
                        .Callback((ControllUser usr) => Console.WriteLine("NULL = " + (usr.Zombies[0].ConnectionId == null)))
                        .Verifiable();



将打印

Will print

NULL = TRUE

NULL = True

,所以我用这个匹配会抓住它想:

So i am thinking using this matching will catch it:

var zombieDisconnectParameterMatcher = It.Is<ControllUser>(x => x.Zombies[0].ConnectionId == null);
hub.MockedUserRepository.Setup(r => r.Update(zombieDisconnectParameterMatcher))
                        .Callback((ControllUser usr) => Console.WriteLine("NULL = " + (usr.Zombies[0].ConnectionId == null)))
                        .Verifiable();



但事实并非如此。

But it does not.

为什么?

推荐答案

通过查看的,它与表达式树做的。我喜欢的问题;他们可以是相当令人费解。如果您将在下面的方法定义来看一看:

By looking at the source code of It, it has to do with expression trees. I like the question; they can be quite puzzling. If you would take a look at the following method definitions:

public static TValue It.Is<TValue>(Expression<Func<TValue, bool>> match)
{
        return Match<TValue>.Create(
                value => match.Compile().Invoke(value),
                () => It.Is<TValue>(match));
}

public static T Match.Create<T>(Predicate<T> condition, Expression<Func<T>> renderExpression)
{
        // ...
        return default(T);
}

如果您将执行以下命令行:

If you would execute the following line:

var zombieDisconnectParameterMatcher = It.Is<ControllUser>(x => x.Zombies[0].ConnectionId == null);



然后 It.Is< >将尝试调用一个名为 Match.Create<方法ControllUser>(),返回 ControllUser 的默认值。我假设 ControllUser 是一类,因此 zombieDisconnectParameterMatcher 。你应该能够看到这个与调试。那么究竟是什么你打电话是:

Then It.Is<ControllUser>() will try to call a method called Match.Create<ControllUser>(), which returns the default of ControllUser. I assume ControllUser is a class and therefore zombieDisconnectParameterMatcher will be null. You should be able to see this with the debugger. So what actually you're calling is:

hub.MockedUserRepository.Setup(r => r.Update(null))
    .Callback((ControllUser usr) => Console.WriteLine("NULL = " + (usr.Zombies[0].ConnectionId == null)))
    .Verifiable();



与非执行更新方法时-null ControllUser ,回调不会触发。因为它不是空不匹配的标准。你也看到验证失败。

When executing the Update method with a non-null ControllUser, the callback will not trigger. It doesn't match the criteria since it's not null. Also you would see the verification fail.

要解决此问题,无论是内联 zombieDisconnectParameterMatcher 变量,或使其一个表达式类型的变量(如表达式来; FUNC。< ...>> )。使得它保持一个表达和将不被执行,但将通过模拟而不是进行评价。

To resolve this issue, either inline the zombieDisconnectParameterMatcher variable, or make it an expression typed variable (eg. Expression<Func<...>>). So that it stays an expression and will not be executed, but will be evaluated by the mock instead.

这篇关于起订量It.Is&LT;&GT;不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆