问题描述
您好,当我看到这段代码时,我已经使用 moq 有一段时间了.
Hi I've been using moq for a while when I see this code.
我必须在我的一个回购中设置回报.
I have to setup a return in one of my repo.
mockIRole.Setup(r => r.GetSomething(It.IsAny<Guid>(), It.IsAny<Guid>(),
It.IsAny<Guid>())).Returns(ReturnSomething);
我有三个参数,我只是在网上的一篇文章或博客中看到这些.
I have three parameters and I just saw these in one of articles or blog on the net.
It.Is<> 或 It.IsAny<> 对对象有什么用?如果我可以使用 Guid.NewGuid() 或其他类型,那么为什么要使用 It.Is?
What is the use of It.Is<> or It.IsAny<> for an object? if I could use Guid.NewGuid() or other types then why use It.Is?
很抱歉,我不确定我的问题是否正确,或者我是否缺少一些测试知识.不过好像都没什么问题.
I'm sorry I'm not sure if my question is right or am I missing some knowledge in testing. But it seems like there is nothing wrong either way.
推荐答案
使用 It.IsAny<>、It.Is<> 或变量 all服务于不同的目的.在设置或验证方法时,它们提供了越来越具体的方法来匹配参数.
Using It.IsAny<>, It.Is<>, or a variable all serve different purposes. They provide increasingly specific ways to match a parameter when setting up or verifying a method.
使用 It.IsAny<> 设置的方法将匹配您提供给该方法的 any 参数.因此,在您的示例中,以下调用都将返回相同的内容(ReturnSomething):
The method set up with It.IsAny<> will match any parameter you give to the method. So, in your example, the following invocations would all return the same thing (ReturnSomething):
role.GetSomething(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
Guid sameGuid = Guid.NewGuid();
role.GetSomething(sameGuid, sameGuid, sameGuid);
role.GetSomething(Guid.Empty, Guid.NewGuid(), sameGuid);
传递的 Guid 的实际值无关紧要.
It doesn't matter the actual value of the Guid that was passed.
It.Is<> 构造对于设置或验证方法很有用,可让您指定与参数匹配的函数.例如:
The It.Is<> construct is useful for setup or verification of a method, letting you specify a function that will match the argument. For instance:
Guid expectedGuid = ...
mockIRole.Setup(r => r.GetSomething(
It.Is<Guid>(g => g.ToString().StartsWith("4")),
It.Is<Guid>(g => g != Guid.Empty),
It.Is<Guid>(g => g == expectedGuid)))
.Returns(ReturnSomething);
这允许您限制该值,而不仅仅是任何值,但允许您对您接受的内容宽容.
This allows you to restrict the value more than just any value, but permits you to be lenient in what you accept.
当您使用变量设置(或验证)方法参数时,您是在说您想要完全该值.使用另一个值调用的方法永远不会匹配您的设置/验证.
When you set up (or verify) a method parameter with a variable, you're saying you want exactly that value. A method called with another value will never match your setup/verify.
Guid expectedGuids = new [] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
mockIRole.Setup(r => r.GetSomething(expectedGuids[0], expectedGuids[1], expectedGuids[2]))
.Returns(ReturnSomething);
现在只有一种情况 GetSomething 将返回 ReturnSomething:当所有 Guid 与您设置的预期值匹配时.
Now there's exactly one case where GetSomething will return ReturnSomething: when all Guids match the expected values that you set it up with.
这篇关于为什么使用 It.is<>或It.IsAny<>如果我可以定义一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)