Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ...
}
like image 435
Elisabeth Avatar asked Jun 26 '26 00:06

Elisabeth


1 Answers

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>()));
like image 60
i3arnon Avatar answered Jun 28 '26 17:06

i3arnon