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

后端 未结 7 1190
忘掉有多难
忘掉有多难 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:35

    I use a DbContext fixture like the following

    public class DbContextFixture 
        where TDbContext : DbContext
    {
        private readonly DbContextOptions _dbContextOptions = 
            new DbContextOptionsBuilder()
                .UseInMemoryDatabase("_", new InMemoryDatabaseRoot())
                .Options;
    
        public TDbContext CreateDbContext()
        {
            return (TDbContext)(typeof(TDbContext)
                .GetConstructor(new[] { typeof(DbContextOptions) })
                .Invoke(new[] { _dbContextOptions }));
        }
    }
    

    you can now simply do

    public class MyRepositoryTests : IDisposable {
        private SchoolContext _context;
        private DbContextFixture _dbContextFixture;
    
        [TestInitialize]
        public void Setup() {
            _dbContextFixture = new DbContextFixture();
            _context = _dbContextFixture.CreateDbContext();
            _context.Students.AddRange(
                new Student { Id = rng.Next(1,10000), Name = "Able" },
                new Student { Id = rng.Next(1,10000), Name = "Bob" }
            );
            _context.SaveChanges();
        }
    
        [TestCleanup]
        public void Cleanup()
            _context.Dispose();
            _dbContextFixture = null;
        }
    
        [TestMethod]
        public void TestMethod1()
        {
            Assert.AreEqual(2, _context.Students.ToList().Count());
        }
    
        [TestMethod]
        public void TestMethod2()
        {
            Assert.AreEqual(2, _context.Students.ToList().Count());
        }
    }
    

    This solution is thread-safe. See my blog for details.

提交回复
热议问题