EF Core In Memory database data leaking between unit tests

.net-core c# entity-framework-core nunit

Question

I'm trying to mock my EF-Core database by using the in memory provider as described here: https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/in-memory.

I have structured my tests like so:

[Test]
public async Task PerformTest1() {
  var options = new DbContextOptionsBuilder<MeldingenModel>()
    .UseInMemoryDatabase(nameof(PerformTest1))
    .Options;
  var protos = new List<MeldingPrototype> { ... };
  var meldingen = new List<Melding> { ... };
  using (var seedingcontext = new MeldingenModel(options)) {

    seedingcontext.MeldingPrototypes.AddRange(protos);
    seedingcontext.Meldingen.AddRange(meldingen);
    seedingcontext.SaveChanges();
  }
  using (var db = new MeldingenModel(options))
  using (var mock = AutoMock.GetLoose(cgf => cgf.RegisterInstance(db))) {

    // do test
  }
}

The first section is to seed data into the database. Each test has a similar pattern, and each is using nameof(<methodname>) as argument to UseInMemoryDatabase. The way I understand the docstrings on that method, the different string arguments should ensure that all the created databased are separate, but they still seem to be affecting each other. If I run each test in isolation, they all pass, but running them all at once makes them fail. The reason for failure is that seed data from one method is also present during the other tests.

The test-framework I use is nUnit.

Can anyone help me get properly isolated testdatabases?

1
0
4/3/2020 11:46:43 AM

Popular Answer

I tend to do the following to make sure that I really have a separate database for each unit test.

public class MyTestClass
{
  [Test]
  public async Task PerformTest1()
  {
    var options = new DbContextOptionsBuilder<MeldingenModel>()
      .UseInMemoryDatabase($"{ nameof(MyTestClass) }.{ nameof(PerformTest1) }")
      .Options;
  }
}

I see that you already have solved your issue. But still it is good practice to be sure, about the uniqueness of the database names.

Cheers, Mike

1
4/3/2020 1:48:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow