Why DbContext doesn't implement IDbContext interface?

前端 未结 4 861
暖寄归人
暖寄归人 2020-12-24 10:22

Why there is no IDbContext interface in the Entity Framework? Wouldn\'t it be easier to test things if there was an existing interface with methods like SaveCha

4条回答
  •  余生分开走
    2020-12-24 11:08

    Just create a mock DbContext extending your production DbContext overriding the methods that complicate testing. That way, any changes to the production DbContext are automatically reflected in the tests, save for the overridden methods. For any other classes that deal with persistence and take the DbContext just extend them as well passing in the extended mock DbContext.

    namespace Test.Mocks
    {  
        public sealed class MockDatabaseContext : MainProject.Persistence.Database.DatabaseContext
        {
            public MockDatabaseContext(ConfigurationWrapper config) : base(config)
            {
    
            }      
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
    
                var dbPath = "test.db";
                optionsBuilder.UseSqlite($"Filename={dbPath}");
    
    
            }
        }
    }
    
    namespace Test.Mocks
    {
    
        public class MockInventoryFacade : InventoryFacade
        {        
            public MockInventoryFacade(MockDatabaseContext databaseContext) : base(databaseContext)
            {
    
            }    
        }
    }
    

提交回复
热议问题