问题描述
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 等待DbContext.SaveChangesAsync()
。
AddCustomersAsync
test fails, I keep getting a NullReferenceException after calling await DbContext.SaveChangesAsync()
.
在
MasonOgCRM.DataAccess.EF.EntityFrameworkRepository.d__2.MoveNext()
在
C:\\Users\\Mason\\Desktop\\Repositories\\masonogcrm\\src\\DataAccess.EFRepository\\EntityFrameworkRepository.cs:line
43
我看不到任何东西,在我的code空。 的DbContext
不为空。 AddCustomers
的等效试验这是与不是异步除外相同的运行正常。我怀疑我没有在 SetupDBContext()
执行的 SaveChangesAsync
正确的设置,但我不知道该怎么办法进行修复。
I can't see anything that's null in my code. DbContext
is not null. The equivalent test of AddCustomers
which is identical with the exception of not being async runs as expected. I suspect I haven't performed a correct setup of SaveChangesAsync
in SetupDBContext()
but I don't know what to do to fix it.
推荐答案
您是对的出现问题,因为你设置的一个不正确:: dbContext.Setup(C =&GT; c.SaveChangesAsync() ).Verifiable();
You are right the problem occurs because one of your setups incorrect :: dbContext.Setup(c => c.SaveChangesAsync()).Verifiable();
.
该方法返回一个工作
键,你忘了返回工作
因此,空
的回报。
The method return a Task
and you forgot to return a Task
therefore null
returns.
您可以删除 dbContext.Setup(C =&GT; c.SaveChangesAsync())可验证();
或
更改设置来是这样的:
You can remove dbContext.Setup(c => c.SaveChangesAsync()).Verifiable();
or change the setup to something like:
dbContext.Setup(c => c.SaveChangesAsync()).Returns(() => Task.Run(() =>{})).Verifiable();
这篇关于如何MOQ实体框架SaveChangesAsync?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!