How can I reset an EF7 InMemory provider between unit tests?

后端 未结 7 1332
忘掉有多难
忘掉有多难 2021-01-31 13:01

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

7条回答
  •  無奈伤痛
    2021-01-31 13:52

    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();
                }
          
        }
    

提交回复
热议问题