Moq Returnsasync() with Parameters
I'm Trying to Mock a Repository's Method Like That Public Async Task Getbytypevalue(Whitelisttype Type, String Value) Using Moq Returnsasync, Like This: Static...
I'm trying to mock a repository's method like that
public async Task<WhitelistItem> GetByTypeValue(WhitelistType type, string value)
using Moq ReturnsAsync, like this:
static List<WhitelistItem> whitelist = new List<WhitelistItem>();
var whitelistRepositoryMock = new Mock<IWhitelistRepository>();
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();
});
but i'm getting this error in the line "... ReturnsAsync((WhitelistType type...):
Cannot convert lambda expression to type 'Model.WhitelistItem' because it is not a delegate type
WhitelistType is an Enum like that:
public enum WhitelistType
{
UserName,
PostalCode
}
I searched by hours and didn't found any answer to my problem.
Any clues?
2 Answers
Must Read
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();
});