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?
You can use ReturnsAync method:
IList<MyModel> expected = new List<MyModel>() { new MyModel { Name = "Test" }};
mockRepo.Setup(x => x.GetAll()).ReturnsAsync(expected);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With