我正在尝试对返回任务>的方法进行单元测试:
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参数1:无法转换 &#39;&System.Threading.Tasks.Task LT; System.Collections.Generic.List&LT; UserQuery.MyModel&GT;&#39; 至 &#39;&System.Threading.Tasks.Task LT; System.Collections.Generic.IList&LT; UserQuery.MyModel&GT;&#39;
我做错了什么?
答案 0 :(得分:9)
您可以使用ReturnsAync方法:
IList<MyModel> expected = new List<MyModel>() { new MyModel { Name = "Test" }};
mockRepo.Setup(x => x.GetAll()).ReturnsAsync(expected);
答案 1 :(得分:2)
很快就发布了,发现Moq有ReturnsAsync方法。
mockRepo.Setup(x => x.GetAllAsync()).ReturnsAsync((new List<MyModel>() { new MyModel { Name = "Test" } });
工作正常。
答案 2 :(得分:0)
只需将您的列表转发给IList:
Task.FromResult((IList<MyModel>) new List<MyModel>() { new MyModel { Name = "Test" } })
或者定义通用参数:
Task.FromResult<IList<MyModel>>(new List<MyModel>() { new MyModel { Name = "Test" } })
答案 3 :(得分:0)
将结果投射到IList
Task.FromResult((IList)new List() { new MyModel { Name = "Test" } });
答案 4 :(得分:0)
您的问题是,您的方法应该返回Task<IList>
并且您正在返回Task<List>
您无法做到这一点 - 它们属于不同类型且不支持逆变或协方差。您需要转换返回类型
mockRepo.Setup(x => x.GetAllAsync()).Returns(Task.FromResult((IList<MyModel>)new List<MyModel>() { new MyModel { Name = "Test" } }));