简体   繁体   中英

Newbie question about mocking and moq framework

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?

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.

Yes, you can Use It.IsAny()

for example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM