How can I mock a method that returns a <IList <>> task?
I am trying to use the unit test method, which returns Task>:
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; }
}
But the task return method generates a compiler error:
CS1503 Argument 1: cannot be converted from 'System.Threading.Tasks.Task <System.Collections.Generic.List <UserQuery.MyModel>' to 'System.Threading.Tasks.Task <System.Collections.Generic.IList <UserQuery.MyModel > '
What am I doing wrong?
+4
5 answers
Well, your problem is that your method should return Task<IList>, and you return Task<List>, you cannot do this - they are of different types, and they do not support contravariance or covariance. You need to specify the type of return
mockRepo.Setup(x => x.GetAllAsync()).Returns(Task.FromResult((IList<MyModel>)new List<MyModel>() { new MyModel { Name = "Test" } }));
0