c# - 如何最小化 Entity Framework SaveChangesAsync?

标签 c# entity-framework unit-testing async-await moq

Mock<IDbContext> dbContext;

[TestFixtureSetUp]
public void SetupDbContext()
{
    dbContext = new Mock<IDbContext>();
    dbContext.Setup(c => c.SaveChanges()).Verifiable();
    dbContext.Setup(c => c.SaveChangesAsync()).Verifiable();
    dbContext.Setup(c => c.Customers.Add(It.IsAny<Customer>()))
             .Returns(It.IsAny<Customer>()).Verifiable();
}

[Test]
public async Task AddCustomerAsync()
{
    //Arrange
    var repository = new EntityFrameworkRepository(dbContext.Object);
    var customer = new Customer() { FirstName = "Larry", LastName = "Hughes" };

    //Act
    await repository.AddCustomerAsync(customer);

    //Assert
    dbContext.Verify(c => c.Customers.Add(It.IsAny<Customer>()));
    dbContext.Verify(c => c.SaveChangesAsync());
}

[Test]
public void AddCustomer()
{
    //Arrange
    var repository = new EntityFrameworkRepository(dbContext.Object);
    var customer = new Customer() { FirstName = "Larry", LastName = "Hughes" };

    //Act
    repository.AddCustomer(customer);

    //Assert
    dbContext.Verify(c => c.Customers.Add(It.IsAny<Customer>()));
    dbContext.Verify(c => c.SaveChanges());
}

这是我要测试的内容:

public class EntityFrameworkRepository
{
    private readonly IDbContext DBContext;

    public EntityFrameworkRepository(IDbContext context)
    {
        DBContext = context;
    }

    public async Task AddCustomerAsync(Customer customer)
    {
        DBContext.Customers.Add(customer);
        await DBContext.SaveChangesAsync();
    }

    public void AddCustomer(Customer customer)
    {
        DBContext.Customers.Add(customer);
        DBContext.SaveChanges();
    }
}

AddCustomers 测试通过。

AddCustomersAsync 测试失败,我在调用 await DbContext.SaveChangesAsync() 后不断收到 NullReferenceException。

at MasonOgCRM.DataAccess.EF.EntityFrameworkRepository.d__2.MoveNext() in C:\Users\Mason\Desktop\Repositories\masonogcrm\src\DataAccess.EFRepository\EntityFrameworkRepository.cs:line 43

我在代码中看不到任何 null。 DbContext 不为空。 AddCustomers 的等效测试与预期相同,只是不是异步运行。我怀疑我没有在 SetupDBContext() 中执行正确的 SaveChangesAsync 设置,但我不知道如何修复它。

最佳答案

你是对的,问题的发生是因为你的设置不正确::dbContext.Setup(c => c.SaveChangesAsync()).Verifiable();.

该方法返回一个 Task,而您忘记返回一个 Task,因此返回 null

您可以删除 dbContext.Setup(c => c.SaveChangesAsync()).Verifiable(); 或 将设置更改为:

dbContext.Setup(c => c.SaveChangesAsync()).Returns(() => Task.Run(() =>{})).Verifiable();

关于c# - 如何最小化 Entity Framework SaveChangesAsync?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793747/

相关文章:

c# - 如何在c#中保存图像流?

c# - 使用 Entity Framework 执行 SQlite 命令

java - Hoverfly仿真模式在单元测试中与Spring Cloud Config Server冲突

entity-framework - 如何在 Entity Framework 中使用事务?

c# - EF 5 更新超时;可能是由于死锁

java - 如何从测试类访问私有(private)方法

python - Django 更新表单的单元测试

c# - Extended Controller 构造函数没有 User 的实例

C# 使用对象按值排序列表

c# - 适合 Unity 的抽象工厂