相关疑难解决方法(0)

我如何告诉Moq返回任务?

我有一个声明的界面

Task DoSomethingAsync();
Run Code Online (Sandbox Code Playgroud)

我正在使用MoqFramework进行测试:

[TestMethod()]
public async Task MyAsyncTest()
{
   Mock<ISomeInterface> mock = new Mock<ISomeInterface>();
   mock.Setup(arg => arg.DoSomethingAsync()).Callback(() => { <my code here> });
   ...
}
Run Code Online (Sandbox Code Playgroud)

然后在我的测试中我执行调用的代码await DoSomethingAsync().而且测试在这条线上失败了.我究竟做错了什么?

c# unit-testing moq task-parallel-library

291
推荐指数
3
解决办法
11万
查看次数

Moq使用参数返回Async()

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

public async Task<WhitelistItem> GetByTypeValue(WhitelistType type, string value)
Run Code Online (Sandbox Code Playgroud)

使用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();
                                    });
Run Code Online (Sandbox Code Playgroud)

但我在行中收到此错误"... ReturnsAsync((WhitelistType type ...):

无法将lambda表达式转换为类型'Model.WhitelistItem',因为它不是委托类型

WhitelistType是这样的枚举:

public enum WhitelistType
    {
        UserName,
        PostalCode
    }
Run Code Online (Sandbox Code Playgroud)

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

有线索吗?

c# unit-testing moq

40
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×2

moq ×2

unit-testing ×2

task-parallel-library ×1