romantitov / MockQueryable

Mocking Entity Framework Core operations such ToListAsync, FirstOrDefaultAsync etc
MIT License
791 stars 77 forks source link

IQueryable mock throws on ToListAsync() #32

Closed dotcom9 closed 4 years ago

dotcom9 commented 4 years ago

This package looks useful. Unfortunately however, it doesn't solve the problem of calling async methods on IQueryable objects.

For example, calling .ToListAsync() on my mock queryable still throws:

System.InvalidOperationException : The source IQueryable doesn't implement IAsyncEnumerable<MyClass>. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.

public class ApplicationControllerTests
{
    private static IEnumerable<Application> GetApplications() => new[]
    {
        new Application
        {
            ...
        },
        ...
    };

    [Fact]
    public async Task GetApplicationsReturnsExpected()
    {
        //Arrange
        var applications = GetApplications()
            .AsQueryable()
            .BuildMock();

        var fixture = ApplicationControllerFixture.Create();
        fixture.QueryService
            .Setup(s => s.GetApplications())
            .Returns(applications.Object);

        //Act
        var result = await fixture.Controller.GetApplications();

        //Assert
        var response = Assert.IsType<OkObjectResult>(result);
    }
}

[ApiController]
public class ApplicationController : ControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetApplications()
    {
        LogActivity(nameof(GetApplications), Request);
        var list = await QueryService.GetApplications(ClientId)
                        .ToListAsync();
        return Ok(list);
    }
}
dotcom9 commented 4 years ago

Apologies, this was due to an error in my code.

sstream17 commented 4 years ago

@dotcom9 could you please explain the error in your code and how you fixed it?