Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

c# - Why use It.is<> or It.IsAny<> if I could just define a variable?

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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);

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.

Defining a Variable

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);

Now there's exactly one case where GetSomething will return ReturnSomething: when all Guids match the expected values that you set it up with.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...