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
source share
5 answers

You can use the ReturnsAync method:

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

, Moq ReturnsAsync.

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

.

+1

IList:

Task.FromResult((IList<MyModel>) new List<MyModel>() { new MyModel { Name = "Test" } })

:

Task.FromResult<IList<MyModel>>(new List<MyModel>() { new MyModel { Name = "Test" } })
0
source

Pass the result IList

Task.FromResult((IList)new List() { new MyModel { Name = "Test" } });
0
source

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
source

Source: https://habr.com/ru/post/1648968/


All Articles