3

I'm running some unit tests on an asp.net core 2.0 project, using EF core and an in-memory database.

I'm creating the database like this:

var serviceProvider = new ServiceCollection()
        .AddEntityFrameworkInMemoryDatabase()
        .BuildServiceProvider();
var builder = new DbContextOptionsBuilder<TDatabaseContext>();
builder.UseInMemoryDatabase(Guid.NewGuid().ToString())
    .UseInternalServiceProvider(serviceProvider)
    .EnableSensitiveDataLogging();
var context = new MyDatabaseContext(builder.Options);

According to this post (How to isolate EF InMemory database per XUnit test), using a separate service provider and using a different name for every in-memory DB instance should ensure that each test has its own database which is not shared with other tests.

However, my tests run fine when I run them separately, but fail if I run them all together, with errors like this:

System.InvalidOperationException: The instance of entity type 'SomeModelObject' cannot be tracked because another instance with the key value 'Id:1' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

Is there anything else I should do to make sure that the DB context is not shared among different tests?

Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
  • Can you show sample test? – arekzyla May 16 '18 at 15:11
  • I tried to create a simple project that reproduces the problem, but I'm failing... this behavior seems to be very erratic – Paolo Tedesco May 16 '18 at 15:12
  • A simple test showing how the setup is done and how the test works might help. I don't think the whole project is needed. – arekzyla May 16 '18 at 15:13
  • I don't want to post the whole project, but the problem is that with the simple test the problem is not there :/ – Paolo Tedesco May 16 '18 at 15:15
  • So there must be something else wrong in test not the setup you have shown. The setup should work. – arekzyla May 16 '18 at 15:15
  • Do you have this setup at the beginning of each test? Or is this done in other way? – arekzyla May 16 '18 at 15:19
  • Problem with - how you are using your context and where it is created. Seems like context instance shared between test methods. You can try to move context creation inside every method and check if problem still appear – Fabio May 17 '18 at 00:40

0 Answers0