From Moq v4.5.28 onwards
You can use ReturnsAsync
with lambdas, exactly as in the code example of the question. No need to use Task.FromResult()
any more. You just need to specify the types of the lambda delegate arguments. Otherwise you will get the same error message:
Cannot convert lambda expression to type ‘Model.WhitelistItem’ because it is not a delegate type
To give an example, the following works with the latest version of Moq:
whitelistRepositoryMock.Setup(w => w.GetByTypeValue(It.IsAny<WhitelistType>(), It.IsAny<string>()))
.ReturnsAsync((WhitelistType type, string value) =>
{
return (from item in whitelist
where item.Type == type && item.Value == value
select item).FirstOrDefault();
});
Before Moq v4.5.28 (answer provided by Alexei Levenkov)
You have to use Returns
with Task.FromResult
:
.Returns((WhitelistType type, string value) =>
{
return Task.FromResult(
(from item in whitelist
where item.Type == type && item.Value == value
select item).FirstOrDefault()
);
});