Half the links I try off the Moq page are broken, including the one for their official API documentation. So I'll ask here.
I have successfully used a single "catch all" parameter like so:
mockRepo.Setup(r => r.GetById(It.IsAny<int>())).Returns((int i) => mockCollection.Where(x => x.Id == i).Single());
However I can't figure out how to achieve the same behavior with multiple parameters.
mockRepo.Setup(r => r.GetByABunchOfStuff(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>())).Returns( ..... );
The ....
is the part I can't figure out.
Edit in response to Jordan:
The problem is how to represent the 3 parameters instead of just one.
How to turn:
(int i) => mockCollection.Where(x => x.Id == i)
into:
(int i), (string s), (int j) => mockCollection.Where(x => x.Id == i && x.SomeProp == s && x.SomeOtherProp == j)
Creating a mock object with multiple interfaces is easy with Moq. First, we create the mock object for a single interface in the usual manner. We can then use the mock's As method to add interfaces. "As" is a generic method with a type parameter that defines the interface that you wish to add.
When you’re mocking a method that’s called multiple times, you may want to change the behavior of the method each time it’s called. The way you do this with Moq is by using SetupSequence (), like this: mock.SetupSequence (t => t.ShouldRetry ()).Returns (true).Returns (true).Returns (false); Code language: C# (cs)
When the mocked method has multiple parameters, you may only be interested in examining some of the parameters. In that case, you can use It.IsAny<T> () to accept any values for the other parameters that you’re not interested in.
a method was called with specific arguments. Using the Moq framework, we can achieve spying with Verifiable and Callback. With these two tools, we can verify that methods were called and pluck out the variables that were used when making the call to make Assertions on them.
It's pretty much the same as with a single parameter:
.Returns
(
(int i, string s, int x)
=> mockCollection.Where
(
x => x.Id == i
&& x.SomeProp == s
&& x.SomeOtherProp == x
)
);
Or use the generic variant of returns:
.Returns<int, string, int>
(
(i, s, x)
=> mockCollection.Where
(
x => x.Id == i
&& x.SomeProp == s
&& x.SomeOtherProp == x
)
);
I think what you need is:
mockRepo
.Setup(r => r.GetByABunchOfStuff(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()))
.Returns<int,string,int>((id, someProp, someOtherProp) =>
mockCollection.Where(x => x.Id == i && x.SomeProp == s && x.SomeOtherProp == x));
Do you mean how do you write the correct lambda?
mockRepo.Setup(r => r.GetByABunchOfStuff(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>()))
.Returns((int i, string s, int i2) => doSomething() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With