c# - 如何模拟返回 Task<IList<>> 的方法?

标签 c# unit-testing asynchronous task moq

我正在尝试对返回任务的方法进行单元测试>:

void Main()
{
    var mockRepo = new Mock<IRepository>();
    mockRepo.Setup(x => x.GetAll()).Returns(new List<MyModel>() { new MyModel { Name = "Test" } });  // works

    mockRepo.Setup(x => x.GetAllAsync()).Returns(Task.FromResult(new List<MyModel>() { new MyModel { Name = "Test" } }));  // error

    var result = mockRepo.Object.GetAll();
    result.Dump();
}

public interface IRepository
{
    Task<IList<MyModel>> GetAllAsync();
    IList<MyModel> GetAll();
}

public class MyModel
{
    public string Name { get; set; }
}

但是 Task 返回方法会产生编译错误:

CS1503 Argument 1: cannot convert from 'System.Threading.Tasks.Task<System.Collections.Generic.List<UserQuery.MyModel>' to 'System.Threading.Tasks.Task<System.Collections.Generic.IList<UserQuery.MyModel>'

我做错了什么?

最佳答案

您可以使用 ReturnsAync 方法:

IList<MyModel> expected = new List<MyModel>() { new MyModel { Name = "Test" }};
mockRepo.Setup(x => x.GetAll()).ReturnsAsync(expected);

关于c# - 如何模拟返回 Task<IList<>> 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38556753/

相关文章:

javascript - node.js 在客户端 <--> Web 服务器流中的什么位置?

c# - @Html.ActionLink 带有链接的 id

php - 模拟 WP_REST_Request 对象

javascript - twitter typeahead.js process() 调用无法异步工作

javascript - Ember.js 观察者在异步更新后不触发

c++ - gtest 是否支持文件比较?

c# - 混淆后从 Settings.settings 文件读取

c# - 图像文件名未传递给 Controller ​​ mvc c#

c# - 关联引用未映射类 : System. Guid

python - 测试。使用堆叠参数化装饰器时定义预期结果的最佳方法?