public void SomeMethod(int id)
{
var user = _dbContext.Users.SingleOrDefault(x => x.Id == id);
}
null
当它找不到具有给定
id
但是,在我的单元测试中,我使用InMemory提供程序。当我从单元测试中调用相同的方法时,它会抛出一个异常,告诉我
_dbContext.Users
是
无效的
我知道通过在单元测试中向DbContext添加一个空的用户列表,可以很容易地解决这个问题。但为什么我的“产品”代码中有这种不同呢?
A
DbSet
是
无效的
无效的
否则永远不会发生的例外。。。
我有一个工厂:
public static MyDbContext Create()
{
var options = new DbContextOptionsBuilder<MyDbContext>()
.UseInMemoryDatabase($"{Guid.NewGuid()}")
.Options;
return new MyDbContext(options);
}
在单元测试中,我会:
[Fact]
public void MyTest()
{
var context = InMemoryDbContextFactory.Create();
// Example of how I add things to the DbContext (this works)
context.Roles.Add(new UserRole { Id = 1, Name = "Test" });
context.SaveChanges();
var sut = new SutService(context);
var result = sut.MyMethod();
// Do assert...
}
附言。
我知道我的DbContext没有包装在
using
声明。但即使是这样,我还是会有同样的问题。