How To Perform Logic In Your Moq Returns

I recently needed to test a method that took in a string and a list of integers, and then return a matching object the input ID matched the ID in the database.  After a quick Google, I couldn’t find how to do this easily, so here it’s a quick code example.

If you need to perform this sort of unit test, then you have several options.  The Callback method is a possibility, but the easiest one is to perform logic in the return method itself.

The Test Class

public MyClass Method(string name, List<int> ids)
{
}

The Mock Database Store

var store = new List<MyObject>
{
new MyObject
{
ID = 1
},
new MyObject
{
ID = 2
}
};

The Test Setup

repo.Setup(x => x.Method(It.IsAny<string>(), It.IsAny<List<int>>()))
.Returns((string code, List<int> publisherIds) =>
{
return store.FirstOrDefault(x => publisherIds.Contains(x));
});

In the snippet above, we have a method that takes a string and a list of int’s as the input parameters.  In the MOQ return method, we need to define two parameters that match the input parameters, so we can get access to the data that will get passed into it when it gets called.

In the return method, we can do a => {} and then add in any logic we want.  In my example, I’m returning the first value in the store that contains any value in my requested Id list.  When your code gets called your object will now be returned.

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *