gpt4 book ai didi

c# - Moq ReturnsAsync() 带参数

转载 作者:IT王子 更新时间:2023-10-29 04:00:14 26 4
gpt4 key购买 nike

我正在尝试像那样模拟存储库的方法

public async Task<WhitelistItem> GetByTypeValue(WhitelistType type, string value)

使用 Moq ReturnsAsync,如下所示:

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();
});

但我在“... ReturnsAsync((WhitelistType type...):

Cannot convert lambda expression to type 'Model.WhitelistItem' because it is not a delegate type

WhitelistType 是一个像这样的枚举:

public enum WhitelistType
{
UserName,
PostalCode
}

我按小时搜索,但没有找到我的问题的任何答案。

有什么线索吗?

最佳答案

Moq v4.5.28 开始

您可以将 ReturnsAsync 与 lambda 一起使用,就像问题的代码示例中一样。无需再使用 Task.FromResult()。您只需需要指定 lambda 委托(delegate)参数的类型。否则你会得到同样的错误信息:

Cannot convert lambda expression to type 'Model.WhitelistItem' because it is not a delegate type

举个例子,以下适用于最新版本的 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();
});

在 Moq v4.5.28 之前(答案由 Alexei Levenkov 提供)

您必须将 ReturnsTask.FromResult 一起使用:

.Returns((WhitelistType type, string value) =>
{
return Task.FromResult(
(from item in whitelist
where item.Type == type && item.Value == value
select item).FirstOrDefault()
);
});

关于c# - Moq ReturnsAsync() 带参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31527394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com