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

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

    I would go with a combination of both answers. If tests run in parallel, you could have a database being deleted while you are in the middle of running another test, so I was seeing sporadic failures when running a 30+ tests.

    Give it a random db name, and ensure it gets deleted when the test is completed.

    public class MyRepositoryTests : IDisposable {
      private SchoolContext _context;
    
      [TestInitialize]
      public void Setup() {
        var options = new DbContextOptionsBuilder()
          // Generate a random db name
          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
          .Options;
          _context = new ApplicationDbContext(options);
      }
    
      [TestCleanup]
      public void Cleanup()
        _context.Database.EnsureDeleted(); // Remove from memory
        _context.Dispose();
      }
    }
    

提交回复
热议问题