I am trying to use the EF7 InMemory provider for unit tests, but the persistent nature of the InMemory database between tests is causing me problems.
The following code d
Here is my 2 cent approach to keep each unit test isolated from each other. I am using C# 7, XUnit and EF core 3.1.
Sample TestFixture class.
public class SampleIntegrationTestFixture : IDisposable
{
public DbContextOptionsBuilder SetupInMemoryDatabase()
=> new DbContextOptionsBuilder().UseInMemoryDatabase("MyInMemoryDatabase");
private IEnumerable CreateStudentStub()
=> new List
{
new Student { Id = rng.Next(1,10000), Name = "Able" },
new Student { Id = rng.Next(1,10000), Name = "Bob" }
};
public void Dispose()
{
}
}
Sample IntegrationTest class
public class SampleJobIntegrationTest : IClassFixture
{
private DbContextOptionsBuilder DbContextBuilder { get; }
private SampleDbContext SampleDbContext { get; set; }
public SampleJobIntegrationTest(SampleIntegrationTestFixture
sampleIntegrationTestFixture )
{
SampleIntegrationTestFixture = sampleIntegrationTestFixture ;
SampleDbContextBuilder = sampleIntegrationTestFixture .SetupInMemoryDatabase();
}
[Fact]
public void TestMethod1()
{
using(SampleDbContext = new SampleDbContext(SampleDbContextBuilder.Options))
var students= SampleIntegrationTestFixture.CreateStudentStub();
{
SampleDbContext.Students.AddRange(students);
SampleDbContext.SaveChanges();
Assert.AreEqual(2, _context.Students.ToList().Count());
SampleDbContext.Database.EnsureDeleted();
}
}