我有单位(
XUnit
)测试项目
InMemoryDatabase
public class MyTestDbContext : MyDbContext
{
public static MyTestDbContext CreateTestDbContext()
{
var options = new DbContextOptionsBuilder<MyContext>
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning))
.Options;
var context = new MyTestDbContext(options);
context.EntitySet1.AddRange(...);
context.EntitySet2.AddRange(...);
...
context.SaveChanges();
return context();
}
}
此外,我还有几个单元测试类(
[Fact]
)例如,它使用此上下文
public class MyTests
{
protected readonly MyTestDbContext Context;
protected MyTests()
{
Context = MyTestDbContext.CreateTestDbContext();
}
[Fact]
private async Task MyTest()
{
// some code with Assert CRUD operations with Context
}
}
有什么问题。当我第一次运行测试时(例如,在单元测试proj Clean And Rebuild之后),我得到了失败的随机测试,出现了异常:
System.InvalidOperationException
The entity type 'MyEntity1' was not found. Ensure that the entity type has been added to the model.
...
但当我第二次运行测试时,所有测试都成功通过。
为什么会发生这种情况?如何修复?