Elisabeth
Elisabeth

Reputation: 21206

Mock async Get method with MOQ

How do I get rid of this error message:

Error   5   Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<TGB.Business.DTO.SchoolyearDTO>>' to 'System.Collections.Generic.IEnumerable<TGB.Business.DTO.SchoolyearDTO>'. An explicit conversion exists (are you missing a cast?)   

I thought my Task.FromResult would fix that but no...

mockService.Setup<IEnumerable<SchoolyearDTO>>(c => c.GetSchoolyears()).Returns(
                    Task.FromResult(Enumerable.Empty<SchoolyearDTO>()));

public async Task<IEnumerable<SchoolyearDTO>> GetSchoolyearsAsync()
{
    var schoolyears = await ...
}

Upvotes: 3

Views: 1413

Answers (1)

i3arnon
i3arnon

Reputation: 116548

GetSchoolyearsAsync is an async method, so it returns a Task<IEnumerable<SchoolyearDTO>> and not just a IEnumerable<SchoolyearDTO>. You need to specify that in the type parameters for SetupGet

mockService.SetupGet<Task<IEnumerable<SchoolyearDTO>>>(c => c.GetSchoolyears()).
    Returns(Task.FromResult(Enumerable.Empty<SchoolyearDTO>()));

Upvotes: 4

Related Questions