Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock a method that returns a Task<IList<>>?

I am trying to unit test a method that returns a 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 returning method generates a compiler error:

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>'

What am I doing wrong?

like image 545
Magnus Johansson Avatar asked Jul 24 '16 21:07

Magnus Johansson


2 Answers

You can use ReturnsAync method:

IList<MyModel> expected = new List<MyModel>() { new MyModel { Name = "Test" }};
mockRepo.Setup(x => x.GetAll()).ReturnsAsync(expected);
like image 51
Ufuk Hacıoğulları Avatar answered Oct 25 '22 12:10

Ufuk Hacıoğulları


Posted to soon, found out that Moq has the ReturnsAsync method.

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

Works fine.

like image 26
Magnus Johansson Avatar answered Oct 25 '22 10:10

Magnus Johansson