2011-05-23 114 views
18

什么可能导致It.IsAny<string>()在每次调用时返回null?假设它被设计为返回一个非空字符串,我不正确吗?Moq - It.IsAny <string>()总是返回null

以下是用法 - 其中Login方法为空的第二个参数(连接字符串)引发ArgumentNullException。我假设It.IsAny<string>()将提供一个非空字符串,它将绕过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."); 

回答

24

好,It.IsAny<TValue>刚刚返回调用Match<TValue>.Create的结果 - 这反过来又返回default(TValue)。对于任何引用类型,这将为空。

不清楚你是否真的把它称为正确的对象 - 你不应该在模拟而不是实际的代码上调用它吗?

我所见过的所有样本都在mock.Setup调用中使用It.IsAny。你能提供更多关于你如何使用它的信息吗?

+0

啊,我明白了。我已经为这个问题添加了完整的测试。我使用它既是为了我的模拟,也是为了一个真实的物体。但它听起来像它不适用于实际的物体? – Jeremy 2011-05-23 14:47:39

+1

@Jeremy:不,这个想法是,你将真实值(以及样本值)传递给你的真实代码。 'It.IsAny'旨在验证从您的真实代码传递给您的模拟值。 – 2011-05-23 14:48:48

+0

知道了 - 所以我一直在想它作为一种数据生成技术......但它并不是为此而设计的。谢谢! – Jeremy 2011-05-23 14:59:16

2

It.IsAny用于匹配您的Returns()Callback()中的代码,用于控制推送到测试中的代码。

10

不,It.IsAny用于在您的设置中指定传递的ANY字符串将匹配。你可以做你的设置,以便如果你的方法只用一个特定的字符串调用,它会返回。试想一下:

myMock.Setup(x => x.DoSomething(It.IsAny<string>()).Return(123); 
myMock.Setup(x => x.DoSomething("SpecialString").Return(456); 
无论是使用模拟,然后将得到取决于被调用DoSomething的当模拟传递参数不同的值

。验证方法调用时,您可以执行相同的操作:

myMock.Verify(x => x.DoSomething(It.IsAny<string>())); // As long as DoSomething was called, this will be fine. 
myMock.Verify(x => x.DoSomething("SpecialString")); // DoSomething MUST have been called with "SpecialString" 

另外,我看到您编辑了您的问题。相反的:

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

做到这一点:

mockApiHelper.Verify(x => x.Connect(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once()); // Change times to whatever you expect. If you expect particular values, replace the relevent It.IsAny<string() calls with those actual vaules.