Search code examples
unit-testingasp.net-coredbcontext

How to dispose Dbcontext in unit tests


In the following example, only the involved part is displayed.

public class AppTypeTests
{
    private AppDBContext GetContext()
    {
        var options = new DbContextOptionsBuilder<AppDBContext>()
                   .UseInMemoryDatabase(databaseName: "InMemoryDatabase")
                   .Options;
        return new AppDBContext(options);
    }

    [Fact]
    public void Test1()
    {
        using (var context = GetContext())
        {
            var entity = new Entity
            {
                Id = Guid.NewGuid().ToString(),
                Name = "Item1"
            };
            context.Entity.Add(entity);
            context.SaveChanges();
            var dbSet1= context.Entity;
        }
        
    }
    [Fact]
    public void Test2()
    {
        using (var context = GetContext())
        {
            var entity= new Entity
            {
                Id = Guid.NewGuid().ToString(),
                Name = "Item2"
            };
            context.Entity.Add(entity);
            context.SaveChanges();
            var dbSet2 = context.Entity;
        }
    }
}

When I debug, if I check dbSet1 (with test 2 executed in first), I have item1 and item2, dbContext is not disposed.

I have read and tried several things but without success.

What to do to have a clean dbContext for each unit thanks?


Solution

  • You may be disposing of the DbContext, but the InMemoryDatabase is still there with the data.

    If you want a clean database for each test, try this:

    private int dbCount = 0;
    
    private AppDBContext GetContext()
    {
        dbCount++;
        var options = new DbContextOptionsBuilder<AppDBContext>()
                   .UseInMemoryDatabase(databaseName: $"InMemoryDatabase{dbCount}")
                   .Options;
        return new AppDBContext(options);
    }