Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Task<IEnumerable<T>> with NSubstitute

I'm having issues trying to get NSubstitute to return an IEnumerable interface from a Task.

The factory I'm mocking:

public interface IWebApiFactory<T> : IDisposable
{
    <T> GetOne(int id);
    Task<IEnumerable<T>> GetAll();
    Task<IEnumerable<T>> GetMany();
    void SetAuth(string token);
}

The test method:

[TestMethod]
public async Task TestMutlipleUsersAsViewResult()
{
    var employees = new List<EmployeeDTO>()
    {
        new EmployeeDTO(),
        new EmployeeDTO()
    };

    // Arrange
    var factory = Substitute.For<IWebApiFactory<EmployeeDTO>>();
    factory.GetMany().Returns(Task.FromResult(employees));
}

The error I am getting is:

cannot convert from 'System.Threading.Tasks.Task> to System.Func>>

Is this an issue with me passing a list, as a posed to IEnumerable even though List is IEnumerable?

Edit:

These are the functions within NSubstitute

public static ConfiguredCall Returns<T>(this T value, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese);
public static ConfiguredCall Returns<T>(this T value, T returnThis, params T[] returnThese);
like image 253
nik0lai Avatar asked Feb 19 '15 11:02

nik0lai


1 Answers

None of the overloads is a good match for the value you passed. The second signature, public static ConfiguredCall Returns<T>(this T value, T returnThis, params T[] returnThese); expect a value of the same type as the function's return type so it isn't the best match.

The simplest way to overcome this is to change the declaration of employees to IEnumerable<EmployeeDTO> :

IEnumerable<EmployeeDTO> employees = new List<EmployeeDTO>()
{
    new EmployeeDTO(),
    new EmployeeDTO()
};
like image 153
Panagiotis Kanavos Avatar answered Nov 20 '22 03:11

Panagiotis Kanavos