Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you store an 'It' matcher object as a variable, instead of defining it inline? (Moq)

Tags:

c#

.net

mocking

moq

I'm mocking some objects using Moq, and some of them can have fairly lengthy parameter-collection request objects passed in as arguments.

For ease of re-use and style, I'd like to be able to store these requests, with specific arguments, for use in the mocking setup. 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 doesn't seem to 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 no joy there either. Is there any way I can save an Itstyle object as a variable? Or am I missing some other obvious way of handling this?

like image 776
Michael Rosefield Avatar asked Dec 10 '14 13:12

Michael Rosefield


People also ask

How do you mock a method in MOQ?

First, we instantiate the FakeDbArticleMock class and indicate which setup we want to use for this test. Then, it is necessary to instantiate the repository we want to test and inject the mock instance into it. Finally, we call the method we are testing and assert the results.

Which method on expect () is used to count the number of times a method to have been called?

Using Verify This is probably the best way to go as Verify is designed for this exact purpose - to verify the number of times a method has been called.

Whats is MOQ?

MOQ is the amount of product a supplier or seller requires a purchaser to buy at one time. An MOQ can cause an ecommerce business to purchase more inventory than they need at one time, causing them to be nowhere near their EOQ.


1 Answers

And... I've found the answer. It's Moq's Match (Class):

Creating a custom matcher is straightforward. You just need to create a method that returns a value from a call to Create with your matching condition and optional friendly render 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 setup invocation:

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

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

like image 153
Michael Rosefield Avatar answered Sep 28 '22 04:09

Michael Rosefield