如何修改实体框架SaveChangesAsync

本文关键字:实体 框架 SaveChangesAsync 修改 何修改 | 更新日期: 2023-09-27 18:14:33

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测试失败,我一直得到一个NullReferenceException后调用await DbContext.SaveChangesAsync()

在MasonOgCRM.DataAccess.EF.EntityFrameworkRepository.d__2.MoveNext ()在C:'Users'Mason'Desktop'库' masonogcrm ' src ' DataAccess.EFRepository ' EntityFrameworkRepository.cs:行43

在我的代码中我看不到任何为空的东西。DbContext不为空。AddCustomers的等效测试是相同的,除了不是异步运行。我怀疑我没有在SetupDBContext()中执行SaveChangesAsync的正确设置,但我不知道该怎么做来修复它。

如何修改实体框架SaveChangesAsync

你可以使用

dataContext.Setup(x => x.SaveChangesAsync()).ReturnsAsync(1);

dataContext.Verify(x=>x.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();

这对我有用:

dbContext.Verify(m => m.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once());

它可能还需要一个取消令牌,所以像这样的东西应该可以工作:

dataContext.Setup(x => x.SaveChangesAsync(It.IsAny<CancellationToken>())).ReturnsAsync(1);