title: How to moq Entity Framework SaveChangesAsync?
body: <pre><code>Mock&lt;IDbContext&gt; dbContext;
  
  [TestFixtureSetUp]
  public void SetupDbContext()
  {
      dbContext = new Mock&lt;IDbContext&gt;();
      dbContext.Setup(c =&gt; c.SaveChanges()).Verifiable();
      dbContext.Setup(c =&gt; c.SaveChangesAsync()).Verifiable();
      dbContext.Setup(c =&gt; c.Customers.Add(It.IsAny&lt;Customer&gt;()))
               .Returns(It.IsAny&lt;Customer&gt;()).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 =&gt; c.Customers.Add(It.IsAny&lt;Customer&gt;()));
      dbContext.Verify(c =&gt; 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 =&gt; c.Customers.Add(It.IsAny&lt;Customer&gt;()));
      dbContext.Verify(c =&gt; c.SaveChanges());
  }
  </code></pre>
  
  <p>And here's what I want to test:</p>
  
  <pre><code>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();
      }
  }
  </code></pre>
  
  <p><code>AddCustomers</code> test passes.</p>
  
  <p><code>AddCustomersAsync</code> test fails, I keep getting a NullReferenceException after calling <code>await DbContext.SaveChangesAsync()</code>.</p>
  
  <blockquote>
    <p>at
    MasonOgCRM.DataAccess.EF.EntityFrameworkRepository.d__2.MoveNext()
    in
    C:\Users\Mason\Desktop\Repositories\masonogcrm\src\DataAccess.EFRepository\EntityFrameworkRepository.cs:line
    43</p>
  </blockquote>
  
  <p>I can't see anything that's null in my code. <code>DbContext</code> is not null. The equivalent test of <code>AddCustomers</code> which is identical with the exception of not being async runs as expected. I suspect I haven't performed a correct setup of <code>SaveChangesAsync</code> in <code>SetupDBContext()</code> but I don't know what to do to fix it.</p>