我正在尝试对返回任务>的方法进行单元测试:
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; } }
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);