views:

72

answers:

2

I've been using Moq framework in c# for mocking in unit tests however there is one thing I dont complete understand yet. I have this line of code

var feedParserMock = new Mock<ApplicationServices.IFeedParser>();
feedParserMock.Setup(y => y.ParseFeed(csv)).Returns(items).Verifiable();

The second line does it mean it will only return the value if the parameter passed is the same? because the parameter that I pass to ParseFeed inside my controller is build inside the controller and I dont have access to it in the unit test. Currently the method is returning null, is there any way to specify I want to return my items variable no matter what the parameter is?

+2  A: 

Yes, you can Use It.IsAny()

for example

feedParserMock.Setup(y => y.ParseFeed(It.IsAny<string>())).Returns(items).Verifiable();
WDuffy
+7  A: 

Yes. Moq provides the It static class that has helper methods for specifying parameters that satisfy certain criteria. Your example could be:

feedParserMock.Setup(y => y.ParseFeed(It.IsAny<string>())).Returns(items).Verifiable();

Then Moq will match your setup, given that the parameter is of the specified type and non-null (I chose string here, you should of course replace that with the correct type of your parameter in order for the code to compile).

You can also pass a delegate that Moq will evalute in order to determine if the setup is a match. Example:

feedParserMock.Setup(y => y.ParseFeed(It.Is<string>(s => s.Length > 3));

This will match any method invocations on ParseFeed, where the parameter is a string with a Length larger than 3.

Check out the "Matching arguments" section of the Moq Quickstart guide to learn more.

driis
'It' is where it's at. Matching arguments is one of my favorite features of Moq.
Dan Bryant