How to make fun of a method returning a <IEnumerable <T>> task using Task <List <T>>?
I am trying to configure the unit test initializer (in Moq) where the interface method is mixed:
public interface IRepository { Task<IEnumerable<myCustomObject>> GetSomethingAsync(string someStringParam); } ... [TestInitialize] public void Initialize() { var repoMock = new Mock<IRepository>(); var objectsList = new List<myCustomObject>() { new myCustomObject("Something"), new myCustomObject("Otherthing") } repoMock.Setup<Task<IEnumerable<myCustomObject>>>( rep => rep.GetSomethingAsync("ThisParam") ).Returns(Task.FromResult(objectsList)); //error here } The problem I am facing cannot understand how to return the objectsList method. In practice, this, of course, works great because List implements IEnumerable, but it doesn't seem to work when it is wrapped in Task, in Moq. The error I get is related to the Returns() method:
Argument 1: cannot convert from 'System.Threading.Tasks.Task< System.Collections.Generic.List<myCustomObject>>' to 'System.Threading.Tasks.Task< System.Collections.Generic.IEnumerable<myCustomObject>>' As a workaround, I can create another method that just creates a List<myObj> and returns it as IEnumerable<myObj> , but I feel there must be a different way to handle what is cleaner.
So, how would I do this without creating a helper method?
You need to specify <IEnumerable<myCustomObject>> in Task.FromResult , for example:
[TestInitialize] public void Initialize() { var repoMock = new Mock<IRepository>(); var objectsList = new List<myCustomObject>() { new myCustomObject("Something"), new myCustomObject("Otherthing") } repoMock.Setup<Task<IEnumerable<myCustomObject>>>( rep => rep.GetSomethingAsync("ThisParam") ).Returns(Task.FromResult<IEnumerable<myCustomObject>>(objectsList)); } Alternatively, you can declare your objectList as <IEnumerable<myCustomObject>> before assigning it from List<myCustomObject> . The implementation of the previous sentence is not required.