Moq-It.IsAny< string>()始终返回null [英] Moq - It.IsAny<string>() always returning null

查看:73
本文介绍了Moq-It.IsAny< string>()始终返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么可能导致It.IsAny<string>()在每次调用时返回null?我以为它被设计为返回非空字符串是错误的吗?

What may cause It.IsAny<string>() to return null at every call? Am I incorrect in assuming that it is designed to return a non-null string?

这里是用法-Login方法将为第二个空参数(连接字符串)抛出ArgumentNullException.我以为It.IsAny<string>()将提供一个非null的字符串,它将绕过ArgumentNullException.

Here's the usage - where the Login method throws an ArgumentNullException for a null 2nd argument (connection string). I was assuming that It.IsAny<string>() would provide a non-null string, which would bypass the ArgumentNullException.

var mockApiHelper = new Mock<ApiHelper>();
mockApiHelper.Setup(m => m.Connect(It.IsAny<string>(), 
                                   It.IsAny<string>(), 
                                   It.IsAny<string>()));

var repositoryPlugin = new RepositoryPlugin(mockApiHelper.Object);
repositoryPlugin.Login(new CredentialsInfo(), It.IsAny<string>());

Assert.IsTrue(repositoryPlugin.LoggedIn, 
    "LoggedIn property should be true after the user logs in.");

推荐答案

好吧, It.IsAny<TValue> 仅返回调用 Match<TValue>.Create -依次返回default(TValue).对于任何引用类型,该值为null.

Well, It.IsAny<TValue> just returns the result of calling Match<TValue>.Create - which in turn returns default(TValue). That will be null for any reference type.

目前尚不清楚您是否真的在正确的对象上调用它-是不是应该在 mock 而不是实际代码上调用它?

It's not clear whether you're really calling it on the right object though - shouldn't you be calling it on the mock rather than on the real code?

我见过的所有示例在mock.Setup调用的上下文中都使用It.IsAny.您能否提供有关如何使用它的更多信息?

All the samples I've seen use It.IsAny in the context of a mock.Setup call. Could you give more information about how you're trying to use it?

这篇关于Moq-It.IsAny&lt; string&gt;()始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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