Can you save the "It" matcher object as a variable, instead of defining it in a string? (Moq)

I mock some objects using Moq, and some of them may have fairly long parameter set request objects, passed as arguments.

For ease of reuse and style, I would like to be able to store these requests with specific arguments for use in a mocking setting. For example:

mockedObject .Setup(mo => mo.GetBobbins(It.Is<GetBobbinsRequest> (r.Parameter1 == value1 && [...] & r.ParameterN == valueN)) .Returns(someBobbins); 

becomes:

 var request = It.Is<GetBobbinsRequest> (r.Parameter1 == value1 && [...] & r.ParameterN == valueN); mockedObject .Setup(mo => mo.GetBobbins(request)) .Returns(someBobbins); 

But that does not work. I also tried:

 Func<GetBobbinsRequest> request = () => It.Is<GetBobbinsRequest> (r.Parameter1 == value1 && [...] & r.ParameterN == valueN); mockedObject .Setup(mo => mo.GetBobbins(request())) .Returns(someBobbins); 

But there is no joy. Is there a way to save an It style object as a variable? Or am I missing another obvious way to handle this?

+7
c # moq mocking
source share
2 answers

And ... I found the answer. This is the Moq Match (class):

Creating a custom connector is simple. You just need to create a method that returns a value from the Create call with your matching condition and an optional friendly expression expression:

 [Matcher] public Order IsBigOrder() { return Match<Order>.Create( o => o.GrandTotal >= 5000, /* a friendly expression to render on failures */ () => IsBigOrder()); } 

This method can be used in any mock configuration call:

 mock.Setup(m => m.Submit(IsBigOrder()).Throws<UnauthorizedAccessException>(); 

http://www.nudoq.org/#!/Packages/Moq/Moq/Match(T)

+5
source share

A quick explanation of why what you have in your question does not work, as I wrote it before I saw your answer:

The It.Is call actually ends with returning default(T) each time , so saving it and then using it will be the same as simply passing null or regardless of the default value for the parameter type.

The reason it should be inline is because the It.Is call actually works by setting a static member in a "mock context" that the Setup call eventually gets around to use.

+4
source share

All Articles