I'm trying to see if Moq is something I'd like to use in a new project as the other mocking frameworks I've used are challenging IMHO. So for instance, I have a method as such:
IEnumerable<PickList> GetPickLists();
I'm not sure how I'm supposed to mock this... I've tried something like this, but I'm getting compliation errors (I know the following Returns() isn't correct, but can't figure out what to put in the Returns body:
var mockCrm = new Mock<ICrmProvider>();
mockCrm.Setup<IEnumerable<PickList>>(foo => foo.GetPickLists())
.Returns<IEnumerable<PickList>>({});
Also, trying to mock something like these two methods:
CustomerSyncResult ApplyActions(IEnumerable<CustomerAction> actions);
IEnumerable<Customer> GetCustomers(IEnumerable<string> crmIDs, IEnumerable<string> emails);
I know I'm asking a blanket question, but I'm having a heck of a time getting started. The CHM in the download doesn't have enough samples for me and some of the tutorials out there seem to be using obsolete methods as well as not covering enumerations which makes it tricky for me :(
Any tips would be greatly appreciated.
Try
mockCrm.Setup(x => x.GetPickLists())
.Returns(new List<PickList>());
The QuickStart is a good reference.
Some examples for the other methods:
mockCrm.Setup(x => x.ApplyActions(It.IsAny<IEnumerable>()))
.Returns(new CustomerSyncResult());
mockCrm.Setup(x => x.GetCustomers(It.IsAny<IEnumerable>(),
It.IsAny<IEnumerable>()))
.Returns(new List<Customers>());
As an aside, make the IEnumerable generic in your original interface for better type safety.
You can also use the new Moq v4 functional specifications:
var list = new List<PickList> { new PickList() };
ICrmProvider crm =
Mock.Of<ICrmProvider>(
x =>
x.GetPickLists() == list);
That is not as well documented currently. Note that you no longer have to write mock.Object
. Some links:
The exact syntax (using It.Is, the contents of the lists, etc.) will depend on what you're trying to accomplish. It.IsAny
will match any argument, which will make things easier when dealing with sequence or collection parameters.
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