Unit testing EntityFrameworkCore.InMemory 3.0异常,正在加载
我正在为ASP.NET Core 3.0使用EntityFrameworkCore和EntityFrameworkCore.InMemory 3.0.0-preview8.x。当使用即时加载时,包括导航属性都可以正常工作。但是当涉及到EntityFrameworkCore.InMemory数据库的单元测试时,Include方法会抛出一个异常 代码: 公共异步任务GetAsync(int-id) { 尝试 { 使用(AppContext上下文=this.factory.Create()) { //返回ModuleBinding return wait context.ModuleBinding .Include(x=>x.PostModule) .Include(x=>x.PreModule) .SingleOrDefaultAsync(x=>x.Id==Id) .配置等待(错误); } } 捕获(例外e) { Log.Error($“无法获取id为{id}的实体{nameof(ModuleBinding)}”,e); 投掷; } } 因此,在我的应用程序中使用它时,效果很好 测试:Unit testing EntityFrameworkCore.InMemory 3.0异常,正在加载,unit-testing,asp.net-core,entity-framework-core,in-memory-database,Unit Testing,Asp.net Core,Entity Framework Core,In Memory Database,我正在为ASP.NET Core 3.0使用EntityFrameworkCore和EntityFrameworkCore.InMemory 3.0.0-preview8.x。当使用即时加载时,包括导航属性都可以正常工作。但是当涉及到EntityFrameworkCore.InMemory数据库的单元测试时,Include方法会抛出一个异常 代码: 公共异步任务GetAsync(int-id) { 尝试 { 使用(AppContext上下文=this.factory.Create()) { //
[设置]
公共作废设置()
{
//设置内存中数据库上下文
DbContextOptions=new DbContextOptions Builder().UseInMemoryDatabase(Guid.NewGuid().ToString()).options;
this.context=新的AppContext(选项);
//设置工厂以创建内存中数据库
var factory=A.Fake();
A.CallTo(()=>factory.Create()).Returns(this.context);
//使用内存中的数据库创建存储库。
this.repository=新模块BindingRepository(工厂);
}
[测试]
公共异步任务GetShouldReturnEntity()
{
//安排
int id=this.binding1.id;
//表演
ModuleBinding result=wait this.repository.GetAsync(id).ConfigureWait(false);
//断言
Assert.IsNotNull(结果);
Assert.AreEqual(结果,this.binding1);
}
只要我删除GetAsync方法中的include,测试也可以正常工作。但对于它们,测试抛出以下异常:
System.InvalidOperationException:由于以下原因,操作无效:
对象的当前状态
您知道这是否是EntityFrameworkCore预览版本中的错误吗。InMemory NuGet包,是否有任何打开的线程?或者我可能做错了什么吗?值得一试最新的Preview9(甚至是每日版本),它帮了我的忙,谢谢!
public async Task<ModuleBinding> GetAsync(int id)
{
try
{
using (AppContext context = this.factory.Create())
{
// Return the ModuleBinding
return await context.ModuleBinding
.Include(x => x.PostModule)
.Include(x => x.PreModule)
.SingleOrDefaultAsync(x => x.Id == id)
.ConfigureAwait(false);
}
}
catch (Exception e)
{
Log.Error($"Failed to get entity {nameof(ModuleBinding)} with id {id}.", e);
throw;
}
}
[SetUp]
public void Setup()
{
// Setup the in-memory database context
DbContextOptions<AppContext> options = new DbContextOptionsBuilder<AppContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
this.context = new AppContext(options);
// Setup the factory to create an in-memory database
var factory = A.Fake<IAppContextFactory>();
A.CallTo(() => factory.Create()).Returns(this.context);
// Create repository with in-memory database.
this.repository = new ModuleBindingRepository(factory);
}
[Test]
public async Task GetShouldReturnEntity()
{
// Arrange
int id = this.binding1.Id;
// Act
ModuleBinding result = await this.repository.GetAsync(id).ConfigureAwait(false);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(result, this.binding1);
}