加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何模拟返回Task>的方法?

发布时间:2020-12-15 08:00:14 所属栏目:百科 来源:网络整理
导读:我正在尝试对返回任务的方法进行单元测试: void Main(){ var mockRepo = new MockIRepository(); mockRepo.Setup(x = x.GetAll()).Returns(new ListMyModel() { new MyModel { Name = "Test" } }); // works mockRepo.Setup(x = x.GetAllAsync()).Returns(T
我正在尝试对返回任务>的方法进行单元测试:
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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读