11

我在一个方法中有一个查询:

private readonly IEntityReader<Customer> _reader;

public async Task<IEnumerable<Customer>> HandleAsync(GetCustomer query)
{
    var result = _reader.Query()
        .Include(customer => customer.Organization)
        .Where(customer => customer.Name == query.Name);

    return await result.ToListAsync();
}

哪个有这个单元测试:

[Fact]
public async Task HandleGetCustomer_ReturnsCustomer_WhenNameMatches()
{
    // Arrange
    var customers = new List<Customer>()
    {
        new Customer
        {
            Id = new Guid("d4e749ba-6874-40f4-9134-6c9cc1bc95fe"),
            Name = "John Doe",
            Age = 18,
            Organization = new Organization
            {
                Id = new Guid("b2ba06c9-5c00-4634-b6f7-80167ea8c3f1"),
                Name = "TheCompany",
                Number = 42
            }
        },
        new Customer
        {
            Id = new Guid("0679ceb5-3d4f-41f3-a1b0-b167e1ac6d7e"),
            Name = "Another Guy",
            Age = 39,
            Organization = new Organization
            {
                Id = new Guid("b2ba06c9-5c00-4634-b6f7-80167ea8c3f1"),
                Name = "TheCompany",
                Number = 42
            }
        }
    }.AsQueryable();

    var entityReader = new Mock<IEntityReader<Customer>>(MockBehavior.Strict);
    entityReader.Setup(reader => reader.Query()).Returns(customers);

    var query = new GetCustomer
    {
        Name = "John Doe"
    };

    var handler = new HandleGetCustomer(entityReader.Object);

    // Act
    var result = await handler.HandleAsync(query);

    // Assert
    Assert.NotNull(result);
    Assert.True(result.Count() == 1);
    Assert.True(result.FirstOrDefault().Id == new Guid("d4e749ba-6874-40f4-9134-6c9cc1bc95fe"));
}

显然调用.ToListAsync();失败的原因是:

源 IQueryable 未实现 IAsyncEnumerable。只有实现 IAsyncEnumerable 的源才能用于实体框架异步操作。

扩展方法是来自 Entity Framework Core 的方法。

如何将我的客户列表转换为IAsyncEnumerable

作为参考,IEntityReader接口定义如下:

public interface IEntityReader<out TEntity> where TEntity : Entity
{
    IQueryable<TEntity> Query();
}
4

1 回答 1

14

感谢@Nkosi,这是解决方案:

How to mock an async repository with Entity Framework Core with customer list的代码片段:

var customers = new TestAsyncEnumerable<Customer>(new List<Customer>
{
    new Customer
    {
        Id = new Guid("d4e749ba-6874-40f4-9134-6c9cc1bc95fe"),
        Name = "John Doe",
        Age = 18,
        Organization = new Organization
        {
            Id = new Guid("b2ba06c9-5c00-4634-b6f7-80167ea8c3f1"),
            Name = "TheCompany",
            Number = 42
        }
    },
    new Customer
    {
        Id = new Guid("0679ceb5-3d4f-41f3-a1b0-b167e1ac6d7e"),
        Name = "Another Guy",
        Age = 39,
        Organization = new Organization
        {
            Id = new Guid("b2ba06c9-5c00-4634-b6f7-80167ea8c3f1"),
            Name = "TheCompany",
            Number = 42
        }
    }
}.AsQueryable();
于 2016-11-23T12:42:44.363 回答